diff --git a/controllers/accounts/profile.go b/controllers/accounts/profile.go index a29c7f9e4..4cd77a190 100644 --- a/controllers/accounts/profile.go +++ b/controllers/accounts/profile.go @@ -16,7 +16,6 @@ import ( "github.com/paycrest/aggregator/ent/providerfiataccount" "github.com/paycrest/aggregator/ent/providerordertoken" "github.com/paycrest/aggregator/ent/providerprofile" - "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/paycrest/aggregator/ent/senderordertoken" "github.com/paycrest/aggregator/ent/senderprofile" "github.com/paycrest/aggregator/ent/token" @@ -35,15 +34,13 @@ var orderConf = config.OrderConfig() // ProfileController is a controller type for profile settings type ProfileController struct { - apiKeyService *svc.APIKeyService - priorityQueueService *svc.PriorityQueueService + apiKeyService *svc.APIKeyService } // NewProfileController creates a new instance of ProfileController func NewProfileController() *ProfileController { return &ProfileController{ - apiKeyService: svc.NewAPIKeyService(), - priorityQueueService: svc.NewPriorityQueueService(), + apiKeyService: svc.NewAPIKeyService(), } } @@ -666,8 +663,6 @@ func (ctrl *ProfileController) UpdateProviderProfile(ctx *gin.Context) { txUpdate.SetVisibilityMode(providerprofile.VisibilityMode(payload.VisibilityMode)) } - var allBuckets []*ent.ProvisionBucket - // Process all token operations for _, op := range tokenOperations { @@ -731,35 +726,6 @@ func (ctrl *ProfileController) UpdateProviderProfile(ctx *gin.Context) { return } } - - // Collect buckets for this token - convertedMin := op.TokenPayload.MinOrderAmount.Mul(op.Rate) - convertedMax := op.TokenPayload.MaxOrderAmount.Mul(op.Rate) - - buckets, err := tx.ProvisionBucket. - Query(). - Where( - provisionbucket.And( - provisionbucket.HasCurrencyWith(fiatcurrency.IDEQ(op.Currency.ID)), - provisionbucket.MinAmountLTE(convertedMax), // providerMin ≤ bucketMax - provisionbucket.MaxAmountGTE(convertedMin), // providerMax ≥ bucketMin - ), - ). - All(reqCtx) - if err != nil { - if rollbackErr := tx.Rollback(); rollbackErr != nil { - logger.Errorf("Failed to rollback transaction: %v", rollbackErr) - } - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "ProviderID": provider.ID, - "MinAmount": op.TokenPayload.MinOrderAmount, - "MaxAmount": op.TokenPayload.MaxOrderAmount, - }).Errorf("Failed to assign provider to buckets") - u.APIResponse(ctx, http.StatusInternalServerError, "error", "Failed to update profile", nil) - return - } - allBuckets = append(allBuckets, buckets...) } // Process all fiat account operations (same pattern as tokens) @@ -878,26 +844,6 @@ func (ctrl *ProfileController) UpdateProviderProfile(ctx *gin.Context) { } } - // Deduplicate buckets to prevent duplicate many-to-many edges - seenBuckets := make(map[int]bool) - var dedupedBuckets []*ent.ProvisionBucket - for _, bucket := range allBuckets { - if !seenBuckets[bucket.ID] { - seenBuckets[bucket.ID] = true - dedupedBuckets = append(dedupedBuckets, bucket) - } - } - - // Update provider profile with deduplicated buckets - // When Tokens field is present, always clear existing buckets first - if payload.Tokens != nil { - txUpdate.ClearProvisionBuckets() - // Only add buckets if there are any matches - if len(dedupedBuckets) > 0 { - txUpdate.AddProvisionBuckets(dedupedBuckets...) - } - } - // Save provider profile update within the transaction _, err = txUpdate.Save(reqCtx) if err != nil { diff --git a/controllers/index.go b/controllers/index.go index 97e71fb8d..75e7cbfc3 100644 --- a/controllers/index.go +++ b/controllers/index.go @@ -33,6 +33,7 @@ import ( tokenEnt "github.com/paycrest/aggregator/ent/token" "github.com/paycrest/aggregator/ent/user" svc "github.com/paycrest/aggregator/services" + "github.com/paycrest/aggregator/services/assignment" "github.com/paycrest/aggregator/services/common" "github.com/paycrest/aggregator/services/email" explorer "github.com/paycrest/aggregator/services/explorer" @@ -61,7 +62,7 @@ var orderConf = config.OrderConfig() // Controller is the default controller for other endpoints type Controller struct { orderService types.OrderService - priorityQueueService *svc.PriorityQueueService + priorityQueueService *assignment.Service receiveAddressService *svc.ReceiveAddressService kycService types.KYCProvider slackService *svc.SlackService @@ -77,7 +78,7 @@ func NewController() *Controller { return &Controller{ orderService: orderSvc.NewOrderEVM(), - priorityQueueService: svc.NewPriorityQueueService(), + priorityQueueService: assignment.New(), receiveAddressService: svc.NewReceiveAddressService(), kycService: smile.NewSmileIDService(), slackService: svc.NewSlackService(serverConf.SlackWebhookURL), diff --git a/controllers/provider/provider.go b/controllers/provider/provider.go index 81989ff06..45e006cb8 100644 --- a/controllers/provider/provider.go +++ b/controllers/provider/provider.go @@ -33,6 +33,7 @@ import ( "github.com/paycrest/aggregator/ent/token" "github.com/paycrest/aggregator/ent/transactionlog" "github.com/paycrest/aggregator/services" + "github.com/paycrest/aggregator/services/assignment" "github.com/paycrest/aggregator/services/balance" "github.com/paycrest/aggregator/services/contracts" orderService "github.com/paycrest/aggregator/services/order" @@ -448,9 +449,6 @@ func (ctrl *ProviderController) handleExportPaymentOrders(ctx *gin.Context, prov WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() }). - WithProvisionBucket(func(pbq *ent.ProvisionBucketQuery) { - pbq.WithCurrency() - }). Limit(maxExportLimit). Order(ent.Desc(paymentorder.FieldCreatedAt), ent.Desc(paymentorder.FieldID)). All(reqCtx) @@ -525,8 +523,10 @@ func (ctrl *ProviderController) handleExportPaymentOrders(ctx *gin.Context, prov } var currencyCode string - if paymentOrder.Edges.ProvisionBucket != nil && paymentOrder.Edges.ProvisionBucket.Edges.Currency != nil { - currencyCode = paymentOrder.Edges.ProvisionBucket.Edges.Currency.Code + if paymentOrder.Institution != "" { + if inst, ierr := u.GetInstitutionByCode(reqCtx, paymentOrder.Institution, true); ierr == nil && inst != nil && inst.Edges.FiatCurrency != nil { + currencyCode = inst.Edges.FiatCurrency.Code + } } row := []string{ @@ -590,7 +590,6 @@ func (ctrl *ProviderController) AcceptOrder(ctx *gin.Context) { WithProvider(). WithSenderProfile(). WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() }). - WithProvisionBucket(func(pbq *ent.ProvisionBucketQuery) { pbq.WithCurrency() }). Only(reqCtx) if fallbackErr != nil || fallbackOrder == nil { if fallbackErr != nil && !ent.IsNotFound(fallbackErr) { @@ -628,9 +627,7 @@ func (ctrl *ProviderController) AcceptOrder(ctx *gin.Context) { } if fallbackOrder.Direction == paymentorder.DirectionOnramp { result["amount"] = fallbackOrder.Amount.Add(fallbackOrder.SenderFee).Mul(fallbackOrder.Rate).RoundBank(0).String() - if fallbackOrder.Edges.ProvisionBucket != nil && fallbackOrder.Edges.ProvisionBucket.Edges.Currency != nil { - result["currency"] = fallbackOrder.Edges.ProvisionBucket.Edges.Currency.Code - } else if fallbackOrder.Institution != "" { + if fallbackOrder.Institution != "" { inst, instErr := u.GetInstitutionByCode(reqCtx, fallbackOrder.Institution, true) if instErr == nil && inst != nil && inst.Edges.FiatCurrency != nil { result["currency"] = inst.Edges.FiatCurrency.Code @@ -1159,9 +1156,6 @@ func (ctrl *ProviderController) FulfillOrder(ctx *gin.Context) { tq.WithNetwork() }) poq.WithProvider() - poq.WithProvisionBucket(func(pbq *ent.ProvisionBucketQuery) { - pbq.WithCurrency() - }) }). Only(reqCtx) if err != nil { @@ -1214,9 +1208,7 @@ func (ctrl *ProviderController) FulfillOrder(ctx *gin.Context) { WithOrder(func(poq *ent.PaymentOrderQuery) { poq.WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() - }).WithProvider().WithProvisionBucket(func(pbq *ent.ProvisionBucketQuery) { - pbq.WithCurrency() - }) + }).WithProvider() }). Only(reqCtx) if err != nil { @@ -1408,10 +1400,7 @@ func (ctrl *ProviderController) handlePayoutFulfillment(ctx *gin.Context, orderI } providerID := fulfillment.Edges.Order.Edges.Provider.ID currency := "" - if fulfillment.Edges.Order.Edges.ProvisionBucket != nil && fulfillment.Edges.Order.Edges.ProvisionBucket.Edges.Currency != nil { - currency = fulfillment.Edges.Order.Edges.ProvisionBucket.Edges.Currency.Code - } - if currency == "" && fulfillment.Edges.Order.Institution != "" { + if fulfillment.Edges.Order.Institution != "" { inst, instErr := u.GetInstitutionByCode(reqCtx, fulfillment.Edges.Order.Institution, true) if instErr == nil && inst != nil && inst.Edges.FiatCurrency != nil { currency = inst.Edges.FiatCurrency.Code @@ -1421,8 +1410,8 @@ func (ctrl *ProviderController) handlePayoutFulfillment(ctx *gin.Context, orderI logger.WithFields(logger.Fields{ "OrderID": orderID.String(), "TxID": payload.TxID, - }).Errorf("FulfillOrder: order missing provision bucket and could not resolve currency from institution") - u.APIResponse(ctx, http.StatusInternalServerError, "error", "Order missing provider or provision bucket", nil) + }).Errorf("FulfillOrder: could not resolve fiat currency from institution") + u.APIResponse(ctx, http.StatusInternalServerError, "error", "Order missing provider or institution currency", nil) _ = tx.Rollback() return } @@ -1463,6 +1452,10 @@ func (ctrl *ProviderController) handlePayoutFulfillment(ctx *gin.Context, orderI return } + if scoreErr := assignment.ApplyProviderScoreChange(reqCtx, orderID, assignment.ScoreEventFulfilledValidated, decimal.NewFromFloat(assignment.RewardFulfilledValidated)); scoreErr != nil { + logger.WithFields(logger.Fields{"OrderID": orderID.String(), "Error": scoreErr.Error()}).Warnf("FulfillOrder: score reward") + } + // Clean up order exclude list from Redis (best effort, don't fail if it errors) orderKey := fmt.Sprintf("order_exclude_list_%s", orderID) _ = storage.RedisClient.Del(reqCtx, orderKey).Err() @@ -1549,10 +1542,7 @@ func (ctrl *ProviderController) handlePayoutFulfillment(ctx *gin.Context, orderI } providerID := fulfillment.Edges.Order.Edges.Provider.ID currency := "" - if fulfillment.Edges.Order.Edges.ProvisionBucket != nil && fulfillment.Edges.Order.Edges.ProvisionBucket.Edges.Currency != nil { - currency = fulfillment.Edges.Order.Edges.ProvisionBucket.Edges.Currency.Code - } - if currency == "" && fulfillment.Edges.Order.Institution != "" { + if fulfillment.Edges.Order.Institution != "" { inst, instErr := u.GetInstitutionByCode(reqCtx, fulfillment.Edges.Order.Institution, true) if instErr == nil && inst != nil && inst.Edges.FiatCurrency != nil { currency = inst.Edges.FiatCurrency.Code @@ -1562,7 +1552,7 @@ func (ctrl *ProviderController) handlePayoutFulfillment(ctx *gin.Context, orderI logger.WithFields(logger.Fields{ "OrderID": orderID.String(), "TxID": payload.TxID, - }).Errorf("FulfillOrder: order missing provision bucket and could not resolve currency from institution") + }).Errorf("FulfillOrder: could not resolve fiat currency from institution") return } amount := fulfillment.Edges.Order.Amount.Mul(fulfillment.Edges.Order.Rate).RoundBank(0) @@ -1578,6 +1568,9 @@ func (ctrl *ProviderController) handlePayoutFulfillment(ctx *gin.Context, orderI }).Errorf("failed to release reserved balance for failed validation") // Don't return error here as the order status is already updated } + if scoreErr := assignment.ApplyProviderScoreChange(reqCtx, orderID, assignment.ScoreEventValidationFailed, decimal.NewFromFloat(assignment.PenaltyValidationFailed)); scoreErr != nil { + logger.WithFields(logger.Fields{"OrderID": orderID.String(), "Error": scoreErr.Error()}).Warnf("FulfillOrder: score validation failed penalty") + } default: // Create log and update order in one transaction so the log is never orphaned @@ -1791,6 +1784,9 @@ func (ctrl *ProviderController) handlePayinFulfillment(ctx *gin.Context, orderID logger.Errorf("Failed to release token balance for payin validation failure (order %s): %v", orderID, relErr) } } + if scoreErr := assignment.ApplyProviderScoreChange(reqCtx, orderID, assignment.ScoreEventValidationFailed, decimal.NewFromFloat(assignment.PenaltyValidationFailed)); scoreErr != nil { + logger.WithFields(logger.Fields{"OrderID": orderID.String(), "Error": scoreErr.Error()}).Warnf("FulfillOrder payin: score validation failed penalty") + } u.APIResponse(ctx, http.StatusOK, "success", "Fulfillment validation failed", nil) return case paymentorderfulfillment.ValidationStatusSuccess: @@ -2024,6 +2020,10 @@ func (ctrl *ProviderController) handlePayinFulfillment(ctx *gin.Context, orderID return } + if scoreErr := assignment.ApplyProviderScoreChange(reqCtx, orderID, assignment.ScoreEventFulfilledValidated, decimal.NewFromFloat(assignment.RewardFulfilledValidated)); scoreErr != nil { + logger.WithFields(logger.Fields{"OrderID": orderID.String(), "Error": scoreErr.Error()}).Warnf("FulfillOrder payin: score reward") + } + u.APIResponse(ctx, http.StatusOK, "success", "Order submitted for settlement", nil) } @@ -2358,9 +2358,6 @@ func (ctrl *ProviderController) CancelOrder(ctx *gin.Context) { tq.WithNetwork() }). WithProvider(). - WithProvisionBucket(func(pbq *ent.ProvisionBucketQuery) { - pbq.WithCurrency() - }). Only(reqCtx) if err != nil { logger.WithFields(logger.Fields{ @@ -2381,49 +2378,8 @@ func (ctrl *ProviderController) CancelOrder(ctx *gin.Context) { } else if payload.Reason != "Insufficient funds" { cancellationCount += 1 orderUpdate.AppendCancellationReasons([]string{payload.Reason}) - } else if payload.Reason == "Insufficient funds" && order.Edges.ProvisionBucket != nil && order.Edges.ProvisionBucket.Edges.Currency != nil { - // Search for the specific provider in the queue using a Redis list (private orders with nil bucket are not in the queue) - redisKey := fmt.Sprintf("bucket_%s_%s_%s", order.Edges.ProvisionBucket.Edges.Currency.Code, order.Edges.ProvisionBucket.MinAmount, order.Edges.ProvisionBucket.MaxAmount) - - // Check if the provider ID exists in the list - for index := -1; ; index-- { - providerData, err := storage.RedisClient.LIndex(reqCtx, redisKey, int64(index)).Result() - if err != nil { - break - } - - // Extract the id from the data (format "providerID:token:network:rate:minAmount:maxAmount") - parts := strings.Split(providerData, ":") - if len(parts) != 6 { - logger.WithFields(logger.Fields{ - "Provider Data": providerData, - }).Error("Invalid provider data format") - continue // Skip this entry due to invalid format - } - - if parts[0] == provider.ID { - // Remove the provider from the list - placeholder := "DELETED_PROVIDER" // Define a placeholder value - _, err := storage.RedisClient.LSet(reqCtx, redisKey, int64(index), placeholder).Result() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Index": index, - }).Errorf("Failed to set placeholder at index %d: %v", index, err) - } - - // Remove all occurences of the placeholder from the list - _, err = storage.RedisClient.LRem(reqCtx, redisKey, 0, placeholder).Result() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Placeholder": placeholder, - }).Errorf("Failed to remove placeholder from circular queue: %v", err) - } - - break - } - } + } else if payload.Reason == "Insufficient funds" { + orderUpdate.AppendCancellationReasons([]string{payload.Reason}) } // Update order status to cancelled @@ -2447,10 +2403,7 @@ func (ctrl *ProviderController) CancelOrder(ctx *gin.Context) { // Release reserved balance for this cancelled order providerID := order.Edges.Provider.ID currency := "" - if order.Edges.ProvisionBucket != nil && order.Edges.ProvisionBucket.Edges.Currency != nil { - currency = order.Edges.ProvisionBucket.Edges.Currency.Code - } - if currency == "" && order.Institution != "" { + if order.Institution != "" { inst, instErr := u.GetInstitutionByCode(reqCtx, order.Institution, true) if instErr == nil && inst != nil && inst.Edges.FiatCurrency != nil { currency = inst.Edges.FiatCurrency.Code @@ -2490,6 +2443,17 @@ func (ctrl *ProviderController) CancelOrder(ctx *gin.Context) { logger.Errorf("error setting TTL for order %s exclude_list on Redis: %v", orderID, err) } + switch { + case payload.Reason == "Insufficient funds": + if scoreErr := assignment.ApplyProviderScoreChange(reqCtx, orderID, assignment.ScoreEventCancelInsufficientFunds, decimal.NewFromFloat(assignment.PenaltyCancelInsufficientFunds)); scoreErr != nil { + logger.WithFields(logger.Fields{"OrderID": orderID.String(), "Error": scoreErr.Error()}).Warnf("CancelOrder: score insufficient funds penalty") + } + case assignment.IsProviderFaultCancelReason(payload.Reason): + if scoreErr := assignment.ApplyProviderScoreChange(reqCtx, orderID, assignment.ScoreEventCancelProviderFault, decimal.NewFromFloat(assignment.PenaltyCancelProviderFault)); scoreErr != nil { + logger.WithFields(logger.Fields{"OrderID": orderID.String(), "Error": scoreErr.Error()}).Warnf("CancelOrder: score provider-fault penalty") + } + } + u.APIResponse(ctx, http.StatusOK, "success", "Order cancelled successfully", nil) } diff --git a/controllers/provider/provider_test.go b/controllers/provider/provider_test.go index d20074380..6867ad079 100644 --- a/controllers/provider/provider_test.go +++ b/controllers/provider/provider_test.go @@ -1621,20 +1621,6 @@ func TestProvider(t *testing.T) { }) assert.NoError(t, err) - // Create a provision bucket for the order - provisionBucket, err := db.Client.ProvisionBucket. - Create(). - SetMinAmount(decimal.NewFromFloat(100.0)). - SetMaxAmount(decimal.NewFromFloat(1000.0)). - SetCurrency(testCtx.currency). - Save(context.Background()) - assert.NoError(t, err) - - order, err = order.Update(). - SetProvisionBucket(provisionBucket). - Save(context.Background()) - assert.NoError(t, err) - orderKey := fmt.Sprintf("order_request_%s", order.ID) user, err := test.CreateTestUser(map[string]interface{}{ @@ -1688,20 +1674,6 @@ func TestProvider(t *testing.T) { }) assert.NoError(t, err) - // Create a provision bucket for the order - provisionBucket, err := db.Client.ProvisionBucket. - Create(). - SetMinAmount(decimal.NewFromFloat(100.0)). - SetMaxAmount(decimal.NewFromFloat(1000.0)). - SetCurrency(testCtx.currency). - Save(context.Background()) - assert.NoError(t, err) - - order, err = order.Update(). - SetProvisionBucket(provisionBucket). - Save(context.Background()) - assert.NoError(t, err) - orderKey := fmt.Sprintf("order_request_%s", order.ID) orderRequestData := map[string]interface{}{ @@ -1909,19 +1881,6 @@ func TestProvider(t *testing.T) { }) assert.NoError(t, err) - // Create a provision bucket and associate it with the order - provisionBucket, err := test.CreateTestProvisionBucket(map[string]interface{}{ - "currency_id": testCtx.currency.ID, - "provider_id": testCtx.provider.ID, - "max_amount": decimal.NewFromFloat(1000.0), - "min_amount": decimal.NewFromFloat(1.0), - }) - assert.NoError(t, err) - - // Associate the provision bucket with the order - order, err = test.AddProvisionBucketToPaymentOrder(order, provisionBucket.ID) - assert.NoError(t, err) - tx_id := "0x123" + fmt.Sprint(rand.Intn(1000000)) _, err = test.CreateTestPaymentOrderFulfillment(map[string]interface{}{ "tx_id": tx_id, diff --git a/controllers/sender/sender_test.go b/controllers/sender/sender_test.go index 1ad02b183..6d55104bb 100644 --- a/controllers/sender/sender_test.go +++ b/controllers/sender/sender_test.go @@ -121,7 +121,7 @@ func setup() error { } // Create ProviderOrderToken for rate validation (Redis queue uses 750; NGN/NGN direct match normalizes ValidateRate to 1, matching payload rate "1") - providerOrderToken, err := test.AddProviderOrderTokenToProvider(map[string]interface{}{ + _, err = test.AddProviderOrderTokenToProvider(map[string]interface{}{ "provider": providerProfile, "token_id": int(tokenId), "currency_id": currency.ID, @@ -138,18 +138,6 @@ func setup() error { return fmt.Errorf("AddProviderOrderTokenToProvider.sender_test: %w", err) } - // Create ProvisionBucket for bucket-based rate validation - // Bucket range accommodates fiat notionally from queue rate (e.g. 100 * 750); initiation uses direct-match rate 1 - bucket, err := test.CreateTestProvisionBucket(map[string]interface{}{ - "provider_id": providerProfile.ID, - "currency_id": currency.ID, - "min_amount": decimal.NewFromFloat(1.0), - "max_amount": decimal.NewFromFloat(100000.0), - }) - if err != nil { - return fmt.Errorf("CreateTestProvisionBucket.sender_test: %w", err) - } - _, err = db.Client.ProviderBalances.Update(). Where( providerbalances.HasProviderWith(providerprofile.IDEQ(providerProfile.ID)), @@ -163,21 +151,6 @@ func setup() error { return fmt.Errorf("UpdateProviderBalances.sender_test: %w", err) } - // Populate Redis bucket with provider data for validateBucketRate - redisKey := fmt.Sprintf("bucket_%s_%s_%s_sell", currency.Code, bucket.MinAmount, bucket.MaxAmount) - providerData := fmt.Sprintf("%s:%s:%s:%s:%s:%s", - providerProfile.ID, - token.Symbol, - providerOrderToken.Network, - providerOrderToken.FixedSellRate.String(), - providerOrderToken.MinOrderAmount.String(), - providerOrderToken.MaxOrderAmount.String(), - ) - err = db.RedisClient.RPush(context.Background(), redisKey, providerData).Err() - if err != nil { - return fmt.Errorf("PopulateRedisBucket.sender_test: %w", err) - } - senderProfile, err := test.CreateTestSenderProfile(map[string]interface{}{ "user_id": user.ID, "fee_percent": "5", @@ -255,18 +228,7 @@ func setup() error { if err != nil { return fmt.Errorf("AddProviderOrderTokenNative.sender_test: %w", err) } - nativeProviderData := fmt.Sprintf("%s:%s:%s:%s:%s:%s", - providerProfile.ID, - testCtx.nativeTokenSymbol, - nativeProviderOrderToken.Network, - nativeProviderOrderToken.FixedSellRate.String(), - nativeProviderOrderToken.MinOrderAmount.String(), - nativeProviderOrderToken.MaxOrderAmount.String(), - ) - err = db.RedisClient.RPush(context.Background(), redisKey, nativeProviderData).Err() - if err != nil { - return fmt.Errorf("PopulateRedisBucketNative.sender_test: %w", err) - } + _ = nativeProviderOrderToken _, err = db.Client.SenderOrderToken. Create(). SetSenderID(senderProfile.ID). @@ -794,19 +756,13 @@ func TestSender(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, providerOrderToken, "Provider order token should be created") - // Create ProvisionBucket for bucket-based rate validation - // Bucket range accommodates fiat notionally from queue rate (e.g. 100 * 750); initiation uses direct-match rate 1 - bucket, err := test.CreateTestProvisionBucket(map[string]interface{}{ - "provider_id": providerProfile.ID, - "currency_id": currency.ID, - "min_amount": decimal.NewFromFloat(1.0), - "max_amount": decimal.NewFromFloat(100000.0), - }) - assert.NoError(t, err) + // Redis bucket key min/max (legacy queue shape; no DB provision bucket in Phase 1 tests) + testRedisBucketMin := decimal.NewFromFloat(1.0) + testRedisBucketMax := decimal.NewFromFloat(100000.0) // Populate Redis bucket with provider data for validateBucketRate // In floating-rate tests, approximate current provider rate using fixed_sell_rate for deterministic behavior - redisKey := fmt.Sprintf("bucket_%s_%s_%s_sell", currency.Code, bucket.MinAmount, bucket.MaxAmount) + redisKey := fmt.Sprintf("bucket_%s_%s_%s_sell", currency.Code, testRedisBucketMin, testRedisBucketMax) providerData := fmt.Sprintf("%s:%s:%s:%s:%s:%s", providerProfile.ID, testCtx.token.Symbol, @@ -981,18 +937,11 @@ func TestSender(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, providerOrderToken, "Provider order token should be created") - // Create ProvisionBucket for bucket-based rate validation - // Bucket range accommodates fiat notionally from queue rate (e.g. 100 * 750); initiation uses direct-match rate 1 - bucket, err := test.CreateTestProvisionBucket(map[string]interface{}{ - "provider_id": providerProfile.ID, - "currency_id": currency.ID, - "min_amount": decimal.NewFromFloat(1.0), - "max_amount": decimal.NewFromFloat(100000.0), - }) - assert.NoError(t, err) + testRedisBucketMin := decimal.NewFromFloat(1.0) + testRedisBucketMax := decimal.NewFromFloat(100000.0) // Populate Redis bucket with provider data for validateBucketRate - redisKey := fmt.Sprintf("bucket_%s_%s_%s_sell", currency.Code, bucket.MinAmount, bucket.MaxAmount) + redisKey := fmt.Sprintf("bucket_%s_%s_%s_sell", currency.Code, testRedisBucketMin, testRedisBucketMax) providerData := fmt.Sprintf("%s:%s:%s:%s:%s:%s", providerProfile.ID, testCtx.token.Symbol, @@ -1167,18 +1116,11 @@ func TestSender(t *testing.T) { assert.NoError(t, err) assert.NotNil(t, providerOrderToken, "Provider order token should be created") - // Create ProvisionBucket for bucket-based rate validation - // Bucket range accommodates fiat notionally from queue rate (e.g. 100 * 750); initiation uses direct-match rate 1 - bucket, err := test.CreateTestProvisionBucket(map[string]interface{}{ - "provider_id": providerProfile.ID, - "currency_id": currency.ID, - "min_amount": decimal.NewFromFloat(1.0), - "max_amount": decimal.NewFromFloat(100000.0), - }) - assert.NoError(t, err) + testRedisBucketMin := decimal.NewFromFloat(1.0) + testRedisBucketMax := decimal.NewFromFloat(100000.0) // Populate Redis bucket with provider data for validateBucketRate - redisKey := fmt.Sprintf("bucket_%s_%s_%s_sell", currency.Code, bucket.MinAmount, bucket.MaxAmount) + redisKey := fmt.Sprintf("bucket_%s_%s_%s_sell", currency.Code, testRedisBucketMin, testRedisBucketMax) providerData := fmt.Sprintf("%s:%s:%s:%s:%s:%s", providerProfile.ID, testCtx.token.Symbol, diff --git a/ent/client.go b/ent/client.go index 09cb4d9fe..fef2f3337 100644 --- a/ent/client.go +++ b/ent/client.go @@ -26,9 +26,11 @@ import ( "github.com/paycrest/aggregator/ent/paymentorder" "github.com/paycrest/aggregator/ent/paymentorderfulfillment" "github.com/paycrest/aggregator/ent/paymentwebhook" + "github.com/paycrest/aggregator/ent/providerassignmentrun" "github.com/paycrest/aggregator/ent/providerbalances" "github.com/paycrest/aggregator/ent/providerfiataccount" "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/providerrating" "github.com/paycrest/aggregator/ent/provisionbucket" @@ -66,12 +68,16 @@ type Client struct { PaymentOrderFulfillment *PaymentOrderFulfillmentClient // PaymentWebhook is the client for interacting with the PaymentWebhook builders. PaymentWebhook *PaymentWebhookClient + // ProviderAssignmentRun is the client for interacting with the ProviderAssignmentRun builders. + ProviderAssignmentRun *ProviderAssignmentRunClient // ProviderBalances is the client for interacting with the ProviderBalances builders. ProviderBalances *ProviderBalancesClient // ProviderFiatAccount is the client for interacting with the ProviderFiatAccount builders. ProviderFiatAccount *ProviderFiatAccountClient // ProviderOrderToken is the client for interacting with the ProviderOrderToken builders. ProviderOrderToken *ProviderOrderTokenClient + // ProviderOrderTokenScoreHistory is the client for interacting with the ProviderOrderTokenScoreHistory builders. + ProviderOrderTokenScoreHistory *ProviderOrderTokenScoreHistoryClient // ProviderProfile is the client for interacting with the ProviderProfile builders. ProviderProfile *ProviderProfileClient // ProviderRating is the client for interacting with the ProviderRating builders. @@ -113,9 +119,11 @@ func (c *Client) init() { c.PaymentOrder = NewPaymentOrderClient(c.config) c.PaymentOrderFulfillment = NewPaymentOrderFulfillmentClient(c.config) c.PaymentWebhook = NewPaymentWebhookClient(c.config) + c.ProviderAssignmentRun = NewProviderAssignmentRunClient(c.config) c.ProviderBalances = NewProviderBalancesClient(c.config) c.ProviderFiatAccount = NewProviderFiatAccountClient(c.config) c.ProviderOrderToken = NewProviderOrderTokenClient(c.config) + c.ProviderOrderTokenScoreHistory = NewProviderOrderTokenScoreHistoryClient(c.config) c.ProviderProfile = NewProviderProfileClient(c.config) c.ProviderRating = NewProviderRatingClient(c.config) c.ProvisionBucket = NewProvisionBucketClient(c.config) @@ -216,31 +224,33 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { cfg := c.config cfg.driver = tx return &Tx{ - ctx: ctx, - config: cfg, - APIKey: NewAPIKeyClient(cfg), - BeneficialOwner: NewBeneficialOwnerClient(cfg), - FiatCurrency: NewFiatCurrencyClient(cfg), - IdentityVerificationRequest: NewIdentityVerificationRequestClient(cfg), - Institution: NewInstitutionClient(cfg), - KYBProfile: NewKYBProfileClient(cfg), - Network: NewNetworkClient(cfg), - PaymentOrder: NewPaymentOrderClient(cfg), - PaymentOrderFulfillment: NewPaymentOrderFulfillmentClient(cfg), - PaymentWebhook: NewPaymentWebhookClient(cfg), - ProviderBalances: NewProviderBalancesClient(cfg), - ProviderFiatAccount: NewProviderFiatAccountClient(cfg), - ProviderOrderToken: NewProviderOrderTokenClient(cfg), - ProviderProfile: NewProviderProfileClient(cfg), - ProviderRating: NewProviderRatingClient(cfg), - ProvisionBucket: NewProvisionBucketClient(cfg), - SenderOrderToken: NewSenderOrderTokenClient(cfg), - SenderProfile: NewSenderProfileClient(cfg), - Token: NewTokenClient(cfg), - TransactionLog: NewTransactionLogClient(cfg), - User: NewUserClient(cfg), - VerificationToken: NewVerificationTokenClient(cfg), - WebhookRetryAttempt: NewWebhookRetryAttemptClient(cfg), + ctx: ctx, + config: cfg, + APIKey: NewAPIKeyClient(cfg), + BeneficialOwner: NewBeneficialOwnerClient(cfg), + FiatCurrency: NewFiatCurrencyClient(cfg), + IdentityVerificationRequest: NewIdentityVerificationRequestClient(cfg), + Institution: NewInstitutionClient(cfg), + KYBProfile: NewKYBProfileClient(cfg), + Network: NewNetworkClient(cfg), + PaymentOrder: NewPaymentOrderClient(cfg), + PaymentOrderFulfillment: NewPaymentOrderFulfillmentClient(cfg), + PaymentWebhook: NewPaymentWebhookClient(cfg), + ProviderAssignmentRun: NewProviderAssignmentRunClient(cfg), + ProviderBalances: NewProviderBalancesClient(cfg), + ProviderFiatAccount: NewProviderFiatAccountClient(cfg), + ProviderOrderToken: NewProviderOrderTokenClient(cfg), + ProviderOrderTokenScoreHistory: NewProviderOrderTokenScoreHistoryClient(cfg), + ProviderProfile: NewProviderProfileClient(cfg), + ProviderRating: NewProviderRatingClient(cfg), + ProvisionBucket: NewProvisionBucketClient(cfg), + SenderOrderToken: NewSenderOrderTokenClient(cfg), + SenderProfile: NewSenderProfileClient(cfg), + Token: NewTokenClient(cfg), + TransactionLog: NewTransactionLogClient(cfg), + User: NewUserClient(cfg), + VerificationToken: NewVerificationTokenClient(cfg), + WebhookRetryAttempt: NewWebhookRetryAttemptClient(cfg), }, nil } @@ -258,31 +268,33 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) cfg := c.config cfg.driver = &txDriver{tx: tx, drv: c.driver} return &Tx{ - ctx: ctx, - config: cfg, - APIKey: NewAPIKeyClient(cfg), - BeneficialOwner: NewBeneficialOwnerClient(cfg), - FiatCurrency: NewFiatCurrencyClient(cfg), - IdentityVerificationRequest: NewIdentityVerificationRequestClient(cfg), - Institution: NewInstitutionClient(cfg), - KYBProfile: NewKYBProfileClient(cfg), - Network: NewNetworkClient(cfg), - PaymentOrder: NewPaymentOrderClient(cfg), - PaymentOrderFulfillment: NewPaymentOrderFulfillmentClient(cfg), - PaymentWebhook: NewPaymentWebhookClient(cfg), - ProviderBalances: NewProviderBalancesClient(cfg), - ProviderFiatAccount: NewProviderFiatAccountClient(cfg), - ProviderOrderToken: NewProviderOrderTokenClient(cfg), - ProviderProfile: NewProviderProfileClient(cfg), - ProviderRating: NewProviderRatingClient(cfg), - ProvisionBucket: NewProvisionBucketClient(cfg), - SenderOrderToken: NewSenderOrderTokenClient(cfg), - SenderProfile: NewSenderProfileClient(cfg), - Token: NewTokenClient(cfg), - TransactionLog: NewTransactionLogClient(cfg), - User: NewUserClient(cfg), - VerificationToken: NewVerificationTokenClient(cfg), - WebhookRetryAttempt: NewWebhookRetryAttemptClient(cfg), + ctx: ctx, + config: cfg, + APIKey: NewAPIKeyClient(cfg), + BeneficialOwner: NewBeneficialOwnerClient(cfg), + FiatCurrency: NewFiatCurrencyClient(cfg), + IdentityVerificationRequest: NewIdentityVerificationRequestClient(cfg), + Institution: NewInstitutionClient(cfg), + KYBProfile: NewKYBProfileClient(cfg), + Network: NewNetworkClient(cfg), + PaymentOrder: NewPaymentOrderClient(cfg), + PaymentOrderFulfillment: NewPaymentOrderFulfillmentClient(cfg), + PaymentWebhook: NewPaymentWebhookClient(cfg), + ProviderAssignmentRun: NewProviderAssignmentRunClient(cfg), + ProviderBalances: NewProviderBalancesClient(cfg), + ProviderFiatAccount: NewProviderFiatAccountClient(cfg), + ProviderOrderToken: NewProviderOrderTokenClient(cfg), + ProviderOrderTokenScoreHistory: NewProviderOrderTokenScoreHistoryClient(cfg), + ProviderProfile: NewProviderProfileClient(cfg), + ProviderRating: NewProviderRatingClient(cfg), + ProvisionBucket: NewProvisionBucketClient(cfg), + SenderOrderToken: NewSenderOrderTokenClient(cfg), + SenderProfile: NewSenderProfileClient(cfg), + Token: NewTokenClient(cfg), + TransactionLog: NewTransactionLogClient(cfg), + User: NewUserClient(cfg), + VerificationToken: NewVerificationTokenClient(cfg), + WebhookRetryAttempt: NewWebhookRetryAttemptClient(cfg), }, nil } @@ -314,10 +326,11 @@ func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ c.APIKey, c.BeneficialOwner, c.FiatCurrency, c.IdentityVerificationRequest, c.Institution, c.KYBProfile, c.Network, c.PaymentOrder, - c.PaymentOrderFulfillment, c.PaymentWebhook, c.ProviderBalances, - c.ProviderFiatAccount, c.ProviderOrderToken, c.ProviderProfile, - c.ProviderRating, c.ProvisionBucket, c.SenderOrderToken, c.SenderProfile, - c.Token, c.TransactionLog, c.User, c.VerificationToken, c.WebhookRetryAttempt, + c.PaymentOrderFulfillment, c.PaymentWebhook, c.ProviderAssignmentRun, + c.ProviderBalances, c.ProviderFiatAccount, c.ProviderOrderToken, + c.ProviderOrderTokenScoreHistory, c.ProviderProfile, c.ProviderRating, + c.ProvisionBucket, c.SenderOrderToken, c.SenderProfile, c.Token, + c.TransactionLog, c.User, c.VerificationToken, c.WebhookRetryAttempt, } { n.Use(hooks...) } @@ -329,10 +342,11 @@ func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ c.APIKey, c.BeneficialOwner, c.FiatCurrency, c.IdentityVerificationRequest, c.Institution, c.KYBProfile, c.Network, c.PaymentOrder, - c.PaymentOrderFulfillment, c.PaymentWebhook, c.ProviderBalances, - c.ProviderFiatAccount, c.ProviderOrderToken, c.ProviderProfile, - c.ProviderRating, c.ProvisionBucket, c.SenderOrderToken, c.SenderProfile, - c.Token, c.TransactionLog, c.User, c.VerificationToken, c.WebhookRetryAttempt, + c.PaymentOrderFulfillment, c.PaymentWebhook, c.ProviderAssignmentRun, + c.ProviderBalances, c.ProviderFiatAccount, c.ProviderOrderToken, + c.ProviderOrderTokenScoreHistory, c.ProviderProfile, c.ProviderRating, + c.ProvisionBucket, c.SenderOrderToken, c.SenderProfile, c.Token, + c.TransactionLog, c.User, c.VerificationToken, c.WebhookRetryAttempt, } { n.Intercept(interceptors...) } @@ -361,12 +375,16 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.PaymentOrderFulfillment.mutate(ctx, m) case *PaymentWebhookMutation: return c.PaymentWebhook.mutate(ctx, m) + case *ProviderAssignmentRunMutation: + return c.ProviderAssignmentRun.mutate(ctx, m) case *ProviderBalancesMutation: return c.ProviderBalances.mutate(ctx, m) case *ProviderFiatAccountMutation: return c.ProviderFiatAccount.mutate(ctx, m) case *ProviderOrderTokenMutation: return c.ProviderOrderToken.mutate(ctx, m) + case *ProviderOrderTokenScoreHistoryMutation: + return c.ProviderOrderTokenScoreHistory.mutate(ctx, m) case *ProviderProfileMutation: return c.ProviderProfile.mutate(ctx, m) case *ProviderRatingMutation: @@ -846,22 +864,6 @@ func (c *FiatCurrencyClient) QueryProviderBalances(_m *FiatCurrency) *ProviderBa return query } -// QueryProvisionBuckets queries the provision_buckets edge of a FiatCurrency. -func (c *FiatCurrencyClient) QueryProvisionBuckets(_m *FiatCurrency) *ProvisionBucketQuery { - query := (&ProvisionBucketClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(fiatcurrency.Table, fiatcurrency.FieldID, id), - sqlgraph.To(provisionbucket.Table, provisionbucket.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, fiatcurrency.ProvisionBucketsTable, fiatcurrency.ProvisionBucketsColumn), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - // QueryInstitutions queries the institutions edge of a FiatCurrency. func (c *FiatCurrencyClient) QueryInstitutions(_m *FiatCurrency) *InstitutionQuery { query := (&InstitutionClient{config: c.config}).Query() @@ -1703,15 +1705,15 @@ func (c *PaymentOrderClient) QueryProvider(_m *PaymentOrder) *ProviderProfileQue return query } -// QueryProvisionBucket queries the provision_bucket edge of a PaymentOrder. -func (c *PaymentOrderClient) QueryProvisionBucket(_m *PaymentOrder) *ProvisionBucketQuery { - query := (&ProvisionBucketClient{config: c.config}).Query() +// QueryFulfillments queries the fulfillments edge of a PaymentOrder. +func (c *PaymentOrderClient) QueryFulfillments(_m *PaymentOrder) *PaymentOrderFulfillmentQuery { + query := (&PaymentOrderFulfillmentClient{config: c.config}).Query() query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := _m.ID step := sqlgraph.NewStep( sqlgraph.From(paymentorder.Table, paymentorder.FieldID, id), - sqlgraph.To(provisionbucket.Table, provisionbucket.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, paymentorder.ProvisionBucketTable, paymentorder.ProvisionBucketColumn), + sqlgraph.To(paymentorderfulfillment.Table, paymentorderfulfillment.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.FulfillmentsTable, paymentorder.FulfillmentsColumn), ) fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) return fromV, nil @@ -1719,15 +1721,15 @@ func (c *PaymentOrderClient) QueryProvisionBucket(_m *PaymentOrder) *ProvisionBu return query } -// QueryFulfillments queries the fulfillments edge of a PaymentOrder. -func (c *PaymentOrderClient) QueryFulfillments(_m *PaymentOrder) *PaymentOrderFulfillmentQuery { - query := (&PaymentOrderFulfillmentClient{config: c.config}).Query() +// QueryTransactions queries the transactions edge of a PaymentOrder. +func (c *PaymentOrderClient) QueryTransactions(_m *PaymentOrder) *TransactionLogQuery { + query := (&TransactionLogClient{config: c.config}).Query() query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := _m.ID step := sqlgraph.NewStep( sqlgraph.From(paymentorder.Table, paymentorder.FieldID, id), - sqlgraph.To(paymentorderfulfillment.Table, paymentorderfulfillment.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.FulfillmentsTable, paymentorder.FulfillmentsColumn), + sqlgraph.To(transactionlog.Table, transactionlog.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.TransactionsTable, paymentorder.TransactionsColumn), ) fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) return fromV, nil @@ -1735,15 +1737,31 @@ func (c *PaymentOrderClient) QueryFulfillments(_m *PaymentOrder) *PaymentOrderFu return query } -// QueryTransactions queries the transactions edge of a PaymentOrder. -func (c *PaymentOrderClient) QueryTransactions(_m *PaymentOrder) *TransactionLogQuery { - query := (&TransactionLogClient{config: c.config}).Query() +// QueryProviderAssignmentRuns queries the provider_assignment_runs edge of a PaymentOrder. +func (c *PaymentOrderClient) QueryProviderAssignmentRuns(_m *PaymentOrder) *ProviderAssignmentRunQuery { + query := (&ProviderAssignmentRunClient{config: c.config}).Query() query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := _m.ID step := sqlgraph.NewStep( sqlgraph.From(paymentorder.Table, paymentorder.FieldID, id), - sqlgraph.To(transactionlog.Table, transactionlog.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.TransactionsTable, paymentorder.TransactionsColumn), + sqlgraph.To(providerassignmentrun.Table, providerassignmentrun.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.ProviderAssignmentRunsTable, paymentorder.ProviderAssignmentRunsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryProviderOrderTokenScoreHistories queries the provider_order_token_score_histories edge of a PaymentOrder. +func (c *PaymentOrderClient) QueryProviderOrderTokenScoreHistories(_m *PaymentOrder) *ProviderOrderTokenScoreHistoryQuery { + query := (&ProviderOrderTokenScoreHistoryClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(paymentorder.Table, paymentorder.FieldID, id), + sqlgraph.To(providerordertokenscorehistory.Table, providerordertokenscorehistory.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.ProviderOrderTokenScoreHistoriesTable, paymentorder.ProviderOrderTokenScoreHistoriesColumn), ) fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) return fromV, nil @@ -2090,6 +2108,171 @@ func (c *PaymentWebhookClient) mutate(ctx context.Context, m *PaymentWebhookMuta } } +// ProviderAssignmentRunClient is a client for the ProviderAssignmentRun schema. +type ProviderAssignmentRunClient struct { + config +} + +// NewProviderAssignmentRunClient returns a client for the ProviderAssignmentRun from the given config. +func NewProviderAssignmentRunClient(c config) *ProviderAssignmentRunClient { + return &ProviderAssignmentRunClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `providerassignmentrun.Hooks(f(g(h())))`. +func (c *ProviderAssignmentRunClient) Use(hooks ...Hook) { + c.hooks.ProviderAssignmentRun = append(c.hooks.ProviderAssignmentRun, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `providerassignmentrun.Intercept(f(g(h())))`. +func (c *ProviderAssignmentRunClient) Intercept(interceptors ...Interceptor) { + c.inters.ProviderAssignmentRun = append(c.inters.ProviderAssignmentRun, interceptors...) +} + +// Create returns a builder for creating a ProviderAssignmentRun entity. +func (c *ProviderAssignmentRunClient) Create() *ProviderAssignmentRunCreate { + mutation := newProviderAssignmentRunMutation(c.config, OpCreate) + return &ProviderAssignmentRunCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ProviderAssignmentRun entities. +func (c *ProviderAssignmentRunClient) CreateBulk(builders ...*ProviderAssignmentRunCreate) *ProviderAssignmentRunCreateBulk { + return &ProviderAssignmentRunCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *ProviderAssignmentRunClient) MapCreateBulk(slice any, setFunc func(*ProviderAssignmentRunCreate, int)) *ProviderAssignmentRunCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ProviderAssignmentRunCreateBulk{err: fmt.Errorf("calling to ProviderAssignmentRunClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ProviderAssignmentRunCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ProviderAssignmentRunCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ProviderAssignmentRun. +func (c *ProviderAssignmentRunClient) Update() *ProviderAssignmentRunUpdate { + mutation := newProviderAssignmentRunMutation(c.config, OpUpdate) + return &ProviderAssignmentRunUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ProviderAssignmentRunClient) UpdateOne(_m *ProviderAssignmentRun) *ProviderAssignmentRunUpdateOne { + mutation := newProviderAssignmentRunMutation(c.config, OpUpdateOne, withProviderAssignmentRun(_m)) + return &ProviderAssignmentRunUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ProviderAssignmentRunClient) UpdateOneID(id uuid.UUID) *ProviderAssignmentRunUpdateOne { + mutation := newProviderAssignmentRunMutation(c.config, OpUpdateOne, withProviderAssignmentRunID(id)) + return &ProviderAssignmentRunUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ProviderAssignmentRun. +func (c *ProviderAssignmentRunClient) Delete() *ProviderAssignmentRunDelete { + mutation := newProviderAssignmentRunMutation(c.config, OpDelete) + return &ProviderAssignmentRunDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ProviderAssignmentRunClient) DeleteOne(_m *ProviderAssignmentRun) *ProviderAssignmentRunDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ProviderAssignmentRunClient) DeleteOneID(id uuid.UUID) *ProviderAssignmentRunDeleteOne { + builder := c.Delete().Where(providerassignmentrun.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ProviderAssignmentRunDeleteOne{builder} +} + +// Query returns a query builder for ProviderAssignmentRun. +func (c *ProviderAssignmentRunClient) Query() *ProviderAssignmentRunQuery { + return &ProviderAssignmentRunQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeProviderAssignmentRun}, + inters: c.Interceptors(), + } +} + +// Get returns a ProviderAssignmentRun entity by its id. +func (c *ProviderAssignmentRunClient) Get(ctx context.Context, id uuid.UUID) (*ProviderAssignmentRun, error) { + return c.Query().Where(providerassignmentrun.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ProviderAssignmentRunClient) GetX(ctx context.Context, id uuid.UUID) *ProviderAssignmentRun { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryPaymentOrder queries the payment_order edge of a ProviderAssignmentRun. +func (c *ProviderAssignmentRunClient) QueryPaymentOrder(_m *ProviderAssignmentRun) *PaymentOrderQuery { + query := (&PaymentOrderClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(providerassignmentrun.Table, providerassignmentrun.FieldID, id), + sqlgraph.To(paymentorder.Table, paymentorder.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, providerassignmentrun.PaymentOrderTable, providerassignmentrun.PaymentOrderColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryProviderOrderToken queries the provider_order_token edge of a ProviderAssignmentRun. +func (c *ProviderAssignmentRunClient) QueryProviderOrderToken(_m *ProviderAssignmentRun) *ProviderOrderTokenQuery { + query := (&ProviderOrderTokenClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(providerassignmentrun.Table, providerassignmentrun.FieldID, id), + sqlgraph.To(providerordertoken.Table, providerordertoken.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, providerassignmentrun.ProviderOrderTokenTable, providerassignmentrun.ProviderOrderTokenColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ProviderAssignmentRunClient) Hooks() []Hook { + return c.hooks.ProviderAssignmentRun +} + +// Interceptors returns the client interceptors. +func (c *ProviderAssignmentRunClient) Interceptors() []Interceptor { + return c.inters.ProviderAssignmentRun +} + +func (c *ProviderAssignmentRunClient) mutate(ctx context.Context, m *ProviderAssignmentRunMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ProviderAssignmentRunCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ProviderAssignmentRunUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ProviderAssignmentRunUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ProviderAssignmentRunDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown ProviderAssignmentRun mutation op: %q", m.Op()) + } +} + // ProviderBalancesClient is a client for the ProviderBalances schema. type ProviderBalancesClient struct { config @@ -2576,6 +2759,38 @@ func (c *ProviderOrderTokenClient) QueryCurrency(_m *ProviderOrderToken) *FiatCu return query } +// QueryScoreHistories queries the score_histories edge of a ProviderOrderToken. +func (c *ProviderOrderTokenClient) QueryScoreHistories(_m *ProviderOrderToken) *ProviderOrderTokenScoreHistoryQuery { + query := (&ProviderOrderTokenScoreHistoryClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(providerordertoken.Table, providerordertoken.FieldID, id), + sqlgraph.To(providerordertokenscorehistory.Table, providerordertokenscorehistory.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, providerordertoken.ScoreHistoriesTable, providerordertoken.ScoreHistoriesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryAssignmentRuns queries the assignment_runs edge of a ProviderOrderToken. +func (c *ProviderOrderTokenClient) QueryAssignmentRuns(_m *ProviderOrderToken) *ProviderAssignmentRunQuery { + query := (&ProviderAssignmentRunClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(providerordertoken.Table, providerordertoken.FieldID, id), + sqlgraph.To(providerassignmentrun.Table, providerassignmentrun.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, providerordertoken.AssignmentRunsTable, providerordertoken.AssignmentRunsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *ProviderOrderTokenClient) Hooks() []Hook { return c.hooks.ProviderOrderToken @@ -2601,6 +2816,172 @@ func (c *ProviderOrderTokenClient) mutate(ctx context.Context, m *ProviderOrderT } } +// ProviderOrderTokenScoreHistoryClient is a client for the ProviderOrderTokenScoreHistory schema. +type ProviderOrderTokenScoreHistoryClient struct { + config +} + +// NewProviderOrderTokenScoreHistoryClient returns a client for the ProviderOrderTokenScoreHistory from the given config. +func NewProviderOrderTokenScoreHistoryClient(c config) *ProviderOrderTokenScoreHistoryClient { + return &ProviderOrderTokenScoreHistoryClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `providerordertokenscorehistory.Hooks(f(g(h())))`. +func (c *ProviderOrderTokenScoreHistoryClient) Use(hooks ...Hook) { + c.hooks.ProviderOrderTokenScoreHistory = append(c.hooks.ProviderOrderTokenScoreHistory, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `providerordertokenscorehistory.Intercept(f(g(h())))`. +func (c *ProviderOrderTokenScoreHistoryClient) Intercept(interceptors ...Interceptor) { + c.inters.ProviderOrderTokenScoreHistory = append(c.inters.ProviderOrderTokenScoreHistory, interceptors...) +} + +// Create returns a builder for creating a ProviderOrderTokenScoreHistory entity. +func (c *ProviderOrderTokenScoreHistoryClient) Create() *ProviderOrderTokenScoreHistoryCreate { + mutation := newProviderOrderTokenScoreHistoryMutation(c.config, OpCreate) + return &ProviderOrderTokenScoreHistoryCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ProviderOrderTokenScoreHistory entities. +func (c *ProviderOrderTokenScoreHistoryClient) CreateBulk(builders ...*ProviderOrderTokenScoreHistoryCreate) *ProviderOrderTokenScoreHistoryCreateBulk { + return &ProviderOrderTokenScoreHistoryCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *ProviderOrderTokenScoreHistoryClient) MapCreateBulk(slice any, setFunc func(*ProviderOrderTokenScoreHistoryCreate, int)) *ProviderOrderTokenScoreHistoryCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ProviderOrderTokenScoreHistoryCreateBulk{err: fmt.Errorf("calling to ProviderOrderTokenScoreHistoryClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ProviderOrderTokenScoreHistoryCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ProviderOrderTokenScoreHistoryCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ProviderOrderTokenScoreHistory. +func (c *ProviderOrderTokenScoreHistoryClient) Update() *ProviderOrderTokenScoreHistoryUpdate { + mutation := newProviderOrderTokenScoreHistoryMutation(c.config, OpUpdate) + return &ProviderOrderTokenScoreHistoryUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ProviderOrderTokenScoreHistoryClient) UpdateOne(_m *ProviderOrderTokenScoreHistory) *ProviderOrderTokenScoreHistoryUpdateOne { + mutation := newProviderOrderTokenScoreHistoryMutation(c.config, OpUpdateOne, withProviderOrderTokenScoreHistory(_m)) + return &ProviderOrderTokenScoreHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ProviderOrderTokenScoreHistoryClient) UpdateOneID(id uuid.UUID) *ProviderOrderTokenScoreHistoryUpdateOne { + mutation := newProviderOrderTokenScoreHistoryMutation(c.config, OpUpdateOne, withProviderOrderTokenScoreHistoryID(id)) + return &ProviderOrderTokenScoreHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ProviderOrderTokenScoreHistory. +func (c *ProviderOrderTokenScoreHistoryClient) Delete() *ProviderOrderTokenScoreHistoryDelete { + mutation := newProviderOrderTokenScoreHistoryMutation(c.config, OpDelete) + return &ProviderOrderTokenScoreHistoryDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ProviderOrderTokenScoreHistoryClient) DeleteOne(_m *ProviderOrderTokenScoreHistory) *ProviderOrderTokenScoreHistoryDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ProviderOrderTokenScoreHistoryClient) DeleteOneID(id uuid.UUID) *ProviderOrderTokenScoreHistoryDeleteOne { + builder := c.Delete().Where(providerordertokenscorehistory.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ProviderOrderTokenScoreHistoryDeleteOne{builder} +} + +// Query returns a query builder for ProviderOrderTokenScoreHistory. +func (c *ProviderOrderTokenScoreHistoryClient) Query() *ProviderOrderTokenScoreHistoryQuery { + return &ProviderOrderTokenScoreHistoryQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeProviderOrderTokenScoreHistory}, + inters: c.Interceptors(), + } +} + +// Get returns a ProviderOrderTokenScoreHistory entity by its id. +func (c *ProviderOrderTokenScoreHistoryClient) Get(ctx context.Context, id uuid.UUID) (*ProviderOrderTokenScoreHistory, error) { + return c.Query().Where(providerordertokenscorehistory.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ProviderOrderTokenScoreHistoryClient) GetX(ctx context.Context, id uuid.UUID) *ProviderOrderTokenScoreHistory { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryPaymentOrder queries the payment_order edge of a ProviderOrderTokenScoreHistory. +func (c *ProviderOrderTokenScoreHistoryClient) QueryPaymentOrder(_m *ProviderOrderTokenScoreHistory) *PaymentOrderQuery { + query := (&PaymentOrderClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(providerordertokenscorehistory.Table, providerordertokenscorehistory.FieldID, id), + sqlgraph.To(paymentorder.Table, paymentorder.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, providerordertokenscorehistory.PaymentOrderTable, providerordertokenscorehistory.PaymentOrderColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryProviderOrderToken queries the provider_order_token edge of a ProviderOrderTokenScoreHistory. +func (c *ProviderOrderTokenScoreHistoryClient) QueryProviderOrderToken(_m *ProviderOrderTokenScoreHistory) *ProviderOrderTokenQuery { + query := (&ProviderOrderTokenClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(providerordertokenscorehistory.Table, providerordertokenscorehistory.FieldID, id), + sqlgraph.To(providerordertoken.Table, providerordertoken.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, providerordertokenscorehistory.ProviderOrderTokenTable, providerordertokenscorehistory.ProviderOrderTokenColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ProviderOrderTokenScoreHistoryClient) Hooks() []Hook { + hooks := c.hooks.ProviderOrderTokenScoreHistory + return append(hooks[:len(hooks):len(hooks)], providerordertokenscorehistory.Hooks[:]...) +} + +// Interceptors returns the client interceptors. +func (c *ProviderOrderTokenScoreHistoryClient) Interceptors() []Interceptor { + return c.inters.ProviderOrderTokenScoreHistory +} + +func (c *ProviderOrderTokenScoreHistoryClient) mutate(ctx context.Context, m *ProviderOrderTokenScoreHistoryMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ProviderOrderTokenScoreHistoryCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ProviderOrderTokenScoreHistoryUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ProviderOrderTokenScoreHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ProviderOrderTokenScoreHistoryDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown ProviderOrderTokenScoreHistory mutation op: %q", m.Op()) + } +} + // ProviderProfileClient is a client for the ProviderProfile schema. type ProviderProfileClient struct { config @@ -2757,22 +3138,6 @@ func (c *ProviderProfileClient) QueryProviderBalances(_m *ProviderProfile) *Prov return query } -// QueryProvisionBuckets queries the provision_buckets edge of a ProviderProfile. -func (c *ProviderProfileClient) QueryProvisionBuckets(_m *ProviderProfile) *ProvisionBucketQuery { - query := (&ProvisionBucketClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(providerprofile.Table, providerprofile.FieldID, id), - sqlgraph.To(provisionbucket.Table, provisionbucket.FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, providerprofile.ProvisionBucketsTable, providerprofile.ProvisionBucketsPrimaryKey...), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - // QueryOrderTokens queries the order_tokens edge of a ProviderProfile. func (c *ProviderProfileClient) QueryOrderTokens(_m *ProviderProfile) *ProviderOrderTokenQuery { query := (&ProviderOrderTokenClient{config: c.config}).Query() @@ -3119,54 +3484,6 @@ func (c *ProvisionBucketClient) GetX(ctx context.Context, id int) *ProvisionBuck return obj } -// QueryCurrency queries the currency edge of a ProvisionBucket. -func (c *ProvisionBucketClient) QueryCurrency(_m *ProvisionBucket) *FiatCurrencyQuery { - query := (&FiatCurrencyClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(provisionbucket.Table, provisionbucket.FieldID, id), - sqlgraph.To(fiatcurrency.Table, fiatcurrency.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, provisionbucket.CurrencyTable, provisionbucket.CurrencyColumn), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// QueryPaymentOrders queries the payment_orders edge of a ProvisionBucket. -func (c *ProvisionBucketClient) QueryPaymentOrders(_m *ProvisionBucket) *PaymentOrderQuery { - query := (&PaymentOrderClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(provisionbucket.Table, provisionbucket.FieldID, id), - sqlgraph.To(paymentorder.Table, paymentorder.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, provisionbucket.PaymentOrdersTable, provisionbucket.PaymentOrdersColumn), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// QueryProviderProfiles queries the provider_profiles edge of a ProvisionBucket. -func (c *ProvisionBucketClient) QueryProviderProfiles(_m *ProvisionBucket) *ProviderProfileQuery { - query := (&ProviderProfileClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(provisionbucket.Table, provisionbucket.FieldID, id), - sqlgraph.To(providerprofile.Table, providerprofile.FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, provisionbucket.ProviderProfilesTable, provisionbucket.ProviderProfilesPrimaryKey...), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - // Hooks returns the client hooks. func (c *ProvisionBucketClient) Hooks() []Hook { return c.hooks.ProvisionBucket @@ -4402,14 +4719,16 @@ type ( hooks struct { APIKey, BeneficialOwner, FiatCurrency, IdentityVerificationRequest, Institution, KYBProfile, Network, PaymentOrder, PaymentOrderFulfillment, PaymentWebhook, - ProviderBalances, ProviderFiatAccount, ProviderOrderToken, ProviderProfile, + ProviderAssignmentRun, ProviderBalances, ProviderFiatAccount, + ProviderOrderToken, ProviderOrderTokenScoreHistory, ProviderProfile, ProviderRating, ProvisionBucket, SenderOrderToken, SenderProfile, Token, TransactionLog, User, VerificationToken, WebhookRetryAttempt []ent.Hook } inters struct { APIKey, BeneficialOwner, FiatCurrency, IdentityVerificationRequest, Institution, KYBProfile, Network, PaymentOrder, PaymentOrderFulfillment, PaymentWebhook, - ProviderBalances, ProviderFiatAccount, ProviderOrderToken, ProviderProfile, + ProviderAssignmentRun, ProviderBalances, ProviderFiatAccount, + ProviderOrderToken, ProviderOrderTokenScoreHistory, ProviderProfile, ProviderRating, ProvisionBucket, SenderOrderToken, SenderProfile, Token, TransactionLog, User, VerificationToken, WebhookRetryAttempt []ent.Interceptor } diff --git a/ent/ent.go b/ent/ent.go index c25317bb5..5bb689cbe 100644 --- a/ent/ent.go +++ b/ent/ent.go @@ -22,9 +22,11 @@ import ( "github.com/paycrest/aggregator/ent/paymentorder" "github.com/paycrest/aggregator/ent/paymentorderfulfillment" "github.com/paycrest/aggregator/ent/paymentwebhook" + "github.com/paycrest/aggregator/ent/providerassignmentrun" "github.com/paycrest/aggregator/ent/providerbalances" "github.com/paycrest/aggregator/ent/providerfiataccount" "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/providerrating" "github.com/paycrest/aggregator/ent/provisionbucket" @@ -95,29 +97,31 @@ var ( func checkColumn(t, c string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ - apikey.Table: apikey.ValidColumn, - beneficialowner.Table: beneficialowner.ValidColumn, - fiatcurrency.Table: fiatcurrency.ValidColumn, - identityverificationrequest.Table: identityverificationrequest.ValidColumn, - institution.Table: institution.ValidColumn, - kybprofile.Table: kybprofile.ValidColumn, - network.Table: network.ValidColumn, - paymentorder.Table: paymentorder.ValidColumn, - paymentorderfulfillment.Table: paymentorderfulfillment.ValidColumn, - paymentwebhook.Table: paymentwebhook.ValidColumn, - providerbalances.Table: providerbalances.ValidColumn, - providerfiataccount.Table: providerfiataccount.ValidColumn, - providerordertoken.Table: providerordertoken.ValidColumn, - providerprofile.Table: providerprofile.ValidColumn, - providerrating.Table: providerrating.ValidColumn, - provisionbucket.Table: provisionbucket.ValidColumn, - senderordertoken.Table: senderordertoken.ValidColumn, - senderprofile.Table: senderprofile.ValidColumn, - token.Table: token.ValidColumn, - transactionlog.Table: transactionlog.ValidColumn, - user.Table: user.ValidColumn, - verificationtoken.Table: verificationtoken.ValidColumn, - webhookretryattempt.Table: webhookretryattempt.ValidColumn, + apikey.Table: apikey.ValidColumn, + beneficialowner.Table: beneficialowner.ValidColumn, + fiatcurrency.Table: fiatcurrency.ValidColumn, + identityverificationrequest.Table: identityverificationrequest.ValidColumn, + institution.Table: institution.ValidColumn, + kybprofile.Table: kybprofile.ValidColumn, + network.Table: network.ValidColumn, + paymentorder.Table: paymentorder.ValidColumn, + paymentorderfulfillment.Table: paymentorderfulfillment.ValidColumn, + paymentwebhook.Table: paymentwebhook.ValidColumn, + providerassignmentrun.Table: providerassignmentrun.ValidColumn, + providerbalances.Table: providerbalances.ValidColumn, + providerfiataccount.Table: providerfiataccount.ValidColumn, + providerordertoken.Table: providerordertoken.ValidColumn, + providerordertokenscorehistory.Table: providerordertokenscorehistory.ValidColumn, + providerprofile.Table: providerprofile.ValidColumn, + providerrating.Table: providerrating.ValidColumn, + provisionbucket.Table: provisionbucket.ValidColumn, + senderordertoken.Table: senderordertoken.ValidColumn, + senderprofile.Table: senderprofile.ValidColumn, + token.Table: token.ValidColumn, + transactionlog.Table: transactionlog.ValidColumn, + user.Table: user.ValidColumn, + verificationtoken.Table: verificationtoken.ValidColumn, + webhookretryattempt.Table: webhookretryattempt.ValidColumn, }) }) return columnCheck(t, c) diff --git a/ent/fiatcurrency.go b/ent/fiatcurrency.go index bc7db84e9..af1982fd4 100644 --- a/ent/fiatcurrency.go +++ b/ent/fiatcurrency.go @@ -49,15 +49,13 @@ type FiatCurrency struct { type FiatCurrencyEdges struct { // ProviderBalances holds the value of the provider_balances edge. ProviderBalances []*ProviderBalances `json:"provider_balances,omitempty"` - // ProvisionBuckets holds the value of the provision_buckets edge. - ProvisionBuckets []*ProvisionBucket `json:"provision_buckets,omitempty"` // Institutions holds the value of the institutions edge. Institutions []*Institution `json:"institutions,omitempty"` // ProviderOrderTokens holds the value of the provider_order_tokens edge. ProviderOrderTokens []*ProviderOrderToken `json:"provider_order_tokens,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [4]bool + loadedTypes [3]bool } // ProviderBalancesOrErr returns the ProviderBalances value or an error if the edge @@ -69,19 +67,10 @@ func (e FiatCurrencyEdges) ProviderBalancesOrErr() ([]*ProviderBalances, error) return nil, &NotLoadedError{edge: "provider_balances"} } -// ProvisionBucketsOrErr returns the ProvisionBuckets value or an error if the edge -// was not loaded in eager-loading. -func (e FiatCurrencyEdges) ProvisionBucketsOrErr() ([]*ProvisionBucket, error) { - if e.loadedTypes[1] { - return e.ProvisionBuckets, nil - } - return nil, &NotLoadedError{edge: "provision_buckets"} -} - // InstitutionsOrErr returns the Institutions value or an error if the edge // was not loaded in eager-loading. func (e FiatCurrencyEdges) InstitutionsOrErr() ([]*Institution, error) { - if e.loadedTypes[2] { + if e.loadedTypes[1] { return e.Institutions, nil } return nil, &NotLoadedError{edge: "institutions"} @@ -90,7 +79,7 @@ func (e FiatCurrencyEdges) InstitutionsOrErr() ([]*Institution, error) { // ProviderOrderTokensOrErr returns the ProviderOrderTokens value or an error if the edge // was not loaded in eager-loading. func (e FiatCurrencyEdges) ProviderOrderTokensOrErr() ([]*ProviderOrderToken, error) { - if e.loadedTypes[3] { + if e.loadedTypes[2] { return e.ProviderOrderTokens, nil } return nil, &NotLoadedError{edge: "provider_order_tokens"} @@ -212,11 +201,6 @@ func (_m *FiatCurrency) QueryProviderBalances() *ProviderBalancesQuery { return NewFiatCurrencyClient(_m.config).QueryProviderBalances(_m) } -// QueryProvisionBuckets queries the "provision_buckets" edge of the FiatCurrency entity. -func (_m *FiatCurrency) QueryProvisionBuckets() *ProvisionBucketQuery { - return NewFiatCurrencyClient(_m.config).QueryProvisionBuckets(_m) -} - // QueryInstitutions queries the "institutions" edge of the FiatCurrency entity. func (_m *FiatCurrency) QueryInstitutions() *InstitutionQuery { return NewFiatCurrencyClient(_m.config).QueryInstitutions(_m) diff --git a/ent/fiatcurrency/fiatcurrency.go b/ent/fiatcurrency/fiatcurrency.go index 93e8d5dea..61e9485b2 100644 --- a/ent/fiatcurrency/fiatcurrency.go +++ b/ent/fiatcurrency/fiatcurrency.go @@ -37,8 +37,6 @@ const ( FieldIsEnabled = "is_enabled" // EdgeProviderBalances holds the string denoting the provider_balances edge name in mutations. EdgeProviderBalances = "provider_balances" - // EdgeProvisionBuckets holds the string denoting the provision_buckets edge name in mutations. - EdgeProvisionBuckets = "provision_buckets" // EdgeInstitutions holds the string denoting the institutions edge name in mutations. EdgeInstitutions = "institutions" // EdgeProviderOrderTokens holds the string denoting the provider_order_tokens edge name in mutations. @@ -52,13 +50,6 @@ const ( ProviderBalancesInverseTable = "provider_balances" // ProviderBalancesColumn is the table column denoting the provider_balances relation/edge. ProviderBalancesColumn = "fiat_currency_provider_balances" - // ProvisionBucketsTable is the table that holds the provision_buckets relation/edge. - ProvisionBucketsTable = "provision_buckets" - // ProvisionBucketsInverseTable is the table name for the ProvisionBucket entity. - // It exists in this package in order to avoid circular dependency with the "provisionbucket" package. - ProvisionBucketsInverseTable = "provision_buckets" - // ProvisionBucketsColumn is the table column denoting the provision_buckets relation/edge. - ProvisionBucketsColumn = "fiat_currency_provision_buckets" // InstitutionsTable is the table that holds the institutions relation/edge. InstitutionsTable = "institutions" // InstitutionsInverseTable is the table name for the Institution entity. @@ -187,20 +178,6 @@ func ByProviderBalances(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption } } -// ByProvisionBucketsCount orders the results by provision_buckets count. -func ByProvisionBucketsCount(opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newProvisionBucketsStep(), opts...) - } -} - -// ByProvisionBuckets orders the results by provision_buckets terms. -func ByProvisionBuckets(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newProvisionBucketsStep(), append([]sql.OrderTerm{term}, terms...)...) - } -} - // ByInstitutionsCount orders the results by institutions count. func ByInstitutionsCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -235,13 +212,6 @@ func newProviderBalancesStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, ProviderBalancesTable, ProviderBalancesColumn), ) } -func newProvisionBucketsStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(ProvisionBucketsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, ProvisionBucketsTable, ProvisionBucketsColumn), - ) -} func newInstitutionsStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), diff --git a/ent/fiatcurrency/where.go b/ent/fiatcurrency/where.go index 7266d961f..4c6779c58 100644 --- a/ent/fiatcurrency/where.go +++ b/ent/fiatcurrency/where.go @@ -620,29 +620,6 @@ func HasProviderBalancesWith(preds ...predicate.ProviderBalances) predicate.Fiat }) } -// HasProvisionBuckets applies the HasEdge predicate on the "provision_buckets" edge. -func HasProvisionBuckets() predicate.FiatCurrency { - return predicate.FiatCurrency(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, ProvisionBucketsTable, ProvisionBucketsColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasProvisionBucketsWith applies the HasEdge predicate on the "provision_buckets" edge with a given conditions (other predicates). -func HasProvisionBucketsWith(preds ...predicate.ProvisionBucket) predicate.FiatCurrency { - return predicate.FiatCurrency(func(s *sql.Selector) { - step := newProvisionBucketsStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - // HasInstitutions applies the HasEdge predicate on the "institutions" edge. func HasInstitutions() predicate.FiatCurrency { return predicate.FiatCurrency(func(s *sql.Selector) { diff --git a/ent/fiatcurrency_create.go b/ent/fiatcurrency_create.go index 334dd619f..3db0c6d09 100644 --- a/ent/fiatcurrency_create.go +++ b/ent/fiatcurrency_create.go @@ -17,7 +17,6 @@ import ( "github.com/paycrest/aggregator/ent/institution" "github.com/paycrest/aggregator/ent/providerbalances" "github.com/paycrest/aggregator/ent/providerordertoken" - "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/shopspring/decimal" ) @@ -166,21 +165,6 @@ func (_c *FiatCurrencyCreate) AddProviderBalances(v ...*ProviderBalances) *FiatC return _c.AddProviderBalanceIDs(ids...) } -// AddProvisionBucketIDs adds the "provision_buckets" edge to the ProvisionBucket entity by IDs. -func (_c *FiatCurrencyCreate) AddProvisionBucketIDs(ids ...int) *FiatCurrencyCreate { - _c.mutation.AddProvisionBucketIDs(ids...) - return _c -} - -// AddProvisionBuckets adds the "provision_buckets" edges to the ProvisionBucket entity. -func (_c *FiatCurrencyCreate) AddProvisionBuckets(v ...*ProvisionBucket) *FiatCurrencyCreate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _c.AddProvisionBucketIDs(ids...) -} - // AddInstitutionIDs adds the "institutions" edge to the Institution entity by IDs. func (_c *FiatCurrencyCreate) AddInstitutionIDs(ids ...int) *FiatCurrencyCreate { _c.mutation.AddInstitutionIDs(ids...) @@ -386,22 +370,6 @@ func (_c *FiatCurrencyCreate) createSpec() (*FiatCurrency, *sqlgraph.CreateSpec) } _spec.Edges = append(_spec.Edges, edge) } - if nodes := _c.mutation.ProvisionBucketsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: fiatcurrency.ProvisionBucketsTable, - Columns: []string{fiatcurrency.ProvisionBucketsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } if nodes := _c.mutation.InstitutionsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/ent/fiatcurrency_query.go b/ent/fiatcurrency_query.go index f157c1586..fe2ccafa6 100644 --- a/ent/fiatcurrency_query.go +++ b/ent/fiatcurrency_query.go @@ -18,7 +18,6 @@ import ( "github.com/paycrest/aggregator/ent/predicate" "github.com/paycrest/aggregator/ent/providerbalances" "github.com/paycrest/aggregator/ent/providerordertoken" - "github.com/paycrest/aggregator/ent/provisionbucket" ) // FiatCurrencyQuery is the builder for querying FiatCurrency entities. @@ -29,7 +28,6 @@ type FiatCurrencyQuery struct { inters []Interceptor predicates []predicate.FiatCurrency withProviderBalances *ProviderBalancesQuery - withProvisionBuckets *ProvisionBucketQuery withInstitutions *InstitutionQuery withProviderOrderTokens *ProviderOrderTokenQuery // intermediate query (i.e. traversal path). @@ -90,28 +88,6 @@ func (_q *FiatCurrencyQuery) QueryProviderBalances() *ProviderBalancesQuery { return query } -// QueryProvisionBuckets chains the current query on the "provision_buckets" edge. -func (_q *FiatCurrencyQuery) QueryProvisionBuckets() *ProvisionBucketQuery { - query := (&ProvisionBucketClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(fiatcurrency.Table, fiatcurrency.FieldID, selector), - sqlgraph.To(provisionbucket.Table, provisionbucket.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, fiatcurrency.ProvisionBucketsTable, fiatcurrency.ProvisionBucketsColumn), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - // QueryInstitutions chains the current query on the "institutions" edge. func (_q *FiatCurrencyQuery) QueryInstitutions() *InstitutionQuery { query := (&InstitutionClient{config: _q.config}).Query() @@ -349,7 +325,6 @@ func (_q *FiatCurrencyQuery) Clone() *FiatCurrencyQuery { inters: append([]Interceptor{}, _q.inters...), predicates: append([]predicate.FiatCurrency{}, _q.predicates...), withProviderBalances: _q.withProviderBalances.Clone(), - withProvisionBuckets: _q.withProvisionBuckets.Clone(), withInstitutions: _q.withInstitutions.Clone(), withProviderOrderTokens: _q.withProviderOrderTokens.Clone(), // clone intermediate query. @@ -369,17 +344,6 @@ func (_q *FiatCurrencyQuery) WithProviderBalances(opts ...func(*ProviderBalances return _q } -// WithProvisionBuckets tells the query-builder to eager-load the nodes that are connected to -// the "provision_buckets" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *FiatCurrencyQuery) WithProvisionBuckets(opts ...func(*ProvisionBucketQuery)) *FiatCurrencyQuery { - query := (&ProvisionBucketClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withProvisionBuckets = query - return _q -} - // WithInstitutions tells the query-builder to eager-load the nodes that are connected to // the "institutions" edge. The optional arguments are used to configure the query builder of the edge. func (_q *FiatCurrencyQuery) WithInstitutions(opts ...func(*InstitutionQuery)) *FiatCurrencyQuery { @@ -480,9 +444,8 @@ func (_q *FiatCurrencyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([] var ( nodes = []*FiatCurrency{} _spec = _q.querySpec() - loadedTypes = [4]bool{ + loadedTypes = [3]bool{ _q.withProviderBalances != nil, - _q.withProvisionBuckets != nil, _q.withInstitutions != nil, _q.withProviderOrderTokens != nil, } @@ -514,15 +477,6 @@ func (_q *FiatCurrencyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([] return nil, err } } - if query := _q.withProvisionBuckets; query != nil { - if err := _q.loadProvisionBuckets(ctx, query, nodes, - func(n *FiatCurrency) { n.Edges.ProvisionBuckets = []*ProvisionBucket{} }, - func(n *FiatCurrency, e *ProvisionBucket) { - n.Edges.ProvisionBuckets = append(n.Edges.ProvisionBuckets, e) - }); err != nil { - return nil, err - } - } if query := _q.withInstitutions; query != nil { if err := _q.loadInstitutions(ctx, query, nodes, func(n *FiatCurrency) { n.Edges.Institutions = []*Institution{} }, @@ -573,37 +527,6 @@ func (_q *FiatCurrencyQuery) loadProviderBalances(ctx context.Context, query *Pr } return nil } -func (_q *FiatCurrencyQuery) loadProvisionBuckets(ctx context.Context, query *ProvisionBucketQuery, nodes []*FiatCurrency, init func(*FiatCurrency), assign func(*FiatCurrency, *ProvisionBucket)) error { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[uuid.UUID]*FiatCurrency) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] - if init != nil { - init(nodes[i]) - } - } - query.withFKs = true - query.Where(predicate.ProvisionBucket(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(fiatcurrency.ProvisionBucketsColumn), fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - fk := n.fiat_currency_provision_buckets - if fk == nil { - return fmt.Errorf(`foreign-key "fiat_currency_provision_buckets" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "fiat_currency_provision_buckets" returned %v for node %v`, *fk, n.ID) - } - assign(node, n) - } - return nil -} func (_q *FiatCurrencyQuery) loadInstitutions(ctx context.Context, query *InstitutionQuery, nodes []*FiatCurrency, init func(*FiatCurrency), assign func(*FiatCurrency, *Institution)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[uuid.UUID]*FiatCurrency) diff --git a/ent/fiatcurrency_update.go b/ent/fiatcurrency_update.go index baa229305..fcc8f581f 100644 --- a/ent/fiatcurrency_update.go +++ b/ent/fiatcurrency_update.go @@ -17,7 +17,6 @@ import ( "github.com/paycrest/aggregator/ent/predicate" "github.com/paycrest/aggregator/ent/providerbalances" "github.com/paycrest/aggregator/ent/providerordertoken" - "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/shopspring/decimal" ) @@ -200,21 +199,6 @@ func (_u *FiatCurrencyUpdate) AddProviderBalances(v ...*ProviderBalances) *FiatC return _u.AddProviderBalanceIDs(ids...) } -// AddProvisionBucketIDs adds the "provision_buckets" edge to the ProvisionBucket entity by IDs. -func (_u *FiatCurrencyUpdate) AddProvisionBucketIDs(ids ...int) *FiatCurrencyUpdate { - _u.mutation.AddProvisionBucketIDs(ids...) - return _u -} - -// AddProvisionBuckets adds the "provision_buckets" edges to the ProvisionBucket entity. -func (_u *FiatCurrencyUpdate) AddProvisionBuckets(v ...*ProvisionBucket) *FiatCurrencyUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddProvisionBucketIDs(ids...) -} - // AddInstitutionIDs adds the "institutions" edge to the Institution entity by IDs. func (_u *FiatCurrencyUpdate) AddInstitutionIDs(ids ...int) *FiatCurrencyUpdate { _u.mutation.AddInstitutionIDs(ids...) @@ -271,27 +255,6 @@ func (_u *FiatCurrencyUpdate) RemoveProviderBalances(v ...*ProviderBalances) *Fi return _u.RemoveProviderBalanceIDs(ids...) } -// ClearProvisionBuckets clears all "provision_buckets" edges to the ProvisionBucket entity. -func (_u *FiatCurrencyUpdate) ClearProvisionBuckets() *FiatCurrencyUpdate { - _u.mutation.ClearProvisionBuckets() - return _u -} - -// RemoveProvisionBucketIDs removes the "provision_buckets" edge to ProvisionBucket entities by IDs. -func (_u *FiatCurrencyUpdate) RemoveProvisionBucketIDs(ids ...int) *FiatCurrencyUpdate { - _u.mutation.RemoveProvisionBucketIDs(ids...) - return _u -} - -// RemoveProvisionBuckets removes "provision_buckets" edges to ProvisionBucket entities. -func (_u *FiatCurrencyUpdate) RemoveProvisionBuckets(v ...*ProvisionBucket) *FiatCurrencyUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveProvisionBucketIDs(ids...) -} - // ClearInstitutions clears all "institutions" edges to the Institution entity. func (_u *FiatCurrencyUpdate) ClearInstitutions() *FiatCurrencyUpdate { _u.mutation.ClearInstitutions() @@ -466,51 +429,6 @@ func (_u *FiatCurrencyUpdate) sqlSave(ctx context.Context) (_node int, err error } _spec.Edges.Add = append(_spec.Edges.Add, edge) } - if _u.mutation.ProvisionBucketsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: fiatcurrency.ProvisionBucketsTable, - Columns: []string{fiatcurrency.ProvisionBucketsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedProvisionBucketsIDs(); len(nodes) > 0 && !_u.mutation.ProvisionBucketsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: fiatcurrency.ProvisionBucketsTable, - Columns: []string{fiatcurrency.ProvisionBucketsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.ProvisionBucketsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: fiatcurrency.ProvisionBucketsTable, - Columns: []string{fiatcurrency.ProvisionBucketsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } if _u.mutation.InstitutionsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -787,21 +705,6 @@ func (_u *FiatCurrencyUpdateOne) AddProviderBalances(v ...*ProviderBalances) *Fi return _u.AddProviderBalanceIDs(ids...) } -// AddProvisionBucketIDs adds the "provision_buckets" edge to the ProvisionBucket entity by IDs. -func (_u *FiatCurrencyUpdateOne) AddProvisionBucketIDs(ids ...int) *FiatCurrencyUpdateOne { - _u.mutation.AddProvisionBucketIDs(ids...) - return _u -} - -// AddProvisionBuckets adds the "provision_buckets" edges to the ProvisionBucket entity. -func (_u *FiatCurrencyUpdateOne) AddProvisionBuckets(v ...*ProvisionBucket) *FiatCurrencyUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddProvisionBucketIDs(ids...) -} - // AddInstitutionIDs adds the "institutions" edge to the Institution entity by IDs. func (_u *FiatCurrencyUpdateOne) AddInstitutionIDs(ids ...int) *FiatCurrencyUpdateOne { _u.mutation.AddInstitutionIDs(ids...) @@ -858,27 +761,6 @@ func (_u *FiatCurrencyUpdateOne) RemoveProviderBalances(v ...*ProviderBalances) return _u.RemoveProviderBalanceIDs(ids...) } -// ClearProvisionBuckets clears all "provision_buckets" edges to the ProvisionBucket entity. -func (_u *FiatCurrencyUpdateOne) ClearProvisionBuckets() *FiatCurrencyUpdateOne { - _u.mutation.ClearProvisionBuckets() - return _u -} - -// RemoveProvisionBucketIDs removes the "provision_buckets" edge to ProvisionBucket entities by IDs. -func (_u *FiatCurrencyUpdateOne) RemoveProvisionBucketIDs(ids ...int) *FiatCurrencyUpdateOne { - _u.mutation.RemoveProvisionBucketIDs(ids...) - return _u -} - -// RemoveProvisionBuckets removes "provision_buckets" edges to ProvisionBucket entities. -func (_u *FiatCurrencyUpdateOne) RemoveProvisionBuckets(v ...*ProvisionBucket) *FiatCurrencyUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveProvisionBucketIDs(ids...) -} - // ClearInstitutions clears all "institutions" edges to the Institution entity. func (_u *FiatCurrencyUpdateOne) ClearInstitutions() *FiatCurrencyUpdateOne { _u.mutation.ClearInstitutions() @@ -1083,51 +965,6 @@ func (_u *FiatCurrencyUpdateOne) sqlSave(ctx context.Context) (_node *FiatCurren } _spec.Edges.Add = append(_spec.Edges.Add, edge) } - if _u.mutation.ProvisionBucketsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: fiatcurrency.ProvisionBucketsTable, - Columns: []string{fiatcurrency.ProvisionBucketsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedProvisionBucketsIDs(); len(nodes) > 0 && !_u.mutation.ProvisionBucketsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: fiatcurrency.ProvisionBucketsTable, - Columns: []string{fiatcurrency.ProvisionBucketsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.ProvisionBucketsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: fiatcurrency.ProvisionBucketsTable, - Columns: []string{fiatcurrency.ProvisionBucketsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } if _u.mutation.InstitutionsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/ent/hook/hook.go b/ent/hook/hook.go index 5b0e632f5..4e33f75ad 100644 --- a/ent/hook/hook.go +++ b/ent/hook/hook.go @@ -129,6 +129,18 @@ func (f PaymentWebhookFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Val return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PaymentWebhookMutation", m) } +// The ProviderAssignmentRunFunc type is an adapter to allow the use of ordinary +// function as ProviderAssignmentRun mutator. +type ProviderAssignmentRunFunc func(context.Context, *ent.ProviderAssignmentRunMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f ProviderAssignmentRunFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.ProviderAssignmentRunMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ProviderAssignmentRunMutation", m) +} + // The ProviderBalancesFunc type is an adapter to allow the use of ordinary // function as ProviderBalances mutator. type ProviderBalancesFunc func(context.Context, *ent.ProviderBalancesMutation) (ent.Value, error) @@ -165,6 +177,18 @@ func (f ProviderOrderTokenFunc) Mutate(ctx context.Context, m ent.Mutation) (ent return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ProviderOrderTokenMutation", m) } +// The ProviderOrderTokenScoreHistoryFunc type is an adapter to allow the use of ordinary +// function as ProviderOrderTokenScoreHistory mutator. +type ProviderOrderTokenScoreHistoryFunc func(context.Context, *ent.ProviderOrderTokenScoreHistoryMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f ProviderOrderTokenScoreHistoryFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.ProviderOrderTokenScoreHistoryMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ProviderOrderTokenScoreHistoryMutation", m) +} + // The ProviderProfileFunc type is an adapter to allow the use of ordinary // function as ProviderProfile mutator. type ProviderProfileFunc func(context.Context, *ent.ProviderProfileMutation) (ent.Value, error) diff --git a/ent/migrate/migrations/20260324013141_provider_selection_phase1.sql b/ent/migrate/migrations/20260324013141_provider_selection_phase1.sql new file mode 100644 index 000000000..b2c53a0aa --- /dev/null +++ b/ent/migrate/migrations/20260324013141_provider_selection_phase1.sql @@ -0,0 +1,48 @@ +-- Modify "payment_orders" table +ALTER TABLE "payment_orders" DROP CONSTRAINT "payment_orders_provision_buckets_payment_orders", ADD COLUMN "assignment_market_buy_rate" double precision NULL, ADD COLUMN "assignment_market_sell_rate" double precision NULL; +-- Modify "provision_buckets" table +ALTER TABLE "provision_buckets" DROP CONSTRAINT "provision_buckets_fiat_currencies_provision_buckets", ALTER COLUMN "fiat_currency_provision_buckets" DROP NOT NULL; +-- Modify "provider_order_tokens" table +ALTER TABLE "provider_order_tokens" ADD COLUMN "score" double precision NOT NULL DEFAULT 0.0, ADD COLUMN "last_order_assigned_at" timestamptz NULL; +-- Create "provider_assignment_runs" table +CREATE TABLE "provider_assignment_runs" ( + "id" uuid NOT NULL, + "assigned_provider_id" character varying NULL, + "attempted_at" timestamptz NOT NULL, + "trigger" character varying NOT NULL, + "result" character varying NOT NULL, + "used_fallback" boolean NOT NULL DEFAULT false, + "market_buy_rate_snapshot" double precision NULL, + "market_sell_rate_snapshot" double precision NULL, + "error_message" text NULL, + "payment_order_provider_assignment_runs" uuid NOT NULL, + "provider_order_token_assignment_runs" bigint NULL, + PRIMARY KEY ("id"), + CONSTRAINT "provider_assignment_runs_payme_84d7fae6191fe88595e67cd16cb3084e" FOREIGN KEY ("payment_order_provider_assignment_runs") REFERENCES "payment_orders" ("id") ON UPDATE NO ACTION ON DELETE CASCADE, + CONSTRAINT "provider_assignment_runs_provider_order_tokens_assignment_runs" FOREIGN KEY ("provider_order_token_assignment_runs") REFERENCES "provider_order_tokens" ("id") ON UPDATE NO ACTION ON DELETE CASCADE +); +-- Create index "providerassignmentrun_payment_order_provider_assignment_runs" to table: "provider_assignment_runs" +CREATE INDEX "providerassignmentrun_payment_order_provider_assignment_runs" ON "provider_assignment_runs" ("payment_order_provider_assignment_runs"); +-- Create index "providerassignmentrun_provider_order_token_assignment_runs" to table: "provider_assignment_runs" +CREATE INDEX "providerassignmentrun_provider_order_token_assignment_runs" ON "provider_assignment_runs" ("provider_order_token_assignment_runs"); +-- Create "provider_order_token_score_histories" table +CREATE TABLE "provider_order_token_score_histories" ( + "id" uuid NOT NULL, + "created_at" timestamptz NOT NULL, + "updated_at" timestamptz NOT NULL, + "event_type" character varying NOT NULL, + "delta" double precision NOT NULL, + "payment_order_provider_order_token_score_histories" uuid NOT NULL, + "provider_order_token_score_histories" bigint NOT NULL, + PRIMARY KEY ("id"), + CONSTRAINT "provider_order_token_score_his_050ed76dac5be457330d8b5fc14ea929" FOREIGN KEY ("provider_order_token_score_histories") REFERENCES "provider_order_tokens" ("id") ON UPDATE NO ACTION ON DELETE CASCADE, + CONSTRAINT "provider_order_token_score_his_86d4d0f0f46280f11b0b15de2006a55a" FOREIGN KEY ("payment_order_provider_order_token_score_histories") REFERENCES "payment_orders" ("id") ON UPDATE NO ACTION ON DELETE CASCADE +); +-- Create index "providerordertokenscorehistory_0743974523bc1cf1715387b50cc6a2e6" to table: "provider_order_token_score_histories" +CREATE INDEX "providerordertokenscorehistory_0743974523bc1cf1715387b50cc6a2e6" ON "provider_order_token_score_histories" ("provider_order_token_score_histories"); +-- Create index "providerordertokenscorehistory_c7a6969c06477946e88e267abce7f037" to table: "provider_order_token_score_histories" +CREATE INDEX "providerordertokenscorehistory_c7a6969c06477946e88e267abce7f037" ON "provider_order_token_score_histories" ("payment_order_provider_order_token_score_histories"); +-- Create index "providerordertokenscorehistory_c8746269c38251583432217f8d24daef" to table: "provider_order_token_score_histories" +CREATE UNIQUE INDEX "providerordertokenscorehistory_c8746269c38251583432217f8d24daef" ON "provider_order_token_score_histories" ("event_type", "payment_order_provider_order_token_score_histories"); +-- Add pk ranges for ('provider_assignment_runs'),('provider_order_token_score_histories') tables +INSERT INTO "ent_types" ("type") VALUES ('provider_assignment_runs'), ('provider_order_token_score_histories'); diff --git a/ent/migrate/migrations/atlas.sum b/ent/migrate/migrations/atlas.sum index a2c0a60c0..c51e53179 100644 --- a/ent/migrate/migrations/atlas.sum +++ b/ent/migrate/migrations/atlas.sum @@ -1,4 +1,4 @@ -h1:XGc0qj58R4xn+fMjZJqIdeosU14dhOs5U5YvG/w+7EM= +h1:xSXCANgPcOjw2l9gHy10VIVTU7nOHf7AWZGRHZvfLD4= 20240118234246_initial.sql h1:dYuYBqns33WT+3p8VQvbKUP62k3k6w6h8S+FqNqgSvU= 20240130122324_order_from_address.sql h1:mMVI2iBUd1roIYLUqu0d2jZ7+B6exppRN8qqn+aIHx4= 20240202010744_fees_on_order.sql h1:P7ngxZKqDKefBM5vk6M3kbWeMPVwbZ4MZVcLBjEfS34= @@ -80,3 +80,4 @@ h1:XGc0qj58R4xn+fMjZJqIdeosU14dhOs5U5YvG/w+7EM= 20260310185904_add_wallet_service.sql h1:eG863f+be3Cac7dzU6+rOJ+tVEVIouatPBlIGtKI+VY= 20260313024459_onramp_bump.sql h1:Px+OHr6ARShsDgaMq95Io5cY36KmfrSYSuk+KGfDvz4= 20260318151618_txlog_edge.sql h1:kgqV1eVk/bpOO0l8RGkLLJZ4EpQ5IaPS9MLbLCxgIao= +20260324013141_provider_selection_phase1.sql h1:1PGfDecxHFJWLCPa5kFU+vvegqZecAknCG1yvxCyufg= diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go index 3db149006..39be955e1 100644 --- a/ent/migrate/schema.go +++ b/ent/migrate/schema.go @@ -218,9 +218,11 @@ var ( {Name: "direction", Type: field.TypeEnum, Enums: []string{"offramp", "onramp"}, Default: "offramp"}, {Name: "order_type", Type: field.TypeEnum, Enums: []string{"otc", "regular"}, Default: "regular"}, {Name: "fallback_tried_at", Type: field.TypeTime, Nullable: true}, + {Name: "assignment_market_buy_rate", Type: field.TypeFloat64, Nullable: true}, + {Name: "assignment_market_sell_rate", Type: field.TypeFloat64, Nullable: true}, + {Name: "provision_bucket_payment_orders", Type: field.TypeInt, Nullable: true}, {Name: "api_key_payment_orders", Type: field.TypeUUID, Nullable: true}, {Name: "provider_profile_assigned_orders", Type: field.TypeString, Nullable: true}, - {Name: "provision_bucket_payment_orders", Type: field.TypeInt, Nullable: true}, {Name: "sender_profile_payment_orders", Type: field.TypeUUID, Nullable: true}, {Name: "token_payment_orders", Type: field.TypeInt}, } @@ -232,31 +234,25 @@ var ( ForeignKeys: []*schema.ForeignKey{ { Symbol: "payment_orders_api_keys_payment_orders", - Columns: []*schema.Column{PaymentOrdersColumns[38]}, + Columns: []*schema.Column{PaymentOrdersColumns[41]}, RefColumns: []*schema.Column{APIKeysColumns[0]}, OnDelete: schema.SetNull, }, { Symbol: "payment_orders_provider_profiles_assigned_orders", - Columns: []*schema.Column{PaymentOrdersColumns[39]}, + Columns: []*schema.Column{PaymentOrdersColumns[42]}, RefColumns: []*schema.Column{ProviderProfilesColumns[0]}, OnDelete: schema.Cascade, }, - { - Symbol: "payment_orders_provision_buckets_payment_orders", - Columns: []*schema.Column{PaymentOrdersColumns[40]}, - RefColumns: []*schema.Column{ProvisionBucketsColumns[0]}, - OnDelete: schema.SetNull, - }, { Symbol: "payment_orders_sender_profiles_payment_orders", - Columns: []*schema.Column{PaymentOrdersColumns[41]}, + Columns: []*schema.Column{PaymentOrdersColumns[43]}, RefColumns: []*schema.Column{SenderProfilesColumns[0]}, OnDelete: schema.SetNull, }, { Symbol: "payment_orders_tokens_payment_orders", - Columns: []*schema.Column{PaymentOrdersColumns[42]}, + Columns: []*schema.Column{PaymentOrdersColumns[44]}, RefColumns: []*schema.Column{TokensColumns[0]}, OnDelete: schema.Cascade, }, @@ -265,7 +261,7 @@ var ( { Name: "paymentorder_gateway_id_rate_tx_hash_block_number_institution_account_identifier_account_name_memo_direction_refund_or_recipient_address_token_payment_orders", Unique: true, - Columns: []*schema.Column{PaymentOrdersColumns[17], PaymentOrdersColumns[4], PaymentOrdersColumns[14], PaymentOrdersColumns[15], PaymentOrdersColumns[25], PaymentOrdersColumns[26], PaymentOrdersColumns[27], PaymentOrdersColumns[33], PaymentOrdersColumns[35], PaymentOrdersColumns[19], PaymentOrdersColumns[42]}, + Columns: []*schema.Column{PaymentOrdersColumns[17], PaymentOrdersColumns[4], PaymentOrdersColumns[14], PaymentOrdersColumns[15], PaymentOrdersColumns[25], PaymentOrdersColumns[26], PaymentOrdersColumns[27], PaymentOrdersColumns[33], PaymentOrdersColumns[35], PaymentOrdersColumns[19], PaymentOrdersColumns[44]}, }, }, } @@ -325,6 +321,52 @@ var ( }, }, } + // ProviderAssignmentRunsColumns holds the columns for the "provider_assignment_runs" table. + ProviderAssignmentRunsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "assigned_provider_id", Type: field.TypeString, Nullable: true, Size: 255}, + {Name: "attempted_at", Type: field.TypeTime}, + {Name: "trigger", Type: field.TypeString, Size: 64}, + {Name: "result", Type: field.TypeString, Size: 32}, + {Name: "used_fallback", Type: field.TypeBool, Default: false}, + {Name: "market_buy_rate_snapshot", Type: field.TypeFloat64, Nullable: true}, + {Name: "market_sell_rate_snapshot", Type: field.TypeFloat64, Nullable: true}, + {Name: "error_message", Type: field.TypeString, Nullable: true, Size: 2147483647}, + {Name: "payment_order_provider_assignment_runs", Type: field.TypeUUID}, + {Name: "provider_order_token_assignment_runs", Type: field.TypeInt, Nullable: true}, + } + // ProviderAssignmentRunsTable holds the schema information for the "provider_assignment_runs" table. + ProviderAssignmentRunsTable = &schema.Table{ + Name: "provider_assignment_runs", + Columns: ProviderAssignmentRunsColumns, + PrimaryKey: []*schema.Column{ProviderAssignmentRunsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "provider_assignment_runs_payment_orders_provider_assignment_runs", + Columns: []*schema.Column{ProviderAssignmentRunsColumns[9]}, + RefColumns: []*schema.Column{PaymentOrdersColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "provider_assignment_runs_provider_order_tokens_assignment_runs", + Columns: []*schema.Column{ProviderAssignmentRunsColumns[10]}, + RefColumns: []*schema.Column{ProviderOrderTokensColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "providerassignmentrun_payment_order_provider_assignment_runs", + Unique: false, + Columns: []*schema.Column{ProviderAssignmentRunsColumns[9]}, + }, + { + Name: "providerassignmentrun_provider_order_token_assignment_runs", + Unique: false, + Columns: []*schema.Column{ProviderAssignmentRunsColumns[10]}, + }, + }, + } // ProviderBalancesColumns holds the columns for the "provider_balances" table. ProviderBalancesColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -424,6 +466,8 @@ var ( {Name: "settlement_address", Type: field.TypeString, Nullable: true}, {Name: "payout_address", Type: field.TypeString, Nullable: true}, {Name: "network", Type: field.TypeString}, + {Name: "score", Type: field.TypeFloat64}, + {Name: "last_order_assigned_at", Type: field.TypeTime, Nullable: true}, {Name: "fiat_currency_provider_order_tokens", Type: field.TypeUUID}, {Name: "provider_profile_order_tokens", Type: field.TypeString}, {Name: "token_provider_order_tokens", Type: field.TypeInt}, @@ -436,19 +480,19 @@ var ( ForeignKeys: []*schema.ForeignKey{ { Symbol: "provider_order_tokens_fiat_currencies_provider_order_tokens", - Columns: []*schema.Column{ProviderOrderTokensColumns[15]}, + Columns: []*schema.Column{ProviderOrderTokensColumns[17]}, RefColumns: []*schema.Column{FiatCurrenciesColumns[0]}, OnDelete: schema.Cascade, }, { Symbol: "provider_order_tokens_provider_profiles_order_tokens", - Columns: []*schema.Column{ProviderOrderTokensColumns[16]}, + Columns: []*schema.Column{ProviderOrderTokensColumns[18]}, RefColumns: []*schema.Column{ProviderProfilesColumns[0]}, OnDelete: schema.Cascade, }, { Symbol: "provider_order_tokens_tokens_provider_order_tokens", - Columns: []*schema.Column{ProviderOrderTokensColumns[17]}, + Columns: []*schema.Column{ProviderOrderTokensColumns[19]}, RefColumns: []*schema.Column{TokensColumns[0]}, OnDelete: schema.Cascade, }, @@ -457,7 +501,54 @@ var ( { Name: "providerordertoken_network_provider_profile_order_tokens_token_provider_order_tokens_fiat_currency_provider_order_tokens", Unique: true, - Columns: []*schema.Column{ProviderOrderTokensColumns[14], ProviderOrderTokensColumns[16], ProviderOrderTokensColumns[17], ProviderOrderTokensColumns[15]}, + Columns: []*schema.Column{ProviderOrderTokensColumns[14], ProviderOrderTokensColumns[18], ProviderOrderTokensColumns[19], ProviderOrderTokensColumns[17]}, + }, + }, + } + // ProviderOrderTokenScoreHistoriesColumns holds the columns for the "provider_order_token_score_histories" table. + ProviderOrderTokenScoreHistoriesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "event_type", Type: field.TypeString, Size: 64}, + {Name: "delta", Type: field.TypeFloat64}, + {Name: "payment_order_provider_order_token_score_histories", Type: field.TypeUUID}, + {Name: "provider_order_token_score_histories", Type: field.TypeInt}, + } + // ProviderOrderTokenScoreHistoriesTable holds the schema information for the "provider_order_token_score_histories" table. + ProviderOrderTokenScoreHistoriesTable = &schema.Table{ + Name: "provider_order_token_score_histories", + Columns: ProviderOrderTokenScoreHistoriesColumns, + PrimaryKey: []*schema.Column{ProviderOrderTokenScoreHistoriesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "provider_order_token_score_histories_payment_orders_provider_order_token_score_histories", + Columns: []*schema.Column{ProviderOrderTokenScoreHistoriesColumns[5]}, + RefColumns: []*schema.Column{PaymentOrdersColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "provider_order_token_score_histories_provider_order_tokens_score_histories", + Columns: []*schema.Column{ProviderOrderTokenScoreHistoriesColumns[6]}, + RefColumns: []*schema.Column{ProviderOrderTokensColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "providerordertokenscorehistory_event_type_payment_order_provider_order_token_score_histories", + Unique: true, + Columns: []*schema.Column{ProviderOrderTokenScoreHistoriesColumns[3], ProviderOrderTokenScoreHistoriesColumns[5]}, + }, + { + Name: "providerordertokenscorehistory_payment_order_provider_order_token_score_histories", + Unique: false, + Columns: []*schema.Column{ProviderOrderTokenScoreHistoriesColumns[5]}, + }, + { + Name: "providerordertokenscorehistory_provider_order_token_score_histories", + Unique: false, + Columns: []*schema.Column{ProviderOrderTokenScoreHistoriesColumns[6]}, }, }, } @@ -514,21 +605,13 @@ var ( {Name: "min_amount", Type: field.TypeFloat64}, {Name: "max_amount", Type: field.TypeFloat64}, {Name: "created_at", Type: field.TypeTime}, - {Name: "fiat_currency_provision_buckets", Type: field.TypeUUID}, + {Name: "fiat_currency_provision_buckets", Type: field.TypeUUID, Nullable: true}, } // ProvisionBucketsTable holds the schema information for the "provision_buckets" table. ProvisionBucketsTable = &schema.Table{ Name: "provision_buckets", Columns: ProvisionBucketsColumns, PrimaryKey: []*schema.Column{ProvisionBucketsColumns[0]}, - ForeignKeys: []*schema.ForeignKey{ - { - Symbol: "provision_buckets_fiat_currencies_provision_buckets", - Columns: []*schema.Column{ProvisionBucketsColumns[4]}, - RefColumns: []*schema.Column{FiatCurrenciesColumns[0]}, - OnDelete: schema.Cascade, - }, - }, } // SenderOrderTokensColumns holds the columns for the "sender_order_tokens" table. SenderOrderTokensColumns = []*schema.Column{ @@ -715,31 +798,6 @@ var ( Columns: WebhookRetryAttemptsColumns, PrimaryKey: []*schema.Column{WebhookRetryAttemptsColumns[0]}, } - // ProvisionBucketProviderProfilesColumns holds the columns for the "provision_bucket_provider_profiles" table. - ProvisionBucketProviderProfilesColumns = []*schema.Column{ - {Name: "provision_bucket_id", Type: field.TypeInt}, - {Name: "provider_profile_id", Type: field.TypeString}, - } - // ProvisionBucketProviderProfilesTable holds the schema information for the "provision_bucket_provider_profiles" table. - ProvisionBucketProviderProfilesTable = &schema.Table{ - Name: "provision_bucket_provider_profiles", - Columns: ProvisionBucketProviderProfilesColumns, - PrimaryKey: []*schema.Column{ProvisionBucketProviderProfilesColumns[0], ProvisionBucketProviderProfilesColumns[1]}, - ForeignKeys: []*schema.ForeignKey{ - { - Symbol: "provision_bucket_provider_profiles_provision_bucket_id", - Columns: []*schema.Column{ProvisionBucketProviderProfilesColumns[0]}, - RefColumns: []*schema.Column{ProvisionBucketsColumns[0]}, - OnDelete: schema.Cascade, - }, - { - Symbol: "provision_bucket_provider_profiles_provider_profile_id", - Columns: []*schema.Column{ProvisionBucketProviderProfilesColumns[1]}, - RefColumns: []*schema.Column{ProviderProfilesColumns[0]}, - OnDelete: schema.Cascade, - }, - }, - } // Tables holds all the tables in the schema. Tables = []*schema.Table{ APIKeysTable, @@ -752,9 +810,11 @@ var ( PaymentOrdersTable, PaymentOrderFulfillmentsTable, PaymentWebhooksTable, + ProviderAssignmentRunsTable, ProviderBalancesTable, ProviderFiatAccountsTable, ProviderOrderTokensTable, + ProviderOrderTokenScoreHistoriesTable, ProviderProfilesTable, ProviderRatingsTable, ProvisionBucketsTable, @@ -765,7 +825,6 @@ var ( UsersTable, VerificationTokensTable, WebhookRetryAttemptsTable, - ProvisionBucketProviderProfilesTable, } ) @@ -777,12 +836,13 @@ func init() { KybProfilesTable.ForeignKeys[0].RefTable = UsersTable PaymentOrdersTable.ForeignKeys[0].RefTable = APIKeysTable PaymentOrdersTable.ForeignKeys[1].RefTable = ProviderProfilesTable - PaymentOrdersTable.ForeignKeys[2].RefTable = ProvisionBucketsTable - PaymentOrdersTable.ForeignKeys[3].RefTable = SenderProfilesTable - PaymentOrdersTable.ForeignKeys[4].RefTable = TokensTable + PaymentOrdersTable.ForeignKeys[2].RefTable = SenderProfilesTable + PaymentOrdersTable.ForeignKeys[3].RefTable = TokensTable PaymentOrderFulfillmentsTable.ForeignKeys[0].RefTable = PaymentOrdersTable PaymentWebhooksTable.ForeignKeys[0].RefTable = NetworksTable PaymentWebhooksTable.ForeignKeys[1].RefTable = PaymentOrdersTable + ProviderAssignmentRunsTable.ForeignKeys[0].RefTable = PaymentOrdersTable + ProviderAssignmentRunsTable.ForeignKeys[1].RefTable = ProviderOrderTokensTable ProviderBalancesTable.ForeignKeys[0].RefTable = FiatCurrenciesTable ProviderBalancesTable.ForeignKeys[1].RefTable = ProviderProfilesTable ProviderBalancesTable.ForeignKeys[2].RefTable = TokensTable @@ -790,15 +850,14 @@ func init() { ProviderOrderTokensTable.ForeignKeys[0].RefTable = FiatCurrenciesTable ProviderOrderTokensTable.ForeignKeys[1].RefTable = ProviderProfilesTable ProviderOrderTokensTable.ForeignKeys[2].RefTable = TokensTable + ProviderOrderTokenScoreHistoriesTable.ForeignKeys[0].RefTable = PaymentOrdersTable + ProviderOrderTokenScoreHistoriesTable.ForeignKeys[1].RefTable = ProviderOrderTokensTable ProviderProfilesTable.ForeignKeys[0].RefTable = UsersTable ProviderRatingsTable.ForeignKeys[0].RefTable = ProviderProfilesTable - ProvisionBucketsTable.ForeignKeys[0].RefTable = FiatCurrenciesTable SenderOrderTokensTable.ForeignKeys[0].RefTable = SenderProfilesTable SenderOrderTokensTable.ForeignKeys[1].RefTable = TokensTable SenderProfilesTable.ForeignKeys[0].RefTable = UsersTable TokensTable.ForeignKeys[0].RefTable = NetworksTable TransactionLogsTable.ForeignKeys[0].RefTable = PaymentOrdersTable VerificationTokensTable.ForeignKeys[0].RefTable = UsersTable - ProvisionBucketProviderProfilesTable.ForeignKeys[0].RefTable = ProvisionBucketsTable - ProvisionBucketProviderProfilesTable.ForeignKeys[1].RefTable = ProviderProfilesTable } diff --git a/ent/mutation.go b/ent/mutation.go index f65d1ea9c..ff49090e3 100644 --- a/ent/mutation.go +++ b/ent/mutation.go @@ -23,9 +23,11 @@ import ( "github.com/paycrest/aggregator/ent/paymentorderfulfillment" "github.com/paycrest/aggregator/ent/paymentwebhook" "github.com/paycrest/aggregator/ent/predicate" + "github.com/paycrest/aggregator/ent/providerassignmentrun" "github.com/paycrest/aggregator/ent/providerbalances" "github.com/paycrest/aggregator/ent/providerfiataccount" "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/providerrating" "github.com/paycrest/aggregator/ent/provisionbucket" @@ -48,29 +50,31 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. - TypeAPIKey = "APIKey" - TypeBeneficialOwner = "BeneficialOwner" - TypeFiatCurrency = "FiatCurrency" - TypeIdentityVerificationRequest = "IdentityVerificationRequest" - TypeInstitution = "Institution" - TypeKYBProfile = "KYBProfile" - TypeNetwork = "Network" - TypePaymentOrder = "PaymentOrder" - TypePaymentOrderFulfillment = "PaymentOrderFulfillment" - TypePaymentWebhook = "PaymentWebhook" - TypeProviderBalances = "ProviderBalances" - TypeProviderFiatAccount = "ProviderFiatAccount" - TypeProviderOrderToken = "ProviderOrderToken" - TypeProviderProfile = "ProviderProfile" - TypeProviderRating = "ProviderRating" - TypeProvisionBucket = "ProvisionBucket" - TypeSenderOrderToken = "SenderOrderToken" - TypeSenderProfile = "SenderProfile" - TypeToken = "Token" - TypeTransactionLog = "TransactionLog" - TypeUser = "User" - TypeVerificationToken = "VerificationToken" - TypeWebhookRetryAttempt = "WebhookRetryAttempt" + TypeAPIKey = "APIKey" + TypeBeneficialOwner = "BeneficialOwner" + TypeFiatCurrency = "FiatCurrency" + TypeIdentityVerificationRequest = "IdentityVerificationRequest" + TypeInstitution = "Institution" + TypeKYBProfile = "KYBProfile" + TypeNetwork = "Network" + TypePaymentOrder = "PaymentOrder" + TypePaymentOrderFulfillment = "PaymentOrderFulfillment" + TypePaymentWebhook = "PaymentWebhook" + TypeProviderAssignmentRun = "ProviderAssignmentRun" + TypeProviderBalances = "ProviderBalances" + TypeProviderFiatAccount = "ProviderFiatAccount" + TypeProviderOrderToken = "ProviderOrderToken" + TypeProviderOrderTokenScoreHistory = "ProviderOrderTokenScoreHistory" + TypeProviderProfile = "ProviderProfile" + TypeProviderRating = "ProviderRating" + TypeProvisionBucket = "ProvisionBucket" + TypeSenderOrderToken = "SenderOrderToken" + TypeSenderProfile = "SenderProfile" + TypeToken = "Token" + TypeTransactionLog = "TransactionLog" + TypeUser = "User" + TypeVerificationToken = "VerificationToken" + TypeWebhookRetryAttempt = "WebhookRetryAttempt" ) // APIKeyMutation represents an operation that mutates the APIKey nodes in the graph. @@ -1420,9 +1424,6 @@ type FiatCurrencyMutation struct { provider_balances map[uuid.UUID]struct{} removedprovider_balances map[uuid.UUID]struct{} clearedprovider_balances bool - provision_buckets map[int]struct{} - removedprovision_buckets map[int]struct{} - clearedprovision_buckets bool institutions map[int]struct{} removedinstitutions map[int]struct{} clearedinstitutions bool @@ -2040,60 +2041,6 @@ func (m *FiatCurrencyMutation) ResetProviderBalances() { m.removedprovider_balances = nil } -// AddProvisionBucketIDs adds the "provision_buckets" edge to the ProvisionBucket entity by ids. -func (m *FiatCurrencyMutation) AddProvisionBucketIDs(ids ...int) { - if m.provision_buckets == nil { - m.provision_buckets = make(map[int]struct{}) - } - for i := range ids { - m.provision_buckets[ids[i]] = struct{}{} - } -} - -// ClearProvisionBuckets clears the "provision_buckets" edge to the ProvisionBucket entity. -func (m *FiatCurrencyMutation) ClearProvisionBuckets() { - m.clearedprovision_buckets = true -} - -// ProvisionBucketsCleared reports if the "provision_buckets" edge to the ProvisionBucket entity was cleared. -func (m *FiatCurrencyMutation) ProvisionBucketsCleared() bool { - return m.clearedprovision_buckets -} - -// RemoveProvisionBucketIDs removes the "provision_buckets" edge to the ProvisionBucket entity by IDs. -func (m *FiatCurrencyMutation) RemoveProvisionBucketIDs(ids ...int) { - if m.removedprovision_buckets == nil { - m.removedprovision_buckets = make(map[int]struct{}) - } - for i := range ids { - delete(m.provision_buckets, ids[i]) - m.removedprovision_buckets[ids[i]] = struct{}{} - } -} - -// RemovedProvisionBuckets returns the removed IDs of the "provision_buckets" edge to the ProvisionBucket entity. -func (m *FiatCurrencyMutation) RemovedProvisionBucketsIDs() (ids []int) { - for id := range m.removedprovision_buckets { - ids = append(ids, id) - } - return -} - -// ProvisionBucketsIDs returns the "provision_buckets" edge IDs in the mutation. -func (m *FiatCurrencyMutation) ProvisionBucketsIDs() (ids []int) { - for id := range m.provision_buckets { - ids = append(ids, id) - } - return -} - -// ResetProvisionBuckets resets all changes to the "provision_buckets" edge. -func (m *FiatCurrencyMutation) ResetProvisionBuckets() { - m.provision_buckets = nil - m.clearedprovision_buckets = false - m.removedprovision_buckets = nil -} - // AddInstitutionIDs adds the "institutions" edge to the Institution entity by ids. func (m *FiatCurrencyMutation) AddInstitutionIDs(ids ...int) { if m.institutions == nil { @@ -2542,13 +2489,10 @@ func (m *FiatCurrencyMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *FiatCurrencyMutation) AddedEdges() []string { - edges := make([]string, 0, 4) + edges := make([]string, 0, 3) if m.provider_balances != nil { edges = append(edges, fiatcurrency.EdgeProviderBalances) } - if m.provision_buckets != nil { - edges = append(edges, fiatcurrency.EdgeProvisionBuckets) - } if m.institutions != nil { edges = append(edges, fiatcurrency.EdgeInstitutions) } @@ -2568,12 +2512,6 @@ func (m *FiatCurrencyMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids - case fiatcurrency.EdgeProvisionBuckets: - ids := make([]ent.Value, 0, len(m.provision_buckets)) - for id := range m.provision_buckets { - ids = append(ids, id) - } - return ids case fiatcurrency.EdgeInstitutions: ids := make([]ent.Value, 0, len(m.institutions)) for id := range m.institutions { @@ -2592,13 +2530,10 @@ func (m *FiatCurrencyMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *FiatCurrencyMutation) RemovedEdges() []string { - edges := make([]string, 0, 4) + edges := make([]string, 0, 3) if m.removedprovider_balances != nil { edges = append(edges, fiatcurrency.EdgeProviderBalances) } - if m.removedprovision_buckets != nil { - edges = append(edges, fiatcurrency.EdgeProvisionBuckets) - } if m.removedinstitutions != nil { edges = append(edges, fiatcurrency.EdgeInstitutions) } @@ -2618,12 +2553,6 @@ func (m *FiatCurrencyMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids - case fiatcurrency.EdgeProvisionBuckets: - ids := make([]ent.Value, 0, len(m.removedprovision_buckets)) - for id := range m.removedprovision_buckets { - ids = append(ids, id) - } - return ids case fiatcurrency.EdgeInstitutions: ids := make([]ent.Value, 0, len(m.removedinstitutions)) for id := range m.removedinstitutions { @@ -2642,13 +2571,10 @@ func (m *FiatCurrencyMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *FiatCurrencyMutation) ClearedEdges() []string { - edges := make([]string, 0, 4) + edges := make([]string, 0, 3) if m.clearedprovider_balances { edges = append(edges, fiatcurrency.EdgeProviderBalances) } - if m.clearedprovision_buckets { - edges = append(edges, fiatcurrency.EdgeProvisionBuckets) - } if m.clearedinstitutions { edges = append(edges, fiatcurrency.EdgeInstitutions) } @@ -2664,8 +2590,6 @@ func (m *FiatCurrencyMutation) EdgeCleared(name string) bool { switch name { case fiatcurrency.EdgeProviderBalances: return m.clearedprovider_balances - case fiatcurrency.EdgeProvisionBuckets: - return m.clearedprovision_buckets case fiatcurrency.EdgeInstitutions: return m.clearedinstitutions case fiatcurrency.EdgeProviderOrderTokens: @@ -2689,9 +2613,6 @@ func (m *FiatCurrencyMutation) ResetEdge(name string) error { case fiatcurrency.EdgeProviderBalances: m.ResetProviderBalances() return nil - case fiatcurrency.EdgeProvisionBuckets: - m.ResetProvisionBuckets() - return nil case fiatcurrency.EdgeInstitutions: m.ResetInstitutions() return nil @@ -6504,80 +6425,90 @@ func (m *NetworkMutation) ResetEdge(name string) error { // PaymentOrderMutation represents an operation that mutates the PaymentOrder nodes in the graph. type PaymentOrderMutation struct { config - op Op - typ string - id *uuid.UUID - created_at *time.Time - updated_at *time.Time - amount *decimal.Decimal - addamount *decimal.Decimal - rate *decimal.Decimal - addrate *decimal.Decimal - amount_in_usd *decimal.Decimal - addamount_in_usd *decimal.Decimal - amount_paid *decimal.Decimal - addamount_paid *decimal.Decimal - amount_returned *decimal.Decimal - addamount_returned *decimal.Decimal - percent_settled *decimal.Decimal - addpercent_settled *decimal.Decimal - sender_fee *decimal.Decimal - addsender_fee *decimal.Decimal - network_fee *decimal.Decimal - addnetwork_fee *decimal.Decimal - protocol_fee *decimal.Decimal - addprotocol_fee *decimal.Decimal - order_percent *decimal.Decimal - addorder_percent *decimal.Decimal - fee_percent *decimal.Decimal - addfee_percent *decimal.Decimal - tx_hash *string - block_number *int64 - addblock_number *int64 - message_hash *string - gateway_id *string - from_address *string - refund_or_recipient_address *string - receive_address *string - receive_address_salt *[]byte - receive_address_expiry *time.Time - fee_address *string - indexer_created_at *time.Time - institution *string - account_identifier *string - account_name *string - metadata *map[string]interface{} - sender *string - reference *string - cancellation_count *int - addcancellation_count *int - cancellation_reasons *[]string - appendcancellation_reasons []string - memo *string - status *paymentorder.Status - direction *paymentorder.Direction - order_type *paymentorder.OrderType - fallback_tried_at *time.Time - clearedFields map[string]struct{} - token *int - clearedtoken bool - sender_profile *uuid.UUID - clearedsender_profile bool - payment_webhook *uuid.UUID - clearedpayment_webhook bool - provider *string - clearedprovider bool - provision_bucket *int - clearedprovision_bucket bool - fulfillments map[uuid.UUID]struct{} - removedfulfillments map[uuid.UUID]struct{} - clearedfulfillments bool - transactions map[uuid.UUID]struct{} - removedtransactions map[uuid.UUID]struct{} - clearedtransactions bool - done bool - oldValue func(context.Context) (*PaymentOrder, error) - predicates []predicate.PaymentOrder + op Op + typ string + id *uuid.UUID + created_at *time.Time + updated_at *time.Time + amount *decimal.Decimal + addamount *decimal.Decimal + rate *decimal.Decimal + addrate *decimal.Decimal + amount_in_usd *decimal.Decimal + addamount_in_usd *decimal.Decimal + amount_paid *decimal.Decimal + addamount_paid *decimal.Decimal + amount_returned *decimal.Decimal + addamount_returned *decimal.Decimal + percent_settled *decimal.Decimal + addpercent_settled *decimal.Decimal + sender_fee *decimal.Decimal + addsender_fee *decimal.Decimal + network_fee *decimal.Decimal + addnetwork_fee *decimal.Decimal + protocol_fee *decimal.Decimal + addprotocol_fee *decimal.Decimal + order_percent *decimal.Decimal + addorder_percent *decimal.Decimal + fee_percent *decimal.Decimal + addfee_percent *decimal.Decimal + tx_hash *string + block_number *int64 + addblock_number *int64 + message_hash *string + gateway_id *string + from_address *string + refund_or_recipient_address *string + receive_address *string + receive_address_salt *[]byte + receive_address_expiry *time.Time + fee_address *string + indexer_created_at *time.Time + institution *string + account_identifier *string + account_name *string + metadata *map[string]interface{} + sender *string + reference *string + cancellation_count *int + addcancellation_count *int + cancellation_reasons *[]string + appendcancellation_reasons []string + memo *string + status *paymentorder.Status + direction *paymentorder.Direction + order_type *paymentorder.OrderType + fallback_tried_at *time.Time + assignment_market_buy_rate *decimal.Decimal + addassignment_market_buy_rate *decimal.Decimal + assignment_market_sell_rate *decimal.Decimal + addassignment_market_sell_rate *decimal.Decimal + legacy_provision_bucket_id *int + addlegacy_provision_bucket_id *int + clearedFields map[string]struct{} + token *int + clearedtoken bool + sender_profile *uuid.UUID + clearedsender_profile bool + payment_webhook *uuid.UUID + clearedpayment_webhook bool + provider *string + clearedprovider bool + fulfillments map[uuid.UUID]struct{} + removedfulfillments map[uuid.UUID]struct{} + clearedfulfillments bool + transactions map[uuid.UUID]struct{} + removedtransactions map[uuid.UUID]struct{} + clearedtransactions bool + provider_assignment_runs map[uuid.UUID]struct{} + removedprovider_assignment_runs map[uuid.UUID]struct{} + clearedprovider_assignment_runs bool + provider_order_token_score_histories map[uuid.UUID]struct{} + removedprovider_order_token_score_histories map[uuid.UUID]struct{} + clearedprovider_order_token_score_histories bool + done bool + oldValue func(context.Context) (*PaymentOrder, error) + predicates []predicate.PaymentOrder } var _ ent.Mutation = (*PaymentOrderMutation)(nil) @@ -8514,6 +8445,216 @@ func (m *PaymentOrderMutation) ResetFallbackTriedAt() { delete(m.clearedFields, paymentorder.FieldFallbackTriedAt) } +// SetAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field. +func (m *PaymentOrderMutation) SetAssignmentMarketBuyRate(d decimal.Decimal) { + m.assignment_market_buy_rate = &d + m.addassignment_market_buy_rate = nil +} + +// AssignmentMarketBuyRate returns the value of the "assignment_market_buy_rate" field in the mutation. +func (m *PaymentOrderMutation) AssignmentMarketBuyRate() (r decimal.Decimal, exists bool) { + v := m.assignment_market_buy_rate + if v == nil { + return + } + return *v, true +} + +// OldAssignmentMarketBuyRate returns the old "assignment_market_buy_rate" field's value of the PaymentOrder entity. +// If the PaymentOrder object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PaymentOrderMutation) OldAssignmentMarketBuyRate(ctx context.Context) (v *decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAssignmentMarketBuyRate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAssignmentMarketBuyRate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAssignmentMarketBuyRate: %w", err) + } + return oldValue.AssignmentMarketBuyRate, nil +} + +// AddAssignmentMarketBuyRate adds d to the "assignment_market_buy_rate" field. +func (m *PaymentOrderMutation) AddAssignmentMarketBuyRate(d decimal.Decimal) { + if m.addassignment_market_buy_rate != nil { + *m.addassignment_market_buy_rate = m.addassignment_market_buy_rate.Add(d) + } else { + m.addassignment_market_buy_rate = &d + } +} + +// AddedAssignmentMarketBuyRate returns the value that was added to the "assignment_market_buy_rate" field in this mutation. +func (m *PaymentOrderMutation) AddedAssignmentMarketBuyRate() (r decimal.Decimal, exists bool) { + v := m.addassignment_market_buy_rate + if v == nil { + return + } + return *v, true +} + +// ClearAssignmentMarketBuyRate clears the value of the "assignment_market_buy_rate" field. +func (m *PaymentOrderMutation) ClearAssignmentMarketBuyRate() { + m.assignment_market_buy_rate = nil + m.addassignment_market_buy_rate = nil + m.clearedFields[paymentorder.FieldAssignmentMarketBuyRate] = struct{}{} +} + +// AssignmentMarketBuyRateCleared returns if the "assignment_market_buy_rate" field was cleared in this mutation. +func (m *PaymentOrderMutation) AssignmentMarketBuyRateCleared() bool { + _, ok := m.clearedFields[paymentorder.FieldAssignmentMarketBuyRate] + return ok +} + +// ResetAssignmentMarketBuyRate resets all changes to the "assignment_market_buy_rate" field. +func (m *PaymentOrderMutation) ResetAssignmentMarketBuyRate() { + m.assignment_market_buy_rate = nil + m.addassignment_market_buy_rate = nil + delete(m.clearedFields, paymentorder.FieldAssignmentMarketBuyRate) +} + +// SetAssignmentMarketSellRate sets the "assignment_market_sell_rate" field. +func (m *PaymentOrderMutation) SetAssignmentMarketSellRate(d decimal.Decimal) { + m.assignment_market_sell_rate = &d + m.addassignment_market_sell_rate = nil +} + +// AssignmentMarketSellRate returns the value of the "assignment_market_sell_rate" field in the mutation. +func (m *PaymentOrderMutation) AssignmentMarketSellRate() (r decimal.Decimal, exists bool) { + v := m.assignment_market_sell_rate + if v == nil { + return + } + return *v, true +} + +// OldAssignmentMarketSellRate returns the old "assignment_market_sell_rate" field's value of the PaymentOrder entity. +// If the PaymentOrder object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PaymentOrderMutation) OldAssignmentMarketSellRate(ctx context.Context) (v *decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAssignmentMarketSellRate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAssignmentMarketSellRate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAssignmentMarketSellRate: %w", err) + } + return oldValue.AssignmentMarketSellRate, nil +} + +// AddAssignmentMarketSellRate adds d to the "assignment_market_sell_rate" field. +func (m *PaymentOrderMutation) AddAssignmentMarketSellRate(d decimal.Decimal) { + if m.addassignment_market_sell_rate != nil { + *m.addassignment_market_sell_rate = m.addassignment_market_sell_rate.Add(d) + } else { + m.addassignment_market_sell_rate = &d + } +} + +// AddedAssignmentMarketSellRate returns the value that was added to the "assignment_market_sell_rate" field in this mutation. +func (m *PaymentOrderMutation) AddedAssignmentMarketSellRate() (r decimal.Decimal, exists bool) { + v := m.addassignment_market_sell_rate + if v == nil { + return + } + return *v, true +} + +// ClearAssignmentMarketSellRate clears the value of the "assignment_market_sell_rate" field. +func (m *PaymentOrderMutation) ClearAssignmentMarketSellRate() { + m.assignment_market_sell_rate = nil + m.addassignment_market_sell_rate = nil + m.clearedFields[paymentorder.FieldAssignmentMarketSellRate] = struct{}{} +} + +// AssignmentMarketSellRateCleared returns if the "assignment_market_sell_rate" field was cleared in this mutation. +func (m *PaymentOrderMutation) AssignmentMarketSellRateCleared() bool { + _, ok := m.clearedFields[paymentorder.FieldAssignmentMarketSellRate] + return ok +} + +// ResetAssignmentMarketSellRate resets all changes to the "assignment_market_sell_rate" field. +func (m *PaymentOrderMutation) ResetAssignmentMarketSellRate() { + m.assignment_market_sell_rate = nil + m.addassignment_market_sell_rate = nil + delete(m.clearedFields, paymentorder.FieldAssignmentMarketSellRate) +} + +// SetLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field. +func (m *PaymentOrderMutation) SetLegacyProvisionBucketID(i int) { + m.legacy_provision_bucket_id = &i + m.addlegacy_provision_bucket_id = nil +} + +// LegacyProvisionBucketID returns the value of the "legacy_provision_bucket_id" field in the mutation. +func (m *PaymentOrderMutation) LegacyProvisionBucketID() (r int, exists bool) { + v := m.legacy_provision_bucket_id + if v == nil { + return + } + return *v, true +} + +// OldLegacyProvisionBucketID returns the old "legacy_provision_bucket_id" field's value of the PaymentOrder entity. +// If the PaymentOrder object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *PaymentOrderMutation) OldLegacyProvisionBucketID(ctx context.Context) (v *int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLegacyProvisionBucketID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLegacyProvisionBucketID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLegacyProvisionBucketID: %w", err) + } + return oldValue.LegacyProvisionBucketID, nil +} + +// AddLegacyProvisionBucketID adds i to the "legacy_provision_bucket_id" field. +func (m *PaymentOrderMutation) AddLegacyProvisionBucketID(i int) { + if m.addlegacy_provision_bucket_id != nil { + *m.addlegacy_provision_bucket_id += i + } else { + m.addlegacy_provision_bucket_id = &i + } +} + +// AddedLegacyProvisionBucketID returns the value that was added to the "legacy_provision_bucket_id" field in this mutation. +func (m *PaymentOrderMutation) AddedLegacyProvisionBucketID() (r int, exists bool) { + v := m.addlegacy_provision_bucket_id + if v == nil { + return + } + return *v, true +} + +// ClearLegacyProvisionBucketID clears the value of the "legacy_provision_bucket_id" field. +func (m *PaymentOrderMutation) ClearLegacyProvisionBucketID() { + m.legacy_provision_bucket_id = nil + m.addlegacy_provision_bucket_id = nil + m.clearedFields[paymentorder.FieldLegacyProvisionBucketID] = struct{}{} +} + +// LegacyProvisionBucketIDCleared returns if the "legacy_provision_bucket_id" field was cleared in this mutation. +func (m *PaymentOrderMutation) LegacyProvisionBucketIDCleared() bool { + _, ok := m.clearedFields[paymentorder.FieldLegacyProvisionBucketID] + return ok +} + +// ResetLegacyProvisionBucketID resets all changes to the "legacy_provision_bucket_id" field. +func (m *PaymentOrderMutation) ResetLegacyProvisionBucketID() { + m.legacy_provision_bucket_id = nil + m.addlegacy_provision_bucket_id = nil + delete(m.clearedFields, paymentorder.FieldLegacyProvisionBucketID) +} + // SetTokenID sets the "token" edge to the Token entity by id. func (m *PaymentOrderMutation) SetTokenID(id int) { m.token = &id @@ -8670,45 +8811,6 @@ func (m *PaymentOrderMutation) ResetProvider() { m.clearedprovider = false } -// SetProvisionBucketID sets the "provision_bucket" edge to the ProvisionBucket entity by id. -func (m *PaymentOrderMutation) SetProvisionBucketID(id int) { - m.provision_bucket = &id -} - -// ClearProvisionBucket clears the "provision_bucket" edge to the ProvisionBucket entity. -func (m *PaymentOrderMutation) ClearProvisionBucket() { - m.clearedprovision_bucket = true -} - -// ProvisionBucketCleared reports if the "provision_bucket" edge to the ProvisionBucket entity was cleared. -func (m *PaymentOrderMutation) ProvisionBucketCleared() bool { - return m.clearedprovision_bucket -} - -// ProvisionBucketID returns the "provision_bucket" edge ID in the mutation. -func (m *PaymentOrderMutation) ProvisionBucketID() (id int, exists bool) { - if m.provision_bucket != nil { - return *m.provision_bucket, true - } - return -} - -// ProvisionBucketIDs returns the "provision_bucket" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// ProvisionBucketID instead. It exists only for internal usage by the builders. -func (m *PaymentOrderMutation) ProvisionBucketIDs() (ids []int) { - if id := m.provision_bucket; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetProvisionBucket resets all changes to the "provision_bucket" edge. -func (m *PaymentOrderMutation) ResetProvisionBucket() { - m.provision_bucket = nil - m.clearedprovision_bucket = false -} - // AddFulfillmentIDs adds the "fulfillments" edge to the PaymentOrderFulfillment entity by ids. func (m *PaymentOrderMutation) AddFulfillmentIDs(ids ...uuid.UUID) { if m.fulfillments == nil { @@ -8817,6 +8919,114 @@ func (m *PaymentOrderMutation) ResetTransactions() { m.removedtransactions = nil } +// AddProviderAssignmentRunIDs adds the "provider_assignment_runs" edge to the ProviderAssignmentRun entity by ids. +func (m *PaymentOrderMutation) AddProviderAssignmentRunIDs(ids ...uuid.UUID) { + if m.provider_assignment_runs == nil { + m.provider_assignment_runs = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.provider_assignment_runs[ids[i]] = struct{}{} + } +} + +// ClearProviderAssignmentRuns clears the "provider_assignment_runs" edge to the ProviderAssignmentRun entity. +func (m *PaymentOrderMutation) ClearProviderAssignmentRuns() { + m.clearedprovider_assignment_runs = true +} + +// ProviderAssignmentRunsCleared reports if the "provider_assignment_runs" edge to the ProviderAssignmentRun entity was cleared. +func (m *PaymentOrderMutation) ProviderAssignmentRunsCleared() bool { + return m.clearedprovider_assignment_runs +} + +// RemoveProviderAssignmentRunIDs removes the "provider_assignment_runs" edge to the ProviderAssignmentRun entity by IDs. +func (m *PaymentOrderMutation) RemoveProviderAssignmentRunIDs(ids ...uuid.UUID) { + if m.removedprovider_assignment_runs == nil { + m.removedprovider_assignment_runs = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.provider_assignment_runs, ids[i]) + m.removedprovider_assignment_runs[ids[i]] = struct{}{} + } +} + +// RemovedProviderAssignmentRuns returns the removed IDs of the "provider_assignment_runs" edge to the ProviderAssignmentRun entity. +func (m *PaymentOrderMutation) RemovedProviderAssignmentRunsIDs() (ids []uuid.UUID) { + for id := range m.removedprovider_assignment_runs { + ids = append(ids, id) + } + return +} + +// ProviderAssignmentRunsIDs returns the "provider_assignment_runs" edge IDs in the mutation. +func (m *PaymentOrderMutation) ProviderAssignmentRunsIDs() (ids []uuid.UUID) { + for id := range m.provider_assignment_runs { + ids = append(ids, id) + } + return +} + +// ResetProviderAssignmentRuns resets all changes to the "provider_assignment_runs" edge. +func (m *PaymentOrderMutation) ResetProviderAssignmentRuns() { + m.provider_assignment_runs = nil + m.clearedprovider_assignment_runs = false + m.removedprovider_assignment_runs = nil +} + +// AddProviderOrderTokenScoreHistoryIDs adds the "provider_order_token_score_histories" edge to the ProviderOrderTokenScoreHistory entity by ids. +func (m *PaymentOrderMutation) AddProviderOrderTokenScoreHistoryIDs(ids ...uuid.UUID) { + if m.provider_order_token_score_histories == nil { + m.provider_order_token_score_histories = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.provider_order_token_score_histories[ids[i]] = struct{}{} + } +} + +// ClearProviderOrderTokenScoreHistories clears the "provider_order_token_score_histories" edge to the ProviderOrderTokenScoreHistory entity. +func (m *PaymentOrderMutation) ClearProviderOrderTokenScoreHistories() { + m.clearedprovider_order_token_score_histories = true +} + +// ProviderOrderTokenScoreHistoriesCleared reports if the "provider_order_token_score_histories" edge to the ProviderOrderTokenScoreHistory entity was cleared. +func (m *PaymentOrderMutation) ProviderOrderTokenScoreHistoriesCleared() bool { + return m.clearedprovider_order_token_score_histories +} + +// RemoveProviderOrderTokenScoreHistoryIDs removes the "provider_order_token_score_histories" edge to the ProviderOrderTokenScoreHistory entity by IDs. +func (m *PaymentOrderMutation) RemoveProviderOrderTokenScoreHistoryIDs(ids ...uuid.UUID) { + if m.removedprovider_order_token_score_histories == nil { + m.removedprovider_order_token_score_histories = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.provider_order_token_score_histories, ids[i]) + m.removedprovider_order_token_score_histories[ids[i]] = struct{}{} + } +} + +// RemovedProviderOrderTokenScoreHistories returns the removed IDs of the "provider_order_token_score_histories" edge to the ProviderOrderTokenScoreHistory entity. +func (m *PaymentOrderMutation) RemovedProviderOrderTokenScoreHistoriesIDs() (ids []uuid.UUID) { + for id := range m.removedprovider_order_token_score_histories { + ids = append(ids, id) + } + return +} + +// ProviderOrderTokenScoreHistoriesIDs returns the "provider_order_token_score_histories" edge IDs in the mutation. +func (m *PaymentOrderMutation) ProviderOrderTokenScoreHistoriesIDs() (ids []uuid.UUID) { + for id := range m.provider_order_token_score_histories { + ids = append(ids, id) + } + return +} + +// ResetProviderOrderTokenScoreHistories resets all changes to the "provider_order_token_score_histories" edge. +func (m *PaymentOrderMutation) ResetProviderOrderTokenScoreHistories() { + m.provider_order_token_score_histories = nil + m.clearedprovider_order_token_score_histories = false + m.removedprovider_order_token_score_histories = nil +} + // Where appends a list predicates to the PaymentOrderMutation builder. func (m *PaymentOrderMutation) Where(ps ...predicate.PaymentOrder) { m.predicates = append(m.predicates, ps...) @@ -8851,7 +9061,7 @@ func (m *PaymentOrderMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *PaymentOrderMutation) Fields() []string { - fields := make([]string, 0, 37) + fields := make([]string, 0, 40) if m.created_at != nil { fields = append(fields, paymentorder.FieldCreatedAt) } @@ -8963,6 +9173,15 @@ func (m *PaymentOrderMutation) Fields() []string { if m.fallback_tried_at != nil { fields = append(fields, paymentorder.FieldFallbackTriedAt) } + if m.assignment_market_buy_rate != nil { + fields = append(fields, paymentorder.FieldAssignmentMarketBuyRate) + } + if m.assignment_market_sell_rate != nil { + fields = append(fields, paymentorder.FieldAssignmentMarketSellRate) + } + if m.legacy_provision_bucket_id != nil { + fields = append(fields, paymentorder.FieldLegacyProvisionBucketID) + } return fields } @@ -9045,6 +9264,12 @@ func (m *PaymentOrderMutation) Field(name string) (ent.Value, bool) { return m.OrderType() case paymentorder.FieldFallbackTriedAt: return m.FallbackTriedAt() + case paymentorder.FieldAssignmentMarketBuyRate: + return m.AssignmentMarketBuyRate() + case paymentorder.FieldAssignmentMarketSellRate: + return m.AssignmentMarketSellRate() + case paymentorder.FieldLegacyProvisionBucketID: + return m.LegacyProvisionBucketID() } return nil, false } @@ -9128,6 +9353,12 @@ func (m *PaymentOrderMutation) OldField(ctx context.Context, name string) (ent.V return m.OldOrderType(ctx) case paymentorder.FieldFallbackTriedAt: return m.OldFallbackTriedAt(ctx) + case paymentorder.FieldAssignmentMarketBuyRate: + return m.OldAssignmentMarketBuyRate(ctx) + case paymentorder.FieldAssignmentMarketSellRate: + return m.OldAssignmentMarketSellRate(ctx) + case paymentorder.FieldLegacyProvisionBucketID: + return m.OldLegacyProvisionBucketID(ctx) } return nil, fmt.Errorf("unknown PaymentOrder field %s", name) } @@ -9396,6 +9627,27 @@ func (m *PaymentOrderMutation) SetField(name string, value ent.Value) error { } m.SetFallbackTriedAt(v) return nil + case paymentorder.FieldAssignmentMarketBuyRate: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAssignmentMarketBuyRate(v) + return nil + case paymentorder.FieldAssignmentMarketSellRate: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAssignmentMarketSellRate(v) + return nil + case paymentorder.FieldLegacyProvisionBucketID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLegacyProvisionBucketID(v) + return nil } return fmt.Errorf("unknown PaymentOrder field %s", name) } @@ -9443,6 +9695,15 @@ func (m *PaymentOrderMutation) AddedFields() []string { if m.addcancellation_count != nil { fields = append(fields, paymentorder.FieldCancellationCount) } + if m.addassignment_market_buy_rate != nil { + fields = append(fields, paymentorder.FieldAssignmentMarketBuyRate) + } + if m.addassignment_market_sell_rate != nil { + fields = append(fields, paymentorder.FieldAssignmentMarketSellRate) + } + if m.addlegacy_provision_bucket_id != nil { + fields = append(fields, paymentorder.FieldLegacyProvisionBucketID) + } return fields } @@ -9477,6 +9738,12 @@ func (m *PaymentOrderMutation) AddedField(name string) (ent.Value, bool) { return m.AddedBlockNumber() case paymentorder.FieldCancellationCount: return m.AddedCancellationCount() + case paymentorder.FieldAssignmentMarketBuyRate: + return m.AddedAssignmentMarketBuyRate() + case paymentorder.FieldAssignmentMarketSellRate: + return m.AddedAssignmentMarketSellRate() + case paymentorder.FieldLegacyProvisionBucketID: + return m.AddedLegacyProvisionBucketID() } return nil, false } @@ -9577,12 +9844,33 @@ func (m *PaymentOrderMutation) AddField(name string, value ent.Value) error { } m.AddCancellationCount(v) return nil - } - return fmt.Errorf("unknown PaymentOrder numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. + case paymentorder.FieldAssignmentMarketBuyRate: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddAssignmentMarketBuyRate(v) + return nil + case paymentorder.FieldAssignmentMarketSellRate: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddAssignmentMarketSellRate(v) + return nil + case paymentorder.FieldLegacyProvisionBucketID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddLegacyProvisionBucketID(v) + return nil + } + return fmt.Errorf("unknown PaymentOrder numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. func (m *PaymentOrderMutation) ClearedFields() []string { var fields []string if m.FieldCleared(paymentorder.FieldTxHash) { @@ -9636,6 +9924,15 @@ func (m *PaymentOrderMutation) ClearedFields() []string { if m.FieldCleared(paymentorder.FieldFallbackTriedAt) { fields = append(fields, paymentorder.FieldFallbackTriedAt) } + if m.FieldCleared(paymentorder.FieldAssignmentMarketBuyRate) { + fields = append(fields, paymentorder.FieldAssignmentMarketBuyRate) + } + if m.FieldCleared(paymentorder.FieldAssignmentMarketSellRate) { + fields = append(fields, paymentorder.FieldAssignmentMarketSellRate) + } + if m.FieldCleared(paymentorder.FieldLegacyProvisionBucketID) { + fields = append(fields, paymentorder.FieldLegacyProvisionBucketID) + } return fields } @@ -9701,6 +9998,15 @@ func (m *PaymentOrderMutation) ClearField(name string) error { case paymentorder.FieldFallbackTriedAt: m.ClearFallbackTriedAt() return nil + case paymentorder.FieldAssignmentMarketBuyRate: + m.ClearAssignmentMarketBuyRate() + return nil + case paymentorder.FieldAssignmentMarketSellRate: + m.ClearAssignmentMarketSellRate() + return nil + case paymentorder.FieldLegacyProvisionBucketID: + m.ClearLegacyProvisionBucketID() + return nil } return fmt.Errorf("unknown PaymentOrder nullable field %s", name) } @@ -9820,13 +10126,22 @@ func (m *PaymentOrderMutation) ResetField(name string) error { case paymentorder.FieldFallbackTriedAt: m.ResetFallbackTriedAt() return nil + case paymentorder.FieldAssignmentMarketBuyRate: + m.ResetAssignmentMarketBuyRate() + return nil + case paymentorder.FieldAssignmentMarketSellRate: + m.ResetAssignmentMarketSellRate() + return nil + case paymentorder.FieldLegacyProvisionBucketID: + m.ResetLegacyProvisionBucketID() + return nil } return fmt.Errorf("unknown PaymentOrder field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. func (m *PaymentOrderMutation) AddedEdges() []string { - edges := make([]string, 0, 7) + edges := make([]string, 0, 8) if m.token != nil { edges = append(edges, paymentorder.EdgeToken) } @@ -9839,15 +10154,18 @@ func (m *PaymentOrderMutation) AddedEdges() []string { if m.provider != nil { edges = append(edges, paymentorder.EdgeProvider) } - if m.provision_bucket != nil { - edges = append(edges, paymentorder.EdgeProvisionBucket) - } if m.fulfillments != nil { edges = append(edges, paymentorder.EdgeFulfillments) } if m.transactions != nil { edges = append(edges, paymentorder.EdgeTransactions) } + if m.provider_assignment_runs != nil { + edges = append(edges, paymentorder.EdgeProviderAssignmentRuns) + } + if m.provider_order_token_score_histories != nil { + edges = append(edges, paymentorder.EdgeProviderOrderTokenScoreHistories) + } return edges } @@ -9871,10 +10189,6 @@ func (m *PaymentOrderMutation) AddedIDs(name string) []ent.Value { if id := m.provider; id != nil { return []ent.Value{*id} } - case paymentorder.EdgeProvisionBucket: - if id := m.provision_bucket; id != nil { - return []ent.Value{*id} - } case paymentorder.EdgeFulfillments: ids := make([]ent.Value, 0, len(m.fulfillments)) for id := range m.fulfillments { @@ -9887,19 +10201,37 @@ func (m *PaymentOrderMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case paymentorder.EdgeProviderAssignmentRuns: + ids := make([]ent.Value, 0, len(m.provider_assignment_runs)) + for id := range m.provider_assignment_runs { + ids = append(ids, id) + } + return ids + case paymentorder.EdgeProviderOrderTokenScoreHistories: + ids := make([]ent.Value, 0, len(m.provider_order_token_score_histories)) + for id := range m.provider_order_token_score_histories { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *PaymentOrderMutation) RemovedEdges() []string { - edges := make([]string, 0, 7) + edges := make([]string, 0, 8) if m.removedfulfillments != nil { edges = append(edges, paymentorder.EdgeFulfillments) } if m.removedtransactions != nil { edges = append(edges, paymentorder.EdgeTransactions) } + if m.removedprovider_assignment_runs != nil { + edges = append(edges, paymentorder.EdgeProviderAssignmentRuns) + } + if m.removedprovider_order_token_score_histories != nil { + edges = append(edges, paymentorder.EdgeProviderOrderTokenScoreHistories) + } return edges } @@ -9919,13 +10251,25 @@ func (m *PaymentOrderMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case paymentorder.EdgeProviderAssignmentRuns: + ids := make([]ent.Value, 0, len(m.removedprovider_assignment_runs)) + for id := range m.removedprovider_assignment_runs { + ids = append(ids, id) + } + return ids + case paymentorder.EdgeProviderOrderTokenScoreHistories: + ids := make([]ent.Value, 0, len(m.removedprovider_order_token_score_histories)) + for id := range m.removedprovider_order_token_score_histories { + ids = append(ids, id) + } + return ids } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *PaymentOrderMutation) ClearedEdges() []string { - edges := make([]string, 0, 7) + edges := make([]string, 0, 8) if m.clearedtoken { edges = append(edges, paymentorder.EdgeToken) } @@ -9938,15 +10282,18 @@ func (m *PaymentOrderMutation) ClearedEdges() []string { if m.clearedprovider { edges = append(edges, paymentorder.EdgeProvider) } - if m.clearedprovision_bucket { - edges = append(edges, paymentorder.EdgeProvisionBucket) - } if m.clearedfulfillments { edges = append(edges, paymentorder.EdgeFulfillments) } if m.clearedtransactions { edges = append(edges, paymentorder.EdgeTransactions) } + if m.clearedprovider_assignment_runs { + edges = append(edges, paymentorder.EdgeProviderAssignmentRuns) + } + if m.clearedprovider_order_token_score_histories { + edges = append(edges, paymentorder.EdgeProviderOrderTokenScoreHistories) + } return edges } @@ -9962,12 +10309,14 @@ func (m *PaymentOrderMutation) EdgeCleared(name string) bool { return m.clearedpayment_webhook case paymentorder.EdgeProvider: return m.clearedprovider - case paymentorder.EdgeProvisionBucket: - return m.clearedprovision_bucket case paymentorder.EdgeFulfillments: return m.clearedfulfillments case paymentorder.EdgeTransactions: return m.clearedtransactions + case paymentorder.EdgeProviderAssignmentRuns: + return m.clearedprovider_assignment_runs + case paymentorder.EdgeProviderOrderTokenScoreHistories: + return m.clearedprovider_order_token_score_histories } return false } @@ -9988,9 +10337,6 @@ func (m *PaymentOrderMutation) ClearEdge(name string) error { case paymentorder.EdgeProvider: m.ClearProvider() return nil - case paymentorder.EdgeProvisionBucket: - m.ClearProvisionBucket() - return nil } return fmt.Errorf("unknown PaymentOrder unique edge %s", name) } @@ -10011,15 +10357,18 @@ func (m *PaymentOrderMutation) ResetEdge(name string) error { case paymentorder.EdgeProvider: m.ResetProvider() return nil - case paymentorder.EdgeProvisionBucket: - m.ResetProvisionBucket() - return nil case paymentorder.EdgeFulfillments: m.ResetFulfillments() return nil case paymentorder.EdgeTransactions: m.ResetTransactions() return nil + case paymentorder.EdgeProviderAssignmentRuns: + m.ResetProviderAssignmentRuns() + return nil + case paymentorder.EdgeProviderOrderTokenScoreHistories: + m.ResetProviderOrderTokenScoreHistories() + return nil } return fmt.Errorf("unknown PaymentOrder edge %s", name) } @@ -11427,45 +11776,43 @@ func (m *PaymentWebhookMutation) ResetEdge(name string) error { return fmt.Errorf("unknown PaymentWebhook edge %s", name) } -// ProviderBalancesMutation represents an operation that mutates the ProviderBalances nodes in the graph. -type ProviderBalancesMutation struct { +// ProviderAssignmentRunMutation represents an operation that mutates the ProviderAssignmentRun nodes in the graph. +type ProviderAssignmentRunMutation struct { config - op Op - typ string - id *uuid.UUID - available_balance *decimal.Decimal - addavailable_balance *decimal.Decimal - total_balance *decimal.Decimal - addtotal_balance *decimal.Decimal - reserved_balance *decimal.Decimal - addreserved_balance *decimal.Decimal - is_available *bool - updated_at *time.Time - peak_balance *decimal.Decimal - addpeak_balance *decimal.Decimal - clearedFields map[string]struct{} - provider *string - clearedprovider bool - fiat_currency *uuid.UUID - clearedfiat_currency bool - token *int - clearedtoken bool - done bool - oldValue func(context.Context) (*ProviderBalances, error) - predicates []predicate.ProviderBalances + op Op + typ string + id *uuid.UUID + assigned_provider_id *string + attempted_at *time.Time + trigger *string + result *string + used_fallback *bool + market_buy_rate_snapshot *decimal.Decimal + addmarket_buy_rate_snapshot *decimal.Decimal + market_sell_rate_snapshot *decimal.Decimal + addmarket_sell_rate_snapshot *decimal.Decimal + error_message *string + clearedFields map[string]struct{} + payment_order *uuid.UUID + clearedpayment_order bool + provider_order_token *int + clearedprovider_order_token bool + done bool + oldValue func(context.Context) (*ProviderAssignmentRun, error) + predicates []predicate.ProviderAssignmentRun } -var _ ent.Mutation = (*ProviderBalancesMutation)(nil) +var _ ent.Mutation = (*ProviderAssignmentRunMutation)(nil) -// providerbalancesOption allows management of the mutation configuration using functional options. -type providerbalancesOption func(*ProviderBalancesMutation) +// providerassignmentrunOption allows management of the mutation configuration using functional options. +type providerassignmentrunOption func(*ProviderAssignmentRunMutation) -// newProviderBalancesMutation creates new mutation for the ProviderBalances entity. -func newProviderBalancesMutation(c config, op Op, opts ...providerbalancesOption) *ProviderBalancesMutation { - m := &ProviderBalancesMutation{ +// newProviderAssignmentRunMutation creates new mutation for the ProviderAssignmentRun entity. +func newProviderAssignmentRunMutation(c config, op Op, opts ...providerassignmentrunOption) *ProviderAssignmentRunMutation { + m := &ProviderAssignmentRunMutation{ config: c, op: op, - typ: TypeProviderBalances, + typ: TypeProviderAssignmentRun, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -11474,20 +11821,20 @@ func newProviderBalancesMutation(c config, op Op, opts ...providerbalancesOption return m } -// withProviderBalancesID sets the ID field of the mutation. -func withProviderBalancesID(id uuid.UUID) providerbalancesOption { - return func(m *ProviderBalancesMutation) { +// withProviderAssignmentRunID sets the ID field of the mutation. +func withProviderAssignmentRunID(id uuid.UUID) providerassignmentrunOption { + return func(m *ProviderAssignmentRunMutation) { var ( err error once sync.Once - value *ProviderBalances + value *ProviderAssignmentRun ) - m.oldValue = func(ctx context.Context) (*ProviderBalances, error) { + m.oldValue = func(ctx context.Context) (*ProviderAssignmentRun, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().ProviderBalances.Get(ctx, id) + value, err = m.Client().ProviderAssignmentRun.Get(ctx, id) } }) return value, err @@ -11496,10 +11843,10 @@ func withProviderBalancesID(id uuid.UUID) providerbalancesOption { } } -// withProviderBalances sets the old ProviderBalances of the mutation. -func withProviderBalances(node *ProviderBalances) providerbalancesOption { - return func(m *ProviderBalancesMutation) { - m.oldValue = func(context.Context) (*ProviderBalances, error) { +// withProviderAssignmentRun sets the old ProviderAssignmentRun of the mutation. +func withProviderAssignmentRun(node *ProviderAssignmentRun) providerassignmentrunOption { + return func(m *ProviderAssignmentRunMutation) { + m.oldValue = func(context.Context) (*ProviderAssignmentRun, error) { return node, nil } m.id = &node.ID @@ -11508,7 +11855,7 @@ func withProviderBalances(node *ProviderBalances) providerbalancesOption { // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m ProviderBalancesMutation) Client() *Client { +func (m ProviderAssignmentRunMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -11516,7 +11863,7 @@ func (m ProviderBalancesMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m ProviderBalancesMutation) Tx() (*Tx, error) { +func (m ProviderAssignmentRunMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("ent: mutation is not running in a transaction") } @@ -11526,14 +11873,14 @@ func (m ProviderBalancesMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of ProviderBalances entities. -func (m *ProviderBalancesMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of ProviderAssignmentRun entities. +func (m *ProviderAssignmentRunMutation) SetID(id uuid.UUID) { m.id = &id } // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *ProviderBalancesMutation) ID() (id uuid.UUID, exists bool) { +func (m *ProviderAssignmentRunMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -11544,7 +11891,7 @@ func (m *ProviderBalancesMutation) ID() (id uuid.UUID, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *ProviderBalancesMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *ProviderAssignmentRunMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -11553,434 +11900,481 @@ func (m *ProviderBalancesMutation) IDs(ctx context.Context) ([]uuid.UUID, error) } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().ProviderBalances.Query().Where(m.predicates...).IDs(ctx) + return m.Client().ProviderAssignmentRun.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetAvailableBalance sets the "available_balance" field. -func (m *ProviderBalancesMutation) SetAvailableBalance(d decimal.Decimal) { - m.available_balance = &d - m.addavailable_balance = nil +// SetAssignedProviderID sets the "assigned_provider_id" field. +func (m *ProviderAssignmentRunMutation) SetAssignedProviderID(s string) { + m.assigned_provider_id = &s } -// AvailableBalance returns the value of the "available_balance" field in the mutation. -func (m *ProviderBalancesMutation) AvailableBalance() (r decimal.Decimal, exists bool) { - v := m.available_balance +// AssignedProviderID returns the value of the "assigned_provider_id" field in the mutation. +func (m *ProviderAssignmentRunMutation) AssignedProviderID() (r string, exists bool) { + v := m.assigned_provider_id if v == nil { return } return *v, true } -// OldAvailableBalance returns the old "available_balance" field's value of the ProviderBalances entity. -// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. +// OldAssignedProviderID returns the old "assigned_provider_id" field's value of the ProviderAssignmentRun entity. +// If the ProviderAssignmentRun object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderBalancesMutation) OldAvailableBalance(ctx context.Context) (v decimal.Decimal, err error) { +func (m *ProviderAssignmentRunMutation) OldAssignedProviderID(ctx context.Context) (v *string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAvailableBalance is only allowed on UpdateOne operations") + return v, errors.New("OldAssignedProviderID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAvailableBalance requires an ID field in the mutation") + return v, errors.New("OldAssignedProviderID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldAvailableBalance: %w", err) + return v, fmt.Errorf("querying old value for OldAssignedProviderID: %w", err) } - return oldValue.AvailableBalance, nil + return oldValue.AssignedProviderID, nil } -// AddAvailableBalance adds d to the "available_balance" field. -func (m *ProviderBalancesMutation) AddAvailableBalance(d decimal.Decimal) { - if m.addavailable_balance != nil { - *m.addavailable_balance = m.addavailable_balance.Add(d) - } else { - m.addavailable_balance = &d - } +// ClearAssignedProviderID clears the value of the "assigned_provider_id" field. +func (m *ProviderAssignmentRunMutation) ClearAssignedProviderID() { + m.assigned_provider_id = nil + m.clearedFields[providerassignmentrun.FieldAssignedProviderID] = struct{}{} } -// AddedAvailableBalance returns the value that was added to the "available_balance" field in this mutation. -func (m *ProviderBalancesMutation) AddedAvailableBalance() (r decimal.Decimal, exists bool) { - v := m.addavailable_balance - if v == nil { - return - } - return *v, true +// AssignedProviderIDCleared returns if the "assigned_provider_id" field was cleared in this mutation. +func (m *ProviderAssignmentRunMutation) AssignedProviderIDCleared() bool { + _, ok := m.clearedFields[providerassignmentrun.FieldAssignedProviderID] + return ok } -// ResetAvailableBalance resets all changes to the "available_balance" field. -func (m *ProviderBalancesMutation) ResetAvailableBalance() { - m.available_balance = nil - m.addavailable_balance = nil +// ResetAssignedProviderID resets all changes to the "assigned_provider_id" field. +func (m *ProviderAssignmentRunMutation) ResetAssignedProviderID() { + m.assigned_provider_id = nil + delete(m.clearedFields, providerassignmentrun.FieldAssignedProviderID) } -// SetTotalBalance sets the "total_balance" field. -func (m *ProviderBalancesMutation) SetTotalBalance(d decimal.Decimal) { - m.total_balance = &d - m.addtotal_balance = nil +// SetAttemptedAt sets the "attempted_at" field. +func (m *ProviderAssignmentRunMutation) SetAttemptedAt(t time.Time) { + m.attempted_at = &t } -// TotalBalance returns the value of the "total_balance" field in the mutation. -func (m *ProviderBalancesMutation) TotalBalance() (r decimal.Decimal, exists bool) { - v := m.total_balance +// AttemptedAt returns the value of the "attempted_at" field in the mutation. +func (m *ProviderAssignmentRunMutation) AttemptedAt() (r time.Time, exists bool) { + v := m.attempted_at if v == nil { return } return *v, true } -// OldTotalBalance returns the old "total_balance" field's value of the ProviderBalances entity. -// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. +// OldAttemptedAt returns the old "attempted_at" field's value of the ProviderAssignmentRun entity. +// If the ProviderAssignmentRun object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderBalancesMutation) OldTotalBalance(ctx context.Context) (v decimal.Decimal, err error) { +func (m *ProviderAssignmentRunMutation) OldAttemptedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTotalBalance is only allowed on UpdateOne operations") + return v, errors.New("OldAttemptedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTotalBalance requires an ID field in the mutation") + return v, errors.New("OldAttemptedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldTotalBalance: %w", err) - } - return oldValue.TotalBalance, nil -} - -// AddTotalBalance adds d to the "total_balance" field. -func (m *ProviderBalancesMutation) AddTotalBalance(d decimal.Decimal) { - if m.addtotal_balance != nil { - *m.addtotal_balance = m.addtotal_balance.Add(d) - } else { - m.addtotal_balance = &d - } -} - -// AddedTotalBalance returns the value that was added to the "total_balance" field in this mutation. -func (m *ProviderBalancesMutation) AddedTotalBalance() (r decimal.Decimal, exists bool) { - v := m.addtotal_balance - if v == nil { - return + return v, fmt.Errorf("querying old value for OldAttemptedAt: %w", err) } - return *v, true + return oldValue.AttemptedAt, nil } -// ResetTotalBalance resets all changes to the "total_balance" field. -func (m *ProviderBalancesMutation) ResetTotalBalance() { - m.total_balance = nil - m.addtotal_balance = nil +// ResetAttemptedAt resets all changes to the "attempted_at" field. +func (m *ProviderAssignmentRunMutation) ResetAttemptedAt() { + m.attempted_at = nil } -// SetReservedBalance sets the "reserved_balance" field. -func (m *ProviderBalancesMutation) SetReservedBalance(d decimal.Decimal) { - m.reserved_balance = &d - m.addreserved_balance = nil +// SetTrigger sets the "trigger" field. +func (m *ProviderAssignmentRunMutation) SetTrigger(s string) { + m.trigger = &s } -// ReservedBalance returns the value of the "reserved_balance" field in the mutation. -func (m *ProviderBalancesMutation) ReservedBalance() (r decimal.Decimal, exists bool) { - v := m.reserved_balance +// Trigger returns the value of the "trigger" field in the mutation. +func (m *ProviderAssignmentRunMutation) Trigger() (r string, exists bool) { + v := m.trigger if v == nil { return } return *v, true } -// OldReservedBalance returns the old "reserved_balance" field's value of the ProviderBalances entity. -// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. +// OldTrigger returns the old "trigger" field's value of the ProviderAssignmentRun entity. +// If the ProviderAssignmentRun object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderBalancesMutation) OldReservedBalance(ctx context.Context) (v decimal.Decimal, err error) { +func (m *ProviderAssignmentRunMutation) OldTrigger(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldReservedBalance is only allowed on UpdateOne operations") + return v, errors.New("OldTrigger is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldReservedBalance requires an ID field in the mutation") + return v, errors.New("OldTrigger requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldReservedBalance: %w", err) + return v, fmt.Errorf("querying old value for OldTrigger: %w", err) } - return oldValue.ReservedBalance, nil + return oldValue.Trigger, nil } -// AddReservedBalance adds d to the "reserved_balance" field. -func (m *ProviderBalancesMutation) AddReservedBalance(d decimal.Decimal) { - if m.addreserved_balance != nil { - *m.addreserved_balance = m.addreserved_balance.Add(d) - } else { - m.addreserved_balance = &d - } +// ResetTrigger resets all changes to the "trigger" field. +func (m *ProviderAssignmentRunMutation) ResetTrigger() { + m.trigger = nil } -// AddedReservedBalance returns the value that was added to the "reserved_balance" field in this mutation. -func (m *ProviderBalancesMutation) AddedReservedBalance() (r decimal.Decimal, exists bool) { - v := m.addreserved_balance +// SetResult sets the "result" field. +func (m *ProviderAssignmentRunMutation) SetResult(s string) { + m.result = &s +} + +// Result returns the value of the "result" field in the mutation. +func (m *ProviderAssignmentRunMutation) Result() (r string, exists bool) { + v := m.result if v == nil { return } return *v, true } -// ResetReservedBalance resets all changes to the "reserved_balance" field. -func (m *ProviderBalancesMutation) ResetReservedBalance() { - m.reserved_balance = nil - m.addreserved_balance = nil +// OldResult returns the old "result" field's value of the ProviderAssignmentRun entity. +// If the ProviderAssignmentRun object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderAssignmentRunMutation) OldResult(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldResult is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldResult requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldResult: %w", err) + } + return oldValue.Result, nil } -// SetIsAvailable sets the "is_available" field. -func (m *ProviderBalancesMutation) SetIsAvailable(b bool) { - m.is_available = &b +// ResetResult resets all changes to the "result" field. +func (m *ProviderAssignmentRunMutation) ResetResult() { + m.result = nil } -// IsAvailable returns the value of the "is_available" field in the mutation. -func (m *ProviderBalancesMutation) IsAvailable() (r bool, exists bool) { - v := m.is_available +// SetUsedFallback sets the "used_fallback" field. +func (m *ProviderAssignmentRunMutation) SetUsedFallback(b bool) { + m.used_fallback = &b +} + +// UsedFallback returns the value of the "used_fallback" field in the mutation. +func (m *ProviderAssignmentRunMutation) UsedFallback() (r bool, exists bool) { + v := m.used_fallback if v == nil { return } return *v, true } -// OldIsAvailable returns the old "is_available" field's value of the ProviderBalances entity. -// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. +// OldUsedFallback returns the old "used_fallback" field's value of the ProviderAssignmentRun entity. +// If the ProviderAssignmentRun object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderBalancesMutation) OldIsAvailable(ctx context.Context) (v bool, err error) { +func (m *ProviderAssignmentRunMutation) OldUsedFallback(ctx context.Context) (v bool, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldIsAvailable is only allowed on UpdateOne operations") + return v, errors.New("OldUsedFallback is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldIsAvailable requires an ID field in the mutation") + return v, errors.New("OldUsedFallback requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldIsAvailable: %w", err) + return v, fmt.Errorf("querying old value for OldUsedFallback: %w", err) } - return oldValue.IsAvailable, nil + return oldValue.UsedFallback, nil } -// ResetIsAvailable resets all changes to the "is_available" field. -func (m *ProviderBalancesMutation) ResetIsAvailable() { - m.is_available = nil +// ResetUsedFallback resets all changes to the "used_fallback" field. +func (m *ProviderAssignmentRunMutation) ResetUsedFallback() { + m.used_fallback = nil } -// SetUpdatedAt sets the "updated_at" field. -func (m *ProviderBalancesMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// SetMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field. +func (m *ProviderAssignmentRunMutation) SetMarketBuyRateSnapshot(d decimal.Decimal) { + m.market_buy_rate_snapshot = &d + m.addmarket_buy_rate_snapshot = nil } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *ProviderBalancesMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at +// MarketBuyRateSnapshot returns the value of the "market_buy_rate_snapshot" field in the mutation. +func (m *ProviderAssignmentRunMutation) MarketBuyRateSnapshot() (r decimal.Decimal, exists bool) { + v := m.market_buy_rate_snapshot if v == nil { return } return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the ProviderBalances entity. -// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. +// OldMarketBuyRateSnapshot returns the old "market_buy_rate_snapshot" field's value of the ProviderAssignmentRun entity. +// If the ProviderAssignmentRun object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderBalancesMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ProviderAssignmentRunMutation) OldMarketBuyRateSnapshot(ctx context.Context) (v *decimal.Decimal, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldMarketBuyRateSnapshot is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + return v, errors.New("OldMarketBuyRateSnapshot requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldMarketBuyRateSnapshot: %w", err) } - return oldValue.UpdatedAt, nil + return oldValue.MarketBuyRateSnapshot, nil } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *ProviderBalancesMutation) ResetUpdatedAt() { - m.updated_at = nil +// AddMarketBuyRateSnapshot adds d to the "market_buy_rate_snapshot" field. +func (m *ProviderAssignmentRunMutation) AddMarketBuyRateSnapshot(d decimal.Decimal) { + if m.addmarket_buy_rate_snapshot != nil { + *m.addmarket_buy_rate_snapshot = m.addmarket_buy_rate_snapshot.Add(d) + } else { + m.addmarket_buy_rate_snapshot = &d + } } -// SetPeakBalance sets the "peak_balance" field. -func (m *ProviderBalancesMutation) SetPeakBalance(d decimal.Decimal) { - m.peak_balance = &d - m.addpeak_balance = nil +// AddedMarketBuyRateSnapshot returns the value that was added to the "market_buy_rate_snapshot" field in this mutation. +func (m *ProviderAssignmentRunMutation) AddedMarketBuyRateSnapshot() (r decimal.Decimal, exists bool) { + v := m.addmarket_buy_rate_snapshot + if v == nil { + return + } + return *v, true } -// PeakBalance returns the value of the "peak_balance" field in the mutation. -func (m *ProviderBalancesMutation) PeakBalance() (r decimal.Decimal, exists bool) { - v := m.peak_balance +// ClearMarketBuyRateSnapshot clears the value of the "market_buy_rate_snapshot" field. +func (m *ProviderAssignmentRunMutation) ClearMarketBuyRateSnapshot() { + m.market_buy_rate_snapshot = nil + m.addmarket_buy_rate_snapshot = nil + m.clearedFields[providerassignmentrun.FieldMarketBuyRateSnapshot] = struct{}{} +} + +// MarketBuyRateSnapshotCleared returns if the "market_buy_rate_snapshot" field was cleared in this mutation. +func (m *ProviderAssignmentRunMutation) MarketBuyRateSnapshotCleared() bool { + _, ok := m.clearedFields[providerassignmentrun.FieldMarketBuyRateSnapshot] + return ok +} + +// ResetMarketBuyRateSnapshot resets all changes to the "market_buy_rate_snapshot" field. +func (m *ProviderAssignmentRunMutation) ResetMarketBuyRateSnapshot() { + m.market_buy_rate_snapshot = nil + m.addmarket_buy_rate_snapshot = nil + delete(m.clearedFields, providerassignmentrun.FieldMarketBuyRateSnapshot) +} + +// SetMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field. +func (m *ProviderAssignmentRunMutation) SetMarketSellRateSnapshot(d decimal.Decimal) { + m.market_sell_rate_snapshot = &d + m.addmarket_sell_rate_snapshot = nil +} + +// MarketSellRateSnapshot returns the value of the "market_sell_rate_snapshot" field in the mutation. +func (m *ProviderAssignmentRunMutation) MarketSellRateSnapshot() (r decimal.Decimal, exists bool) { + v := m.market_sell_rate_snapshot if v == nil { return } return *v, true } -// OldPeakBalance returns the old "peak_balance" field's value of the ProviderBalances entity. -// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. +// OldMarketSellRateSnapshot returns the old "market_sell_rate_snapshot" field's value of the ProviderAssignmentRun entity. +// If the ProviderAssignmentRun object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderBalancesMutation) OldPeakBalance(ctx context.Context) (v decimal.Decimal, err error) { +func (m *ProviderAssignmentRunMutation) OldMarketSellRateSnapshot(ctx context.Context) (v *decimal.Decimal, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPeakBalance is only allowed on UpdateOne operations") + return v, errors.New("OldMarketSellRateSnapshot is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPeakBalance requires an ID field in the mutation") + return v, errors.New("OldMarketSellRateSnapshot requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldPeakBalance: %w", err) + return v, fmt.Errorf("querying old value for OldMarketSellRateSnapshot: %w", err) } - return oldValue.PeakBalance, nil + return oldValue.MarketSellRateSnapshot, nil } -// AddPeakBalance adds d to the "peak_balance" field. -func (m *ProviderBalancesMutation) AddPeakBalance(d decimal.Decimal) { - if m.addpeak_balance != nil { - *m.addpeak_balance = m.addpeak_balance.Add(d) +// AddMarketSellRateSnapshot adds d to the "market_sell_rate_snapshot" field. +func (m *ProviderAssignmentRunMutation) AddMarketSellRateSnapshot(d decimal.Decimal) { + if m.addmarket_sell_rate_snapshot != nil { + *m.addmarket_sell_rate_snapshot = m.addmarket_sell_rate_snapshot.Add(d) } else { - m.addpeak_balance = &d + m.addmarket_sell_rate_snapshot = &d } } -// AddedPeakBalance returns the value that was added to the "peak_balance" field in this mutation. -func (m *ProviderBalancesMutation) AddedPeakBalance() (r decimal.Decimal, exists bool) { - v := m.addpeak_balance +// AddedMarketSellRateSnapshot returns the value that was added to the "market_sell_rate_snapshot" field in this mutation. +func (m *ProviderAssignmentRunMutation) AddedMarketSellRateSnapshot() (r decimal.Decimal, exists bool) { + v := m.addmarket_sell_rate_snapshot if v == nil { return } return *v, true } -// ResetPeakBalance resets all changes to the "peak_balance" field. -func (m *ProviderBalancesMutation) ResetPeakBalance() { - m.peak_balance = nil - m.addpeak_balance = nil +// ClearMarketSellRateSnapshot clears the value of the "market_sell_rate_snapshot" field. +func (m *ProviderAssignmentRunMutation) ClearMarketSellRateSnapshot() { + m.market_sell_rate_snapshot = nil + m.addmarket_sell_rate_snapshot = nil + m.clearedFields[providerassignmentrun.FieldMarketSellRateSnapshot] = struct{}{} } -// SetProviderID sets the "provider" edge to the ProviderProfile entity by id. -func (m *ProviderBalancesMutation) SetProviderID(id string) { - m.provider = &id +// MarketSellRateSnapshotCleared returns if the "market_sell_rate_snapshot" field was cleared in this mutation. +func (m *ProviderAssignmentRunMutation) MarketSellRateSnapshotCleared() bool { + _, ok := m.clearedFields[providerassignmentrun.FieldMarketSellRateSnapshot] + return ok } -// ClearProvider clears the "provider" edge to the ProviderProfile entity. -func (m *ProviderBalancesMutation) ClearProvider() { - m.clearedprovider = true +// ResetMarketSellRateSnapshot resets all changes to the "market_sell_rate_snapshot" field. +func (m *ProviderAssignmentRunMutation) ResetMarketSellRateSnapshot() { + m.market_sell_rate_snapshot = nil + m.addmarket_sell_rate_snapshot = nil + delete(m.clearedFields, providerassignmentrun.FieldMarketSellRateSnapshot) } -// ProviderCleared reports if the "provider" edge to the ProviderProfile entity was cleared. -func (m *ProviderBalancesMutation) ProviderCleared() bool { - return m.clearedprovider +// SetErrorMessage sets the "error_message" field. +func (m *ProviderAssignmentRunMutation) SetErrorMessage(s string) { + m.error_message = &s } -// ProviderID returns the "provider" edge ID in the mutation. -func (m *ProviderBalancesMutation) ProviderID() (id string, exists bool) { - if m.provider != nil { - return *m.provider, true +// ErrorMessage returns the value of the "error_message" field in the mutation. +func (m *ProviderAssignmentRunMutation) ErrorMessage() (r string, exists bool) { + v := m.error_message + if v == nil { + return } - return + return *v, true } -// ProviderIDs returns the "provider" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// ProviderID instead. It exists only for internal usage by the builders. -func (m *ProviderBalancesMutation) ProviderIDs() (ids []string) { - if id := m.provider; id != nil { - ids = append(ids, *id) +// OldErrorMessage returns the old "error_message" field's value of the ProviderAssignmentRun entity. +// If the ProviderAssignmentRun object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderAssignmentRunMutation) OldErrorMessage(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldErrorMessage is only allowed on UpdateOne operations") } - return + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldErrorMessage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldErrorMessage: %w", err) + } + return oldValue.ErrorMessage, nil } -// ResetProvider resets all changes to the "provider" edge. -func (m *ProviderBalancesMutation) ResetProvider() { - m.provider = nil - m.clearedprovider = false +// ClearErrorMessage clears the value of the "error_message" field. +func (m *ProviderAssignmentRunMutation) ClearErrorMessage() { + m.error_message = nil + m.clearedFields[providerassignmentrun.FieldErrorMessage] = struct{}{} } -// SetFiatCurrencyID sets the "fiat_currency" edge to the FiatCurrency entity by id. -func (m *ProviderBalancesMutation) SetFiatCurrencyID(id uuid.UUID) { - m.fiat_currency = &id +// ErrorMessageCleared returns if the "error_message" field was cleared in this mutation. +func (m *ProviderAssignmentRunMutation) ErrorMessageCleared() bool { + _, ok := m.clearedFields[providerassignmentrun.FieldErrorMessage] + return ok } -// ClearFiatCurrency clears the "fiat_currency" edge to the FiatCurrency entity. -func (m *ProviderBalancesMutation) ClearFiatCurrency() { - m.clearedfiat_currency = true +// ResetErrorMessage resets all changes to the "error_message" field. +func (m *ProviderAssignmentRunMutation) ResetErrorMessage() { + m.error_message = nil + delete(m.clearedFields, providerassignmentrun.FieldErrorMessage) } -// FiatCurrencyCleared reports if the "fiat_currency" edge to the FiatCurrency entity was cleared. -func (m *ProviderBalancesMutation) FiatCurrencyCleared() bool { - return m.clearedfiat_currency +// SetPaymentOrderID sets the "payment_order" edge to the PaymentOrder entity by id. +func (m *ProviderAssignmentRunMutation) SetPaymentOrderID(id uuid.UUID) { + m.payment_order = &id } -// FiatCurrencyID returns the "fiat_currency" edge ID in the mutation. -func (m *ProviderBalancesMutation) FiatCurrencyID() (id uuid.UUID, exists bool) { - if m.fiat_currency != nil { - return *m.fiat_currency, true +// ClearPaymentOrder clears the "payment_order" edge to the PaymentOrder entity. +func (m *ProviderAssignmentRunMutation) ClearPaymentOrder() { + m.clearedpayment_order = true +} + +// PaymentOrderCleared reports if the "payment_order" edge to the PaymentOrder entity was cleared. +func (m *ProviderAssignmentRunMutation) PaymentOrderCleared() bool { + return m.clearedpayment_order +} + +// PaymentOrderID returns the "payment_order" edge ID in the mutation. +func (m *ProviderAssignmentRunMutation) PaymentOrderID() (id uuid.UUID, exists bool) { + if m.payment_order != nil { + return *m.payment_order, true } return } -// FiatCurrencyIDs returns the "fiat_currency" edge IDs in the mutation. +// PaymentOrderIDs returns the "payment_order" edge IDs in the mutation. // Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// FiatCurrencyID instead. It exists only for internal usage by the builders. -func (m *ProviderBalancesMutation) FiatCurrencyIDs() (ids []uuid.UUID) { - if id := m.fiat_currency; id != nil { +// PaymentOrderID instead. It exists only for internal usage by the builders. +func (m *ProviderAssignmentRunMutation) PaymentOrderIDs() (ids []uuid.UUID) { + if id := m.payment_order; id != nil { ids = append(ids, *id) } return } -// ResetFiatCurrency resets all changes to the "fiat_currency" edge. -func (m *ProviderBalancesMutation) ResetFiatCurrency() { - m.fiat_currency = nil - m.clearedfiat_currency = false +// ResetPaymentOrder resets all changes to the "payment_order" edge. +func (m *ProviderAssignmentRunMutation) ResetPaymentOrder() { + m.payment_order = nil + m.clearedpayment_order = false } -// SetTokenID sets the "token" edge to the Token entity by id. -func (m *ProviderBalancesMutation) SetTokenID(id int) { - m.token = &id +// SetProviderOrderTokenID sets the "provider_order_token" edge to the ProviderOrderToken entity by id. +func (m *ProviderAssignmentRunMutation) SetProviderOrderTokenID(id int) { + m.provider_order_token = &id } -// ClearToken clears the "token" edge to the Token entity. -func (m *ProviderBalancesMutation) ClearToken() { - m.clearedtoken = true +// ClearProviderOrderToken clears the "provider_order_token" edge to the ProviderOrderToken entity. +func (m *ProviderAssignmentRunMutation) ClearProviderOrderToken() { + m.clearedprovider_order_token = true } -// TokenCleared reports if the "token" edge to the Token entity was cleared. -func (m *ProviderBalancesMutation) TokenCleared() bool { - return m.clearedtoken +// ProviderOrderTokenCleared reports if the "provider_order_token" edge to the ProviderOrderToken entity was cleared. +func (m *ProviderAssignmentRunMutation) ProviderOrderTokenCleared() bool { + return m.clearedprovider_order_token } -// TokenID returns the "token" edge ID in the mutation. -func (m *ProviderBalancesMutation) TokenID() (id int, exists bool) { - if m.token != nil { - return *m.token, true +// ProviderOrderTokenID returns the "provider_order_token" edge ID in the mutation. +func (m *ProviderAssignmentRunMutation) ProviderOrderTokenID() (id int, exists bool) { + if m.provider_order_token != nil { + return *m.provider_order_token, true } return } -// TokenIDs returns the "token" edge IDs in the mutation. +// ProviderOrderTokenIDs returns the "provider_order_token" edge IDs in the mutation. // Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// TokenID instead. It exists only for internal usage by the builders. -func (m *ProviderBalancesMutation) TokenIDs() (ids []int) { - if id := m.token; id != nil { +// ProviderOrderTokenID instead. It exists only for internal usage by the builders. +func (m *ProviderAssignmentRunMutation) ProviderOrderTokenIDs() (ids []int) { + if id := m.provider_order_token; id != nil { ids = append(ids, *id) } return } -// ResetToken resets all changes to the "token" edge. -func (m *ProviderBalancesMutation) ResetToken() { - m.token = nil - m.clearedtoken = false +// ResetProviderOrderToken resets all changes to the "provider_order_token" edge. +func (m *ProviderAssignmentRunMutation) ResetProviderOrderToken() { + m.provider_order_token = nil + m.clearedprovider_order_token = false } -// Where appends a list predicates to the ProviderBalancesMutation builder. -func (m *ProviderBalancesMutation) Where(ps ...predicate.ProviderBalances) { +// Where appends a list predicates to the ProviderAssignmentRunMutation builder. +func (m *ProviderAssignmentRunMutation) Where(ps ...predicate.ProviderAssignmentRun) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the ProviderBalancesMutation builder. Using this method, +// WhereP appends storage-level predicates to the ProviderAssignmentRunMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *ProviderBalancesMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.ProviderBalances, len(ps)) +func (m *ProviderAssignmentRunMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ProviderAssignmentRun, len(ps)) for i := range ps { p[i] = ps[i] } @@ -11988,42 +12382,48 @@ func (m *ProviderBalancesMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *ProviderBalancesMutation) Op() Op { +func (m *ProviderAssignmentRunMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *ProviderBalancesMutation) SetOp(op Op) { +func (m *ProviderAssignmentRunMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (ProviderBalances). -func (m *ProviderBalancesMutation) Type() string { +// Type returns the node type of this mutation (ProviderAssignmentRun). +func (m *ProviderAssignmentRunMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *ProviderBalancesMutation) Fields() []string { - fields := make([]string, 0, 6) - if m.available_balance != nil { - fields = append(fields, providerbalances.FieldAvailableBalance) +func (m *ProviderAssignmentRunMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.assigned_provider_id != nil { + fields = append(fields, providerassignmentrun.FieldAssignedProviderID) } - if m.total_balance != nil { - fields = append(fields, providerbalances.FieldTotalBalance) + if m.attempted_at != nil { + fields = append(fields, providerassignmentrun.FieldAttemptedAt) } - if m.reserved_balance != nil { - fields = append(fields, providerbalances.FieldReservedBalance) + if m.trigger != nil { + fields = append(fields, providerassignmentrun.FieldTrigger) } - if m.is_available != nil { - fields = append(fields, providerbalances.FieldIsAvailable) + if m.result != nil { + fields = append(fields, providerassignmentrun.FieldResult) } - if m.updated_at != nil { - fields = append(fields, providerbalances.FieldUpdatedAt) + if m.used_fallback != nil { + fields = append(fields, providerassignmentrun.FieldUsedFallback) } - if m.peak_balance != nil { - fields = append(fields, providerbalances.FieldPeakBalance) + if m.market_buy_rate_snapshot != nil { + fields = append(fields, providerassignmentrun.FieldMarketBuyRateSnapshot) + } + if m.market_sell_rate_snapshot != nil { + fields = append(fields, providerassignmentrun.FieldMarketSellRateSnapshot) + } + if m.error_message != nil { + fields = append(fields, providerassignmentrun.FieldErrorMessage) } return fields } @@ -12031,20 +12431,24 @@ func (m *ProviderBalancesMutation) Fields() []string { // Field returns the value of a field with the given name. The second boolean // return value indicates that this field was not set, or was not defined in the // schema. -func (m *ProviderBalancesMutation) Field(name string) (ent.Value, bool) { +func (m *ProviderAssignmentRunMutation) Field(name string) (ent.Value, bool) { switch name { - case providerbalances.FieldAvailableBalance: - return m.AvailableBalance() - case providerbalances.FieldTotalBalance: - return m.TotalBalance() - case providerbalances.FieldReservedBalance: - return m.ReservedBalance() - case providerbalances.FieldIsAvailable: - return m.IsAvailable() - case providerbalances.FieldUpdatedAt: - return m.UpdatedAt() - case providerbalances.FieldPeakBalance: - return m.PeakBalance() + case providerassignmentrun.FieldAssignedProviderID: + return m.AssignedProviderID() + case providerassignmentrun.FieldAttemptedAt: + return m.AttemptedAt() + case providerassignmentrun.FieldTrigger: + return m.Trigger() + case providerassignmentrun.FieldResult: + return m.Result() + case providerassignmentrun.FieldUsedFallback: + return m.UsedFallback() + case providerassignmentrun.FieldMarketBuyRateSnapshot: + return m.MarketBuyRateSnapshot() + case providerassignmentrun.FieldMarketSellRateSnapshot: + return m.MarketSellRateSnapshot() + case providerassignmentrun.FieldErrorMessage: + return m.ErrorMessage() } return nil, false } @@ -12052,90 +12456,102 @@ func (m *ProviderBalancesMutation) Field(name string) (ent.Value, bool) { // OldField returns the old value of the field from the database. An error is // returned if the mutation operation is not UpdateOne, or the query to the // database failed. -func (m *ProviderBalancesMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *ProviderAssignmentRunMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case providerbalances.FieldAvailableBalance: - return m.OldAvailableBalance(ctx) - case providerbalances.FieldTotalBalance: - return m.OldTotalBalance(ctx) - case providerbalances.FieldReservedBalance: - return m.OldReservedBalance(ctx) - case providerbalances.FieldIsAvailable: - return m.OldIsAvailable(ctx) - case providerbalances.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - case providerbalances.FieldPeakBalance: - return m.OldPeakBalance(ctx) - } - return nil, fmt.Errorf("unknown ProviderBalances field %s", name) + case providerassignmentrun.FieldAssignedProviderID: + return m.OldAssignedProviderID(ctx) + case providerassignmentrun.FieldAttemptedAt: + return m.OldAttemptedAt(ctx) + case providerassignmentrun.FieldTrigger: + return m.OldTrigger(ctx) + case providerassignmentrun.FieldResult: + return m.OldResult(ctx) + case providerassignmentrun.FieldUsedFallback: + return m.OldUsedFallback(ctx) + case providerassignmentrun.FieldMarketBuyRateSnapshot: + return m.OldMarketBuyRateSnapshot(ctx) + case providerassignmentrun.FieldMarketSellRateSnapshot: + return m.OldMarketSellRateSnapshot(ctx) + case providerassignmentrun.FieldErrorMessage: + return m.OldErrorMessage(ctx) + } + return nil, fmt.Errorf("unknown ProviderAssignmentRun field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *ProviderBalancesMutation) SetField(name string, value ent.Value) error { +func (m *ProviderAssignmentRunMutation) SetField(name string, value ent.Value) error { switch name { - case providerbalances.FieldAvailableBalance: - v, ok := value.(decimal.Decimal) + case providerassignmentrun.FieldAssignedProviderID: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetAvailableBalance(v) + m.SetAssignedProviderID(v) return nil - case providerbalances.FieldTotalBalance: - v, ok := value.(decimal.Decimal) + case providerassignmentrun.FieldAttemptedAt: + v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetTotalBalance(v) + m.SetAttemptedAt(v) return nil - case providerbalances.FieldReservedBalance: - v, ok := value.(decimal.Decimal) + case providerassignmentrun.FieldTrigger: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetReservedBalance(v) + m.SetTrigger(v) return nil - case providerbalances.FieldIsAvailable: + case providerassignmentrun.FieldResult: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetResult(v) + return nil + case providerassignmentrun.FieldUsedFallback: v, ok := value.(bool) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetIsAvailable(v) + m.SetUsedFallback(v) return nil - case providerbalances.FieldUpdatedAt: - v, ok := value.(time.Time) + case providerassignmentrun.FieldMarketBuyRateSnapshot: + v, ok := value.(decimal.Decimal) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetUpdatedAt(v) + m.SetMarketBuyRateSnapshot(v) return nil - case providerbalances.FieldPeakBalance: + case providerassignmentrun.FieldMarketSellRateSnapshot: v, ok := value.(decimal.Decimal) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetPeakBalance(v) + m.SetMarketSellRateSnapshot(v) + return nil + case providerassignmentrun.FieldErrorMessage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetErrorMessage(v) return nil } - return fmt.Errorf("unknown ProviderBalances field %s", name) + return fmt.Errorf("unknown ProviderAssignmentRun field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *ProviderBalancesMutation) AddedFields() []string { +func (m *ProviderAssignmentRunMutation) AddedFields() []string { var fields []string - if m.addavailable_balance != nil { - fields = append(fields, providerbalances.FieldAvailableBalance) - } - if m.addtotal_balance != nil { - fields = append(fields, providerbalances.FieldTotalBalance) + if m.addmarket_buy_rate_snapshot != nil { + fields = append(fields, providerassignmentrun.FieldMarketBuyRateSnapshot) } - if m.addreserved_balance != nil { - fields = append(fields, providerbalances.FieldReservedBalance) - } - if m.addpeak_balance != nil { - fields = append(fields, providerbalances.FieldPeakBalance) + if m.addmarket_sell_rate_snapshot != nil { + fields = append(fields, providerassignmentrun.FieldMarketSellRateSnapshot) } return fields } @@ -12143,16 +12559,12 @@ func (m *ProviderBalancesMutation) AddedFields() []string { // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *ProviderBalancesMutation) AddedField(name string) (ent.Value, bool) { +func (m *ProviderAssignmentRunMutation) AddedField(name string) (ent.Value, bool) { switch name { - case providerbalances.FieldAvailableBalance: - return m.AddedAvailableBalance() - case providerbalances.FieldTotalBalance: - return m.AddedTotalBalance() - case providerbalances.FieldReservedBalance: - return m.AddedReservedBalance() - case providerbalances.FieldPeakBalance: - return m.AddedPeakBalance() + case providerassignmentrun.FieldMarketBuyRateSnapshot: + return m.AddedMarketBuyRateSnapshot() + case providerassignmentrun.FieldMarketSellRateSnapshot: + return m.AddedMarketSellRateSnapshot() } return nil, false } @@ -12160,114 +12572,126 @@ func (m *ProviderBalancesMutation) AddedField(name string) (ent.Value, bool) { // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *ProviderBalancesMutation) AddField(name string, value ent.Value) error { +func (m *ProviderAssignmentRunMutation) AddField(name string, value ent.Value) error { switch name { - case providerbalances.FieldAvailableBalance: + case providerassignmentrun.FieldMarketBuyRateSnapshot: v, ok := value.(decimal.Decimal) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.AddAvailableBalance(v) + m.AddMarketBuyRateSnapshot(v) return nil - case providerbalances.FieldTotalBalance: + case providerassignmentrun.FieldMarketSellRateSnapshot: v, ok := value.(decimal.Decimal) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.AddTotalBalance(v) - return nil - case providerbalances.FieldReservedBalance: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddReservedBalance(v) - return nil - case providerbalances.FieldPeakBalance: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddPeakBalance(v) + m.AddMarketSellRateSnapshot(v) return nil } - return fmt.Errorf("unknown ProviderBalances numeric field %s", name) + return fmt.Errorf("unknown ProviderAssignmentRun numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *ProviderBalancesMutation) ClearedFields() []string { - return nil +func (m *ProviderAssignmentRunMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(providerassignmentrun.FieldAssignedProviderID) { + fields = append(fields, providerassignmentrun.FieldAssignedProviderID) + } + if m.FieldCleared(providerassignmentrun.FieldMarketBuyRateSnapshot) { + fields = append(fields, providerassignmentrun.FieldMarketBuyRateSnapshot) + } + if m.FieldCleared(providerassignmentrun.FieldMarketSellRateSnapshot) { + fields = append(fields, providerassignmentrun.FieldMarketSellRateSnapshot) + } + if m.FieldCleared(providerassignmentrun.FieldErrorMessage) { + fields = append(fields, providerassignmentrun.FieldErrorMessage) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *ProviderBalancesMutation) FieldCleared(name string) bool { +func (m *ProviderAssignmentRunMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. -func (m *ProviderBalancesMutation) ClearField(name string) error { - return fmt.Errorf("unknown ProviderBalances nullable field %s", name) +func (m *ProviderAssignmentRunMutation) ClearField(name string) error { + switch name { + case providerassignmentrun.FieldAssignedProviderID: + m.ClearAssignedProviderID() + return nil + case providerassignmentrun.FieldMarketBuyRateSnapshot: + m.ClearMarketBuyRateSnapshot() + return nil + case providerassignmentrun.FieldMarketSellRateSnapshot: + m.ClearMarketSellRateSnapshot() + return nil + case providerassignmentrun.FieldErrorMessage: + m.ClearErrorMessage() + return nil + } + return fmt.Errorf("unknown ProviderAssignmentRun nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *ProviderBalancesMutation) ResetField(name string) error { +func (m *ProviderAssignmentRunMutation) ResetField(name string) error { switch name { - case providerbalances.FieldAvailableBalance: - m.ResetAvailableBalance() + case providerassignmentrun.FieldAssignedProviderID: + m.ResetAssignedProviderID() return nil - case providerbalances.FieldTotalBalance: - m.ResetTotalBalance() + case providerassignmentrun.FieldAttemptedAt: + m.ResetAttemptedAt() return nil - case providerbalances.FieldReservedBalance: - m.ResetReservedBalance() + case providerassignmentrun.FieldTrigger: + m.ResetTrigger() return nil - case providerbalances.FieldIsAvailable: - m.ResetIsAvailable() + case providerassignmentrun.FieldResult: + m.ResetResult() return nil - case providerbalances.FieldUpdatedAt: - m.ResetUpdatedAt() + case providerassignmentrun.FieldUsedFallback: + m.ResetUsedFallback() return nil - case providerbalances.FieldPeakBalance: - m.ResetPeakBalance() + case providerassignmentrun.FieldMarketBuyRateSnapshot: + m.ResetMarketBuyRateSnapshot() + return nil + case providerassignmentrun.FieldMarketSellRateSnapshot: + m.ResetMarketSellRateSnapshot() + return nil + case providerassignmentrun.FieldErrorMessage: + m.ResetErrorMessage() return nil } - return fmt.Errorf("unknown ProviderBalances field %s", name) + return fmt.Errorf("unknown ProviderAssignmentRun field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *ProviderBalancesMutation) AddedEdges() []string { - edges := make([]string, 0, 3) - if m.provider != nil { - edges = append(edges, providerbalances.EdgeProvider) - } - if m.fiat_currency != nil { - edges = append(edges, providerbalances.EdgeFiatCurrency) +func (m *ProviderAssignmentRunMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.payment_order != nil { + edges = append(edges, providerassignmentrun.EdgePaymentOrder) } - if m.token != nil { - edges = append(edges, providerbalances.EdgeToken) + if m.provider_order_token != nil { + edges = append(edges, providerassignmentrun.EdgeProviderOrderToken) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *ProviderBalancesMutation) AddedIDs(name string) []ent.Value { +func (m *ProviderAssignmentRunMutation) AddedIDs(name string) []ent.Value { switch name { - case providerbalances.EdgeProvider: - if id := m.provider; id != nil { - return []ent.Value{*id} - } - case providerbalances.EdgeFiatCurrency: - if id := m.fiat_currency; id != nil { + case providerassignmentrun.EdgePaymentOrder: + if id := m.payment_order; id != nil { return []ent.Value{*id} } - case providerbalances.EdgeToken: - if id := m.token; id != nil { + case providerassignmentrun.EdgeProviderOrderToken: + if id := m.provider_order_token; id != nil { return []ent.Value{*id} } } @@ -12275,110 +12699,108 @@ func (m *ProviderBalancesMutation) AddedIDs(name string) []ent.Value { } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *ProviderBalancesMutation) RemovedEdges() []string { - edges := make([]string, 0, 3) +func (m *ProviderAssignmentRunMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *ProviderBalancesMutation) RemovedIDs(name string) []ent.Value { +func (m *ProviderAssignmentRunMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *ProviderBalancesMutation) ClearedEdges() []string { - edges := make([]string, 0, 3) - if m.clearedprovider { - edges = append(edges, providerbalances.EdgeProvider) - } - if m.clearedfiat_currency { - edges = append(edges, providerbalances.EdgeFiatCurrency) +func (m *ProviderAssignmentRunMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedpayment_order { + edges = append(edges, providerassignmentrun.EdgePaymentOrder) } - if m.clearedtoken { - edges = append(edges, providerbalances.EdgeToken) + if m.clearedprovider_order_token { + edges = append(edges, providerassignmentrun.EdgeProviderOrderToken) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *ProviderBalancesMutation) EdgeCleared(name string) bool { +func (m *ProviderAssignmentRunMutation) EdgeCleared(name string) bool { switch name { - case providerbalances.EdgeProvider: - return m.clearedprovider - case providerbalances.EdgeFiatCurrency: - return m.clearedfiat_currency - case providerbalances.EdgeToken: - return m.clearedtoken + case providerassignmentrun.EdgePaymentOrder: + return m.clearedpayment_order + case providerassignmentrun.EdgeProviderOrderToken: + return m.clearedprovider_order_token } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *ProviderBalancesMutation) ClearEdge(name string) error { +func (m *ProviderAssignmentRunMutation) ClearEdge(name string) error { switch name { - case providerbalances.EdgeProvider: - m.ClearProvider() - return nil - case providerbalances.EdgeFiatCurrency: - m.ClearFiatCurrency() + case providerassignmentrun.EdgePaymentOrder: + m.ClearPaymentOrder() return nil - case providerbalances.EdgeToken: - m.ClearToken() + case providerassignmentrun.EdgeProviderOrderToken: + m.ClearProviderOrderToken() return nil } - return fmt.Errorf("unknown ProviderBalances unique edge %s", name) + return fmt.Errorf("unknown ProviderAssignmentRun unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *ProviderBalancesMutation) ResetEdge(name string) error { +func (m *ProviderAssignmentRunMutation) ResetEdge(name string) error { switch name { - case providerbalances.EdgeProvider: - m.ResetProvider() - return nil - case providerbalances.EdgeFiatCurrency: - m.ResetFiatCurrency() + case providerassignmentrun.EdgePaymentOrder: + m.ResetPaymentOrder() return nil - case providerbalances.EdgeToken: - m.ResetToken() + case providerassignmentrun.EdgeProviderOrderToken: + m.ResetProviderOrderToken() return nil } - return fmt.Errorf("unknown ProviderBalances edge %s", name) + return fmt.Errorf("unknown ProviderAssignmentRun edge %s", name) } -// ProviderFiatAccountMutation represents an operation that mutates the ProviderFiatAccount nodes in the graph. -type ProviderFiatAccountMutation struct { +// ProviderBalancesMutation represents an operation that mutates the ProviderBalances nodes in the graph. +type ProviderBalancesMutation struct { config - op Op - typ string - id *uuid.UUID - created_at *time.Time - updated_at *time.Time - institution *string - account_identifier *string - account_name *string - clearedFields map[string]struct{} - provider *string - clearedprovider bool - done bool - oldValue func(context.Context) (*ProviderFiatAccount, error) - predicates []predicate.ProviderFiatAccount + op Op + typ string + id *uuid.UUID + available_balance *decimal.Decimal + addavailable_balance *decimal.Decimal + total_balance *decimal.Decimal + addtotal_balance *decimal.Decimal + reserved_balance *decimal.Decimal + addreserved_balance *decimal.Decimal + is_available *bool + updated_at *time.Time + peak_balance *decimal.Decimal + addpeak_balance *decimal.Decimal + clearedFields map[string]struct{} + provider *string + clearedprovider bool + fiat_currency *uuid.UUID + clearedfiat_currency bool + token *int + clearedtoken bool + done bool + oldValue func(context.Context) (*ProviderBalances, error) + predicates []predicate.ProviderBalances } -var _ ent.Mutation = (*ProviderFiatAccountMutation)(nil) +var _ ent.Mutation = (*ProviderBalancesMutation)(nil) -// providerfiataccountOption allows management of the mutation configuration using functional options. -type providerfiataccountOption func(*ProviderFiatAccountMutation) +// providerbalancesOption allows management of the mutation configuration using functional options. +type providerbalancesOption func(*ProviderBalancesMutation) -// newProviderFiatAccountMutation creates new mutation for the ProviderFiatAccount entity. -func newProviderFiatAccountMutation(c config, op Op, opts ...providerfiataccountOption) *ProviderFiatAccountMutation { - m := &ProviderFiatAccountMutation{ +// newProviderBalancesMutation creates new mutation for the ProviderBalances entity. +func newProviderBalancesMutation(c config, op Op, opts ...providerbalancesOption) *ProviderBalancesMutation { + m := &ProviderBalancesMutation{ config: c, op: op, - typ: TypeProviderFiatAccount, + typ: TypeProviderBalances, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -12387,20 +12809,20 @@ func newProviderFiatAccountMutation(c config, op Op, opts ...providerfiataccount return m } -// withProviderFiatAccountID sets the ID field of the mutation. -func withProviderFiatAccountID(id uuid.UUID) providerfiataccountOption { - return func(m *ProviderFiatAccountMutation) { +// withProviderBalancesID sets the ID field of the mutation. +func withProviderBalancesID(id uuid.UUID) providerbalancesOption { + return func(m *ProviderBalancesMutation) { var ( err error once sync.Once - value *ProviderFiatAccount + value *ProviderBalances ) - m.oldValue = func(ctx context.Context) (*ProviderFiatAccount, error) { + m.oldValue = func(ctx context.Context) (*ProviderBalances, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().ProviderFiatAccount.Get(ctx, id) + value, err = m.Client().ProviderBalances.Get(ctx, id) } }) return value, err @@ -12409,10 +12831,10 @@ func withProviderFiatAccountID(id uuid.UUID) providerfiataccountOption { } } -// withProviderFiatAccount sets the old ProviderFiatAccount of the mutation. -func withProviderFiatAccount(node *ProviderFiatAccount) providerfiataccountOption { - return func(m *ProviderFiatAccountMutation) { - m.oldValue = func(context.Context) (*ProviderFiatAccount, error) { +// withProviderBalances sets the old ProviderBalances of the mutation. +func withProviderBalances(node *ProviderBalances) providerbalancesOption { + return func(m *ProviderBalancesMutation) { + m.oldValue = func(context.Context) (*ProviderBalances, error) { return node, nil } m.id = &node.ID @@ -12421,7 +12843,7 @@ func withProviderFiatAccount(node *ProviderFiatAccount) providerfiataccountOptio // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m ProviderFiatAccountMutation) Client() *Client { +func (m ProviderBalancesMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -12429,7 +12851,7 @@ func (m ProviderFiatAccountMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m ProviderFiatAccountMutation) Tx() (*Tx, error) { +func (m ProviderBalancesMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("ent: mutation is not running in a transaction") } @@ -12439,14 +12861,14 @@ func (m ProviderFiatAccountMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of ProviderFiatAccount entities. -func (m *ProviderFiatAccountMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of ProviderBalances entities. +func (m *ProviderBalancesMutation) SetID(id uuid.UUID) { m.id = &id } // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *ProviderFiatAccountMutation) ID() (id uuid.UUID, exists bool) { +func (m *ProviderBalancesMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -12457,7 +12879,7 @@ func (m *ProviderFiatAccountMutation) ID() (id uuid.UUID, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *ProviderFiatAccountMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *ProviderBalancesMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -12466,209 +12888,325 @@ func (m *ProviderFiatAccountMutation) IDs(ctx context.Context) ([]uuid.UUID, err } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().ProviderFiatAccount.Query().Where(m.predicates...).IDs(ctx) + return m.Client().ProviderBalances.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetCreatedAt sets the "created_at" field. -func (m *ProviderFiatAccountMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// SetAvailableBalance sets the "available_balance" field. +func (m *ProviderBalancesMutation) SetAvailableBalance(d decimal.Decimal) { + m.available_balance = &d + m.addavailable_balance = nil } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *ProviderFiatAccountMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at +// AvailableBalance returns the value of the "available_balance" field in the mutation. +func (m *ProviderBalancesMutation) AvailableBalance() (r decimal.Decimal, exists bool) { + v := m.available_balance if v == nil { return } return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the ProviderFiatAccount entity. -// If the ProviderFiatAccount object wasn't provided to the builder, the object is fetched from the database. +// OldAvailableBalance returns the old "available_balance" field's value of the ProviderBalances entity. +// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderFiatAccountMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ProviderBalancesMutation) OldAvailableBalance(ctx context.Context) (v decimal.Decimal, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldAvailableBalance is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") + return v, errors.New("OldAvailableBalance requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + return v, fmt.Errorf("querying old value for OldAvailableBalance: %w", err) } - return oldValue.CreatedAt, nil -} - -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *ProviderFiatAccountMutation) ResetCreatedAt() { - m.created_at = nil + return oldValue.AvailableBalance, nil } -// SetUpdatedAt sets the "updated_at" field. -func (m *ProviderFiatAccountMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// AddAvailableBalance adds d to the "available_balance" field. +func (m *ProviderBalancesMutation) AddAvailableBalance(d decimal.Decimal) { + if m.addavailable_balance != nil { + *m.addavailable_balance = m.addavailable_balance.Add(d) + } else { + m.addavailable_balance = &d + } } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *ProviderFiatAccountMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at +// AddedAvailableBalance returns the value that was added to the "available_balance" field in this mutation. +func (m *ProviderBalancesMutation) AddedAvailableBalance() (r decimal.Decimal, exists bool) { + v := m.addavailable_balance if v == nil { return } return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the ProviderFiatAccount entity. -// If the ProviderFiatAccount object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderFiatAccountMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) +// ResetAvailableBalance resets all changes to the "available_balance" field. +func (m *ProviderBalancesMutation) ResetAvailableBalance() { + m.available_balance = nil + m.addavailable_balance = nil +} + +// SetTotalBalance sets the "total_balance" field. +func (m *ProviderBalancesMutation) SetTotalBalance(d decimal.Decimal) { + m.total_balance = &d + m.addtotal_balance = nil +} + +// TotalBalance returns the value of the "total_balance" field in the mutation. +func (m *ProviderBalancesMutation) TotalBalance() (r decimal.Decimal, exists bool) { + v := m.total_balance + if v == nil { + return } - return oldValue.UpdatedAt, nil + return *v, true } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *ProviderFiatAccountMutation) ResetUpdatedAt() { - m.updated_at = nil +// OldTotalBalance returns the old "total_balance" field's value of the ProviderBalances entity. +// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderBalancesMutation) OldTotalBalance(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTotalBalance is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTotalBalance requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTotalBalance: %w", err) + } + return oldValue.TotalBalance, nil } -// SetInstitution sets the "institution" field. -func (m *ProviderFiatAccountMutation) SetInstitution(s string) { - m.institution = &s +// AddTotalBalance adds d to the "total_balance" field. +func (m *ProviderBalancesMutation) AddTotalBalance(d decimal.Decimal) { + if m.addtotal_balance != nil { + *m.addtotal_balance = m.addtotal_balance.Add(d) + } else { + m.addtotal_balance = &d + } } -// Institution returns the value of the "institution" field in the mutation. -func (m *ProviderFiatAccountMutation) Institution() (r string, exists bool) { - v := m.institution +// AddedTotalBalance returns the value that was added to the "total_balance" field in this mutation. +func (m *ProviderBalancesMutation) AddedTotalBalance() (r decimal.Decimal, exists bool) { + v := m.addtotal_balance if v == nil { return } return *v, true } -// OldInstitution returns the old "institution" field's value of the ProviderFiatAccount entity. -// If the ProviderFiatAccount object wasn't provided to the builder, the object is fetched from the database. +// ResetTotalBalance resets all changes to the "total_balance" field. +func (m *ProviderBalancesMutation) ResetTotalBalance() { + m.total_balance = nil + m.addtotal_balance = nil +} + +// SetReservedBalance sets the "reserved_balance" field. +func (m *ProviderBalancesMutation) SetReservedBalance(d decimal.Decimal) { + m.reserved_balance = &d + m.addreserved_balance = nil +} + +// ReservedBalance returns the value of the "reserved_balance" field in the mutation. +func (m *ProviderBalancesMutation) ReservedBalance() (r decimal.Decimal, exists bool) { + v := m.reserved_balance + if v == nil { + return + } + return *v, true +} + +// OldReservedBalance returns the old "reserved_balance" field's value of the ProviderBalances entity. +// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderFiatAccountMutation) OldInstitution(ctx context.Context) (v string, err error) { +func (m *ProviderBalancesMutation) OldReservedBalance(ctx context.Context) (v decimal.Decimal, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldInstitution is only allowed on UpdateOne operations") + return v, errors.New("OldReservedBalance is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldInstitution requires an ID field in the mutation") + return v, errors.New("OldReservedBalance requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldInstitution: %w", err) + return v, fmt.Errorf("querying old value for OldReservedBalance: %w", err) } - return oldValue.Institution, nil + return oldValue.ReservedBalance, nil } -// ResetInstitution resets all changes to the "institution" field. -func (m *ProviderFiatAccountMutation) ResetInstitution() { - m.institution = nil +// AddReservedBalance adds d to the "reserved_balance" field. +func (m *ProviderBalancesMutation) AddReservedBalance(d decimal.Decimal) { + if m.addreserved_balance != nil { + *m.addreserved_balance = m.addreserved_balance.Add(d) + } else { + m.addreserved_balance = &d + } } -// SetAccountIdentifier sets the "account_identifier" field. -func (m *ProviderFiatAccountMutation) SetAccountIdentifier(s string) { - m.account_identifier = &s +// AddedReservedBalance returns the value that was added to the "reserved_balance" field in this mutation. +func (m *ProviderBalancesMutation) AddedReservedBalance() (r decimal.Decimal, exists bool) { + v := m.addreserved_balance + if v == nil { + return + } + return *v, true } -// AccountIdentifier returns the value of the "account_identifier" field in the mutation. -func (m *ProviderFiatAccountMutation) AccountIdentifier() (r string, exists bool) { - v := m.account_identifier +// ResetReservedBalance resets all changes to the "reserved_balance" field. +func (m *ProviderBalancesMutation) ResetReservedBalance() { + m.reserved_balance = nil + m.addreserved_balance = nil +} + +// SetIsAvailable sets the "is_available" field. +func (m *ProviderBalancesMutation) SetIsAvailable(b bool) { + m.is_available = &b +} + +// IsAvailable returns the value of the "is_available" field in the mutation. +func (m *ProviderBalancesMutation) IsAvailable() (r bool, exists bool) { + v := m.is_available if v == nil { return } return *v, true } -// OldAccountIdentifier returns the old "account_identifier" field's value of the ProviderFiatAccount entity. -// If the ProviderFiatAccount object wasn't provided to the builder, the object is fetched from the database. +// OldIsAvailable returns the old "is_available" field's value of the ProviderBalances entity. +// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderFiatAccountMutation) OldAccountIdentifier(ctx context.Context) (v string, err error) { +func (m *ProviderBalancesMutation) OldIsAvailable(ctx context.Context) (v bool, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAccountIdentifier is only allowed on UpdateOne operations") + return v, errors.New("OldIsAvailable is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAccountIdentifier requires an ID field in the mutation") + return v, errors.New("OldIsAvailable requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldAccountIdentifier: %w", err) + return v, fmt.Errorf("querying old value for OldIsAvailable: %w", err) } - return oldValue.AccountIdentifier, nil + return oldValue.IsAvailable, nil } -// ResetAccountIdentifier resets all changes to the "account_identifier" field. -func (m *ProviderFiatAccountMutation) ResetAccountIdentifier() { - m.account_identifier = nil +// ResetIsAvailable resets all changes to the "is_available" field. +func (m *ProviderBalancesMutation) ResetIsAvailable() { + m.is_available = nil } -// SetAccountName sets the "account_name" field. -func (m *ProviderFiatAccountMutation) SetAccountName(s string) { - m.account_name = &s +// SetUpdatedAt sets the "updated_at" field. +func (m *ProviderBalancesMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// AccountName returns the value of the "account_name" field in the mutation. -func (m *ProviderFiatAccountMutation) AccountName() (r string, exists bool) { - v := m.account_name +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ProviderBalancesMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at if v == nil { return } return *v, true } -// OldAccountName returns the old "account_name" field's value of the ProviderFiatAccount entity. -// If the ProviderFiatAccount object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the ProviderBalances entity. +// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderFiatAccountMutation) OldAccountName(ctx context.Context) (v string, err error) { +func (m *ProviderBalancesMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAccountName is only allowed on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAccountName requires an ID field in the mutation") + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldAccountName: %w", err) + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - return oldValue.AccountName, nil + return oldValue.UpdatedAt, nil } -// ResetAccountName resets all changes to the "account_name" field. -func (m *ProviderFiatAccountMutation) ResetAccountName() { - m.account_name = nil +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *ProviderBalancesMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetPeakBalance sets the "peak_balance" field. +func (m *ProviderBalancesMutation) SetPeakBalance(d decimal.Decimal) { + m.peak_balance = &d + m.addpeak_balance = nil +} + +// PeakBalance returns the value of the "peak_balance" field in the mutation. +func (m *ProviderBalancesMutation) PeakBalance() (r decimal.Decimal, exists bool) { + v := m.peak_balance + if v == nil { + return + } + return *v, true +} + +// OldPeakBalance returns the old "peak_balance" field's value of the ProviderBalances entity. +// If the ProviderBalances object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderBalancesMutation) OldPeakBalance(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPeakBalance is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPeakBalance requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPeakBalance: %w", err) + } + return oldValue.PeakBalance, nil +} + +// AddPeakBalance adds d to the "peak_balance" field. +func (m *ProviderBalancesMutation) AddPeakBalance(d decimal.Decimal) { + if m.addpeak_balance != nil { + *m.addpeak_balance = m.addpeak_balance.Add(d) + } else { + m.addpeak_balance = &d + } +} + +// AddedPeakBalance returns the value that was added to the "peak_balance" field in this mutation. +func (m *ProviderBalancesMutation) AddedPeakBalance() (r decimal.Decimal, exists bool) { + v := m.addpeak_balance + if v == nil { + return + } + return *v, true +} + +// ResetPeakBalance resets all changes to the "peak_balance" field. +func (m *ProviderBalancesMutation) ResetPeakBalance() { + m.peak_balance = nil + m.addpeak_balance = nil } // SetProviderID sets the "provider" edge to the ProviderProfile entity by id. -func (m *ProviderFiatAccountMutation) SetProviderID(id string) { +func (m *ProviderBalancesMutation) SetProviderID(id string) { m.provider = &id } // ClearProvider clears the "provider" edge to the ProviderProfile entity. -func (m *ProviderFiatAccountMutation) ClearProvider() { +func (m *ProviderBalancesMutation) ClearProvider() { m.clearedprovider = true } // ProviderCleared reports if the "provider" edge to the ProviderProfile entity was cleared. -func (m *ProviderFiatAccountMutation) ProviderCleared() bool { +func (m *ProviderBalancesMutation) ProviderCleared() bool { return m.clearedprovider } // ProviderID returns the "provider" edge ID in the mutation. -func (m *ProviderFiatAccountMutation) ProviderID() (id string, exists bool) { +func (m *ProviderBalancesMutation) ProviderID() (id string, exists bool) { if m.provider != nil { return *m.provider, true } @@ -12678,7 +13216,7 @@ func (m *ProviderFiatAccountMutation) ProviderID() (id string, exists bool) { // ProviderIDs returns the "provider" edge IDs in the mutation. // Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // ProviderID instead. It exists only for internal usage by the builders. -func (m *ProviderFiatAccountMutation) ProviderIDs() (ids []string) { +func (m *ProviderBalancesMutation) ProviderIDs() (ids []string) { if id := m.provider; id != nil { ids = append(ids, *id) } @@ -12686,20 +13224,98 @@ func (m *ProviderFiatAccountMutation) ProviderIDs() (ids []string) { } // ResetProvider resets all changes to the "provider" edge. -func (m *ProviderFiatAccountMutation) ResetProvider() { +func (m *ProviderBalancesMutation) ResetProvider() { m.provider = nil m.clearedprovider = false } -// Where appends a list predicates to the ProviderFiatAccountMutation builder. -func (m *ProviderFiatAccountMutation) Where(ps ...predicate.ProviderFiatAccount) { - m.predicates = append(m.predicates, ps...) +// SetFiatCurrencyID sets the "fiat_currency" edge to the FiatCurrency entity by id. +func (m *ProviderBalancesMutation) SetFiatCurrencyID(id uuid.UUID) { + m.fiat_currency = &id } -// WhereP appends storage-level predicates to the ProviderFiatAccountMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *ProviderFiatAccountMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.ProviderFiatAccount, len(ps)) +// ClearFiatCurrency clears the "fiat_currency" edge to the FiatCurrency entity. +func (m *ProviderBalancesMutation) ClearFiatCurrency() { + m.clearedfiat_currency = true +} + +// FiatCurrencyCleared reports if the "fiat_currency" edge to the FiatCurrency entity was cleared. +func (m *ProviderBalancesMutation) FiatCurrencyCleared() bool { + return m.clearedfiat_currency +} + +// FiatCurrencyID returns the "fiat_currency" edge ID in the mutation. +func (m *ProviderBalancesMutation) FiatCurrencyID() (id uuid.UUID, exists bool) { + if m.fiat_currency != nil { + return *m.fiat_currency, true + } + return +} + +// FiatCurrencyIDs returns the "fiat_currency" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FiatCurrencyID instead. It exists only for internal usage by the builders. +func (m *ProviderBalancesMutation) FiatCurrencyIDs() (ids []uuid.UUID) { + if id := m.fiat_currency; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFiatCurrency resets all changes to the "fiat_currency" edge. +func (m *ProviderBalancesMutation) ResetFiatCurrency() { + m.fiat_currency = nil + m.clearedfiat_currency = false +} + +// SetTokenID sets the "token" edge to the Token entity by id. +func (m *ProviderBalancesMutation) SetTokenID(id int) { + m.token = &id +} + +// ClearToken clears the "token" edge to the Token entity. +func (m *ProviderBalancesMutation) ClearToken() { + m.clearedtoken = true +} + +// TokenCleared reports if the "token" edge to the Token entity was cleared. +func (m *ProviderBalancesMutation) TokenCleared() bool { + return m.clearedtoken +} + +// TokenID returns the "token" edge ID in the mutation. +func (m *ProviderBalancesMutation) TokenID() (id int, exists bool) { + if m.token != nil { + return *m.token, true + } + return +} + +// TokenIDs returns the "token" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TokenID instead. It exists only for internal usage by the builders. +func (m *ProviderBalancesMutation) TokenIDs() (ids []int) { + if id := m.token; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetToken resets all changes to the "token" edge. +func (m *ProviderBalancesMutation) ResetToken() { + m.token = nil + m.clearedtoken = false +} + +// Where appends a list predicates to the ProviderBalancesMutation builder. +func (m *ProviderBalancesMutation) Where(ps ...predicate.ProviderBalances) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ProviderBalancesMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ProviderBalancesMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ProviderBalances, len(ps)) for i := range ps { p[i] = ps[i] } @@ -12707,39 +13323,42 @@ func (m *ProviderFiatAccountMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *ProviderFiatAccountMutation) Op() Op { +func (m *ProviderBalancesMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *ProviderFiatAccountMutation) SetOp(op Op) { +func (m *ProviderBalancesMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (ProviderFiatAccount). -func (m *ProviderFiatAccountMutation) Type() string { +// Type returns the node type of this mutation (ProviderBalances). +func (m *ProviderBalancesMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *ProviderFiatAccountMutation) Fields() []string { - fields := make([]string, 0, 5) - if m.created_at != nil { - fields = append(fields, providerfiataccount.FieldCreatedAt) +func (m *ProviderBalancesMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.available_balance != nil { + fields = append(fields, providerbalances.FieldAvailableBalance) } - if m.updated_at != nil { - fields = append(fields, providerfiataccount.FieldUpdatedAt) + if m.total_balance != nil { + fields = append(fields, providerbalances.FieldTotalBalance) } - if m.institution != nil { - fields = append(fields, providerfiataccount.FieldInstitution) + if m.reserved_balance != nil { + fields = append(fields, providerbalances.FieldReservedBalance) } - if m.account_identifier != nil { - fields = append(fields, providerfiataccount.FieldAccountIdentifier) + if m.is_available != nil { + fields = append(fields, providerbalances.FieldIsAvailable) } - if m.account_name != nil { - fields = append(fields, providerfiataccount.FieldAccountName) + if m.updated_at != nil { + fields = append(fields, providerbalances.FieldUpdatedAt) + } + if m.peak_balance != nil { + fields = append(fields, providerbalances.FieldPeakBalance) } return fields } @@ -12747,18 +13366,20 @@ func (m *ProviderFiatAccountMutation) Fields() []string { // Field returns the value of a field with the given name. The second boolean // return value indicates that this field was not set, or was not defined in the // schema. -func (m *ProviderFiatAccountMutation) Field(name string) (ent.Value, bool) { +func (m *ProviderBalancesMutation) Field(name string) (ent.Value, bool) { switch name { - case providerfiataccount.FieldCreatedAt: - return m.CreatedAt() - case providerfiataccount.FieldUpdatedAt: + case providerbalances.FieldAvailableBalance: + return m.AvailableBalance() + case providerbalances.FieldTotalBalance: + return m.TotalBalance() + case providerbalances.FieldReservedBalance: + return m.ReservedBalance() + case providerbalances.FieldIsAvailable: + return m.IsAvailable() + case providerbalances.FieldUpdatedAt: return m.UpdatedAt() - case providerfiataccount.FieldInstitution: - return m.Institution() - case providerfiataccount.FieldAccountIdentifier: - return m.AccountIdentifier() - case providerfiataccount.FieldAccountName: - return m.AccountName() + case providerbalances.FieldPeakBalance: + return m.PeakBalance() } return nil, false } @@ -12766,256 +13387,333 @@ func (m *ProviderFiatAccountMutation) Field(name string) (ent.Value, bool) { // OldField returns the old value of the field from the database. An error is // returned if the mutation operation is not UpdateOne, or the query to the // database failed. -func (m *ProviderFiatAccountMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *ProviderBalancesMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case providerfiataccount.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case providerfiataccount.FieldUpdatedAt: + case providerbalances.FieldAvailableBalance: + return m.OldAvailableBalance(ctx) + case providerbalances.FieldTotalBalance: + return m.OldTotalBalance(ctx) + case providerbalances.FieldReservedBalance: + return m.OldReservedBalance(ctx) + case providerbalances.FieldIsAvailable: + return m.OldIsAvailable(ctx) + case providerbalances.FieldUpdatedAt: return m.OldUpdatedAt(ctx) - case providerfiataccount.FieldInstitution: - return m.OldInstitution(ctx) - case providerfiataccount.FieldAccountIdentifier: - return m.OldAccountIdentifier(ctx) - case providerfiataccount.FieldAccountName: - return m.OldAccountName(ctx) + case providerbalances.FieldPeakBalance: + return m.OldPeakBalance(ctx) } - return nil, fmt.Errorf("unknown ProviderFiatAccount field %s", name) + return nil, fmt.Errorf("unknown ProviderBalances field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *ProviderFiatAccountMutation) SetField(name string, value ent.Value) error { +func (m *ProviderBalancesMutation) SetField(name string, value ent.Value) error { switch name { - case providerfiataccount.FieldCreatedAt: - v, ok := value.(time.Time) + case providerbalances.FieldAvailableBalance: + v, ok := value.(decimal.Decimal) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCreatedAt(v) + m.SetAvailableBalance(v) return nil - case providerfiataccount.FieldUpdatedAt: - v, ok := value.(time.Time) + case providerbalances.FieldTotalBalance: + v, ok := value.(decimal.Decimal) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetUpdatedAt(v) + m.SetTotalBalance(v) return nil - case providerfiataccount.FieldInstitution: - v, ok := value.(string) + case providerbalances.FieldReservedBalance: + v, ok := value.(decimal.Decimal) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetInstitution(v) + m.SetReservedBalance(v) return nil - case providerfiataccount.FieldAccountIdentifier: - v, ok := value.(string) + case providerbalances.FieldIsAvailable: + v, ok := value.(bool) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetAccountIdentifier(v) + m.SetIsAvailable(v) return nil - case providerfiataccount.FieldAccountName: - v, ok := value.(string) + case providerbalances.FieldUpdatedAt: + v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetAccountName(v) + m.SetUpdatedAt(v) + return nil + case providerbalances.FieldPeakBalance: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPeakBalance(v) return nil } - return fmt.Errorf("unknown ProviderFiatAccount field %s", name) + return fmt.Errorf("unknown ProviderBalances field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *ProviderFiatAccountMutation) AddedFields() []string { - return nil +func (m *ProviderBalancesMutation) AddedFields() []string { + var fields []string + if m.addavailable_balance != nil { + fields = append(fields, providerbalances.FieldAvailableBalance) + } + if m.addtotal_balance != nil { + fields = append(fields, providerbalances.FieldTotalBalance) + } + if m.addreserved_balance != nil { + fields = append(fields, providerbalances.FieldReservedBalance) + } + if m.addpeak_balance != nil { + fields = append(fields, providerbalances.FieldPeakBalance) + } + return fields } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *ProviderFiatAccountMutation) AddedField(name string) (ent.Value, bool) { +func (m *ProviderBalancesMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case providerbalances.FieldAvailableBalance: + return m.AddedAvailableBalance() + case providerbalances.FieldTotalBalance: + return m.AddedTotalBalance() + case providerbalances.FieldReservedBalance: + return m.AddedReservedBalance() + case providerbalances.FieldPeakBalance: + return m.AddedPeakBalance() + } return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *ProviderFiatAccountMutation) AddField(name string, value ent.Value) error { +func (m *ProviderBalancesMutation) AddField(name string, value ent.Value) error { switch name { - } - return fmt.Errorf("unknown ProviderFiatAccount numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *ProviderFiatAccountMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *ProviderFiatAccountMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *ProviderFiatAccountMutation) ClearField(name string) error { - return fmt.Errorf("unknown ProviderFiatAccount nullable field %s", name) + case providerbalances.FieldAvailableBalance: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddAvailableBalance(v) + return nil + case providerbalances.FieldTotalBalance: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTotalBalance(v) + return nil + case providerbalances.FieldReservedBalance: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddReservedBalance(v) + return nil + case providerbalances.FieldPeakBalance: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPeakBalance(v) + return nil + } + return fmt.Errorf("unknown ProviderBalances numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ProviderBalancesMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ProviderBalancesMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *ProviderBalancesMutation) ClearField(name string) error { + return fmt.Errorf("unknown ProviderBalances nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *ProviderFiatAccountMutation) ResetField(name string) error { +func (m *ProviderBalancesMutation) ResetField(name string) error { switch name { - case providerfiataccount.FieldCreatedAt: - m.ResetCreatedAt() + case providerbalances.FieldAvailableBalance: + m.ResetAvailableBalance() return nil - case providerfiataccount.FieldUpdatedAt: - m.ResetUpdatedAt() + case providerbalances.FieldTotalBalance: + m.ResetTotalBalance() return nil - case providerfiataccount.FieldInstitution: - m.ResetInstitution() + case providerbalances.FieldReservedBalance: + m.ResetReservedBalance() return nil - case providerfiataccount.FieldAccountIdentifier: - m.ResetAccountIdentifier() + case providerbalances.FieldIsAvailable: + m.ResetIsAvailable() return nil - case providerfiataccount.FieldAccountName: - m.ResetAccountName() + case providerbalances.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case providerbalances.FieldPeakBalance: + m.ResetPeakBalance() return nil } - return fmt.Errorf("unknown ProviderFiatAccount field %s", name) + return fmt.Errorf("unknown ProviderBalances field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *ProviderFiatAccountMutation) AddedEdges() []string { - edges := make([]string, 0, 1) +func (m *ProviderBalancesMutation) AddedEdges() []string { + edges := make([]string, 0, 3) if m.provider != nil { - edges = append(edges, providerfiataccount.EdgeProvider) + edges = append(edges, providerbalances.EdgeProvider) + } + if m.fiat_currency != nil { + edges = append(edges, providerbalances.EdgeFiatCurrency) + } + if m.token != nil { + edges = append(edges, providerbalances.EdgeToken) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *ProviderFiatAccountMutation) AddedIDs(name string) []ent.Value { +func (m *ProviderBalancesMutation) AddedIDs(name string) []ent.Value { switch name { - case providerfiataccount.EdgeProvider: + case providerbalances.EdgeProvider: if id := m.provider; id != nil { return []ent.Value{*id} } + case providerbalances.EdgeFiatCurrency: + if id := m.fiat_currency; id != nil { + return []ent.Value{*id} + } + case providerbalances.EdgeToken: + if id := m.token; id != nil { + return []ent.Value{*id} + } } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *ProviderFiatAccountMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) +func (m *ProviderBalancesMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *ProviderFiatAccountMutation) RemovedIDs(name string) []ent.Value { +func (m *ProviderBalancesMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *ProviderFiatAccountMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) +func (m *ProviderBalancesMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) if m.clearedprovider { - edges = append(edges, providerfiataccount.EdgeProvider) + edges = append(edges, providerbalances.EdgeProvider) + } + if m.clearedfiat_currency { + edges = append(edges, providerbalances.EdgeFiatCurrency) + } + if m.clearedtoken { + edges = append(edges, providerbalances.EdgeToken) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *ProviderFiatAccountMutation) EdgeCleared(name string) bool { +func (m *ProviderBalancesMutation) EdgeCleared(name string) bool { switch name { - case providerfiataccount.EdgeProvider: + case providerbalances.EdgeProvider: return m.clearedprovider + case providerbalances.EdgeFiatCurrency: + return m.clearedfiat_currency + case providerbalances.EdgeToken: + return m.clearedtoken } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *ProviderFiatAccountMutation) ClearEdge(name string) error { +func (m *ProviderBalancesMutation) ClearEdge(name string) error { switch name { - case providerfiataccount.EdgeProvider: + case providerbalances.EdgeProvider: m.ClearProvider() return nil + case providerbalances.EdgeFiatCurrency: + m.ClearFiatCurrency() + return nil + case providerbalances.EdgeToken: + m.ClearToken() + return nil } - return fmt.Errorf("unknown ProviderFiatAccount unique edge %s", name) + return fmt.Errorf("unknown ProviderBalances unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *ProviderFiatAccountMutation) ResetEdge(name string) error { +func (m *ProviderBalancesMutation) ResetEdge(name string) error { switch name { - case providerfiataccount.EdgeProvider: + case providerbalances.EdgeProvider: m.ResetProvider() return nil + case providerbalances.EdgeFiatCurrency: + m.ResetFiatCurrency() + return nil + case providerbalances.EdgeToken: + m.ResetToken() + return nil } - return fmt.Errorf("unknown ProviderFiatAccount edge %s", name) + return fmt.Errorf("unknown ProviderBalances edge %s", name) } -// ProviderOrderTokenMutation represents an operation that mutates the ProviderOrderToken nodes in the graph. -type ProviderOrderTokenMutation struct { +// ProviderFiatAccountMutation represents an operation that mutates the ProviderFiatAccount nodes in the graph. +type ProviderFiatAccountMutation struct { config - op Op - typ string - id *int - created_at *time.Time - updated_at *time.Time - fixed_buy_rate *decimal.Decimal - addfixed_buy_rate *decimal.Decimal - fixed_sell_rate *decimal.Decimal - addfixed_sell_rate *decimal.Decimal - floating_buy_delta *decimal.Decimal - addfloating_buy_delta *decimal.Decimal - floating_sell_delta *decimal.Decimal - addfloating_sell_delta *decimal.Decimal - max_order_amount *decimal.Decimal - addmax_order_amount *decimal.Decimal - min_order_amount *decimal.Decimal - addmin_order_amount *decimal.Decimal - max_order_amount_otc *decimal.Decimal - addmax_order_amount_otc *decimal.Decimal - min_order_amount_otc *decimal.Decimal - addmin_order_amount_otc *decimal.Decimal - rate_slippage *decimal.Decimal - addrate_slippage *decimal.Decimal - settlement_address *string - payout_address *string - network *string - clearedFields map[string]struct{} - provider *string - clearedprovider bool - token *int - clearedtoken bool - currency *uuid.UUID - clearedcurrency bool - done bool - oldValue func(context.Context) (*ProviderOrderToken, error) - predicates []predicate.ProviderOrderToken + op Op + typ string + id *uuid.UUID + created_at *time.Time + updated_at *time.Time + institution *string + account_identifier *string + account_name *string + clearedFields map[string]struct{} + provider *string + clearedprovider bool + done bool + oldValue func(context.Context) (*ProviderFiatAccount, error) + predicates []predicate.ProviderFiatAccount } -var _ ent.Mutation = (*ProviderOrderTokenMutation)(nil) +var _ ent.Mutation = (*ProviderFiatAccountMutation)(nil) -// providerordertokenOption allows management of the mutation configuration using functional options. -type providerordertokenOption func(*ProviderOrderTokenMutation) +// providerfiataccountOption allows management of the mutation configuration using functional options. +type providerfiataccountOption func(*ProviderFiatAccountMutation) -// newProviderOrderTokenMutation creates new mutation for the ProviderOrderToken entity. -func newProviderOrderTokenMutation(c config, op Op, opts ...providerordertokenOption) *ProviderOrderTokenMutation { - m := &ProviderOrderTokenMutation{ +// newProviderFiatAccountMutation creates new mutation for the ProviderFiatAccount entity. +func newProviderFiatAccountMutation(c config, op Op, opts ...providerfiataccountOption) *ProviderFiatAccountMutation { + m := &ProviderFiatAccountMutation{ config: c, op: op, - typ: TypeProviderOrderToken, + typ: TypeProviderFiatAccount, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -13024,20 +13722,20 @@ func newProviderOrderTokenMutation(c config, op Op, opts ...providerordertokenOp return m } -// withProviderOrderTokenID sets the ID field of the mutation. -func withProviderOrderTokenID(id int) providerordertokenOption { - return func(m *ProviderOrderTokenMutation) { +// withProviderFiatAccountID sets the ID field of the mutation. +func withProviderFiatAccountID(id uuid.UUID) providerfiataccountOption { + return func(m *ProviderFiatAccountMutation) { var ( err error once sync.Once - value *ProviderOrderToken + value *ProviderFiatAccount ) - m.oldValue = func(ctx context.Context) (*ProviderOrderToken, error) { + m.oldValue = func(ctx context.Context) (*ProviderFiatAccount, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().ProviderOrderToken.Get(ctx, id) + value, err = m.Client().ProviderFiatAccount.Get(ctx, id) } }) return value, err @@ -13046,10 +13744,10 @@ func withProviderOrderTokenID(id int) providerordertokenOption { } } -// withProviderOrderToken sets the old ProviderOrderToken of the mutation. -func withProviderOrderToken(node *ProviderOrderToken) providerordertokenOption { - return func(m *ProviderOrderTokenMutation) { - m.oldValue = func(context.Context) (*ProviderOrderToken, error) { +// withProviderFiatAccount sets the old ProviderFiatAccount of the mutation. +func withProviderFiatAccount(node *ProviderFiatAccount) providerfiataccountOption { + return func(m *ProviderFiatAccountMutation) { + m.oldValue = func(context.Context) (*ProviderFiatAccount, error) { return node, nil } m.id = &node.ID @@ -13058,7 +13756,7 @@ func withProviderOrderToken(node *ProviderOrderToken) providerordertokenOption { // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. -func (m ProviderOrderTokenMutation) Client() *Client { +func (m ProviderFiatAccountMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -13066,7 +13764,7 @@ func (m ProviderOrderTokenMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m ProviderOrderTokenMutation) Tx() (*Tx, error) { +func (m ProviderFiatAccountMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("ent: mutation is not running in a transaction") } @@ -13075,9 +13773,15 @@ func (m ProviderOrderTokenMutation) Tx() (*Tx, error) { return tx, nil } +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of ProviderFiatAccount entities. +func (m *ProviderFiatAccountMutation) SetID(id uuid.UUID) { + m.id = &id +} + // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *ProviderOrderTokenMutation) ID() (id int, exists bool) { +func (m *ProviderFiatAccountMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -13088,28 +13792,28 @@ func (m *ProviderOrderTokenMutation) ID() (id int, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *ProviderOrderTokenMutation) IDs(ctx context.Context) ([]int, error) { +func (m *ProviderFiatAccountMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() if exists { - return []int{id}, nil + return []uuid.UUID{id}, nil } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().ProviderOrderToken.Query().Where(m.predicates...).IDs(ctx) + return m.Client().ProviderFiatAccount.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } // SetCreatedAt sets the "created_at" field. -func (m *ProviderOrderTokenMutation) SetCreatedAt(t time.Time) { +func (m *ProviderFiatAccountMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *ProviderOrderTokenMutation) CreatedAt() (r time.Time, exists bool) { +func (m *ProviderFiatAccountMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -13117,10 +13821,10 @@ func (m *ProviderOrderTokenMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the ProviderFiatAccount entity. +// If the ProviderFiatAccount object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ProviderFiatAccountMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } @@ -13135,17 +13839,17 @@ func (m *ProviderOrderTokenMutation) OldCreatedAt(ctx context.Context) (v time.T } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *ProviderOrderTokenMutation) ResetCreatedAt() { +func (m *ProviderFiatAccountMutation) ResetCreatedAt() { m.created_at = nil } // SetUpdatedAt sets the "updated_at" field. -func (m *ProviderOrderTokenMutation) SetUpdatedAt(t time.Time) { +func (m *ProviderFiatAccountMutation) SetUpdatedAt(t time.Time) { m.updated_at = &t } // UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *ProviderOrderTokenMutation) UpdatedAt() (r time.Time, exists bool) { +func (m *ProviderFiatAccountMutation) UpdatedAt() (r time.Time, exists bool) { v := m.updated_at if v == nil { return @@ -13153,10 +13857,10 @@ func (m *ProviderOrderTokenMutation) UpdatedAt() (r time.Time, exists bool) { return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the ProviderFiatAccount entity. +// If the ProviderFiatAccount object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ProviderFiatAccountMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } @@ -13171,830 +13875,2768 @@ func (m *ProviderOrderTokenMutation) OldUpdatedAt(ctx context.Context) (v time.T } // ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *ProviderOrderTokenMutation) ResetUpdatedAt() { +func (m *ProviderFiatAccountMutation) ResetUpdatedAt() { m.updated_at = nil } -// SetFixedBuyRate sets the "fixed_buy_rate" field. -func (m *ProviderOrderTokenMutation) SetFixedBuyRate(d decimal.Decimal) { - m.fixed_buy_rate = &d - m.addfixed_buy_rate = nil +// SetInstitution sets the "institution" field. +func (m *ProviderFiatAccountMutation) SetInstitution(s string) { + m.institution = &s } -// FixedBuyRate returns the value of the "fixed_buy_rate" field in the mutation. -func (m *ProviderOrderTokenMutation) FixedBuyRate() (r decimal.Decimal, exists bool) { - v := m.fixed_buy_rate +// Institution returns the value of the "institution" field in the mutation. +func (m *ProviderFiatAccountMutation) Institution() (r string, exists bool) { + v := m.institution if v == nil { return } return *v, true } -// OldFixedBuyRate returns the old "fixed_buy_rate" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// OldInstitution returns the old "institution" field's value of the ProviderFiatAccount entity. +// If the ProviderFiatAccount object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldFixedBuyRate(ctx context.Context) (v decimal.Decimal, err error) { +func (m *ProviderFiatAccountMutation) OldInstitution(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldFixedBuyRate is only allowed on UpdateOne operations") + return v, errors.New("OldInstitution is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldFixedBuyRate requires an ID field in the mutation") + return v, errors.New("OldInstitution requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldFixedBuyRate: %w", err) - } - return oldValue.FixedBuyRate, nil -} - -// AddFixedBuyRate adds d to the "fixed_buy_rate" field. -func (m *ProviderOrderTokenMutation) AddFixedBuyRate(d decimal.Decimal) { - if m.addfixed_buy_rate != nil { - *m.addfixed_buy_rate = m.addfixed_buy_rate.Add(d) - } else { - m.addfixed_buy_rate = &d - } -} - -// AddedFixedBuyRate returns the value that was added to the "fixed_buy_rate" field in this mutation. -func (m *ProviderOrderTokenMutation) AddedFixedBuyRate() (r decimal.Decimal, exists bool) { - v := m.addfixed_buy_rate - if v == nil { - return + return v, fmt.Errorf("querying old value for OldInstitution: %w", err) } - return *v, true -} - -// ClearFixedBuyRate clears the value of the "fixed_buy_rate" field. -func (m *ProviderOrderTokenMutation) ClearFixedBuyRate() { - m.fixed_buy_rate = nil - m.addfixed_buy_rate = nil - m.clearedFields[providerordertoken.FieldFixedBuyRate] = struct{}{} -} - -// FixedBuyRateCleared returns if the "fixed_buy_rate" field was cleared in this mutation. -func (m *ProviderOrderTokenMutation) FixedBuyRateCleared() bool { - _, ok := m.clearedFields[providerordertoken.FieldFixedBuyRate] - return ok + return oldValue.Institution, nil } -// ResetFixedBuyRate resets all changes to the "fixed_buy_rate" field. -func (m *ProviderOrderTokenMutation) ResetFixedBuyRate() { - m.fixed_buy_rate = nil - m.addfixed_buy_rate = nil - delete(m.clearedFields, providerordertoken.FieldFixedBuyRate) +// ResetInstitution resets all changes to the "institution" field. +func (m *ProviderFiatAccountMutation) ResetInstitution() { + m.institution = nil } -// SetFixedSellRate sets the "fixed_sell_rate" field. -func (m *ProviderOrderTokenMutation) SetFixedSellRate(d decimal.Decimal) { - m.fixed_sell_rate = &d - m.addfixed_sell_rate = nil +// SetAccountIdentifier sets the "account_identifier" field. +func (m *ProviderFiatAccountMutation) SetAccountIdentifier(s string) { + m.account_identifier = &s } -// FixedSellRate returns the value of the "fixed_sell_rate" field in the mutation. -func (m *ProviderOrderTokenMutation) FixedSellRate() (r decimal.Decimal, exists bool) { - v := m.fixed_sell_rate +// AccountIdentifier returns the value of the "account_identifier" field in the mutation. +func (m *ProviderFiatAccountMutation) AccountIdentifier() (r string, exists bool) { + v := m.account_identifier if v == nil { return } return *v, true } -// OldFixedSellRate returns the old "fixed_sell_rate" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// OldAccountIdentifier returns the old "account_identifier" field's value of the ProviderFiatAccount entity. +// If the ProviderFiatAccount object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldFixedSellRate(ctx context.Context) (v decimal.Decimal, err error) { +func (m *ProviderFiatAccountMutation) OldAccountIdentifier(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldFixedSellRate is only allowed on UpdateOne operations") + return v, errors.New("OldAccountIdentifier is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldFixedSellRate requires an ID field in the mutation") + return v, errors.New("OldAccountIdentifier requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldFixedSellRate: %w", err) - } - return oldValue.FixedSellRate, nil -} - -// AddFixedSellRate adds d to the "fixed_sell_rate" field. -func (m *ProviderOrderTokenMutation) AddFixedSellRate(d decimal.Decimal) { - if m.addfixed_sell_rate != nil { - *m.addfixed_sell_rate = m.addfixed_sell_rate.Add(d) - } else { - m.addfixed_sell_rate = &d - } -} - -// AddedFixedSellRate returns the value that was added to the "fixed_sell_rate" field in this mutation. -func (m *ProviderOrderTokenMutation) AddedFixedSellRate() (r decimal.Decimal, exists bool) { - v := m.addfixed_sell_rate - if v == nil { - return + return v, fmt.Errorf("querying old value for OldAccountIdentifier: %w", err) } - return *v, true -} - -// ClearFixedSellRate clears the value of the "fixed_sell_rate" field. -func (m *ProviderOrderTokenMutation) ClearFixedSellRate() { - m.fixed_sell_rate = nil - m.addfixed_sell_rate = nil - m.clearedFields[providerordertoken.FieldFixedSellRate] = struct{}{} -} - -// FixedSellRateCleared returns if the "fixed_sell_rate" field was cleared in this mutation. -func (m *ProviderOrderTokenMutation) FixedSellRateCleared() bool { - _, ok := m.clearedFields[providerordertoken.FieldFixedSellRate] - return ok + return oldValue.AccountIdentifier, nil } -// ResetFixedSellRate resets all changes to the "fixed_sell_rate" field. -func (m *ProviderOrderTokenMutation) ResetFixedSellRate() { - m.fixed_sell_rate = nil - m.addfixed_sell_rate = nil - delete(m.clearedFields, providerordertoken.FieldFixedSellRate) +// ResetAccountIdentifier resets all changes to the "account_identifier" field. +func (m *ProviderFiatAccountMutation) ResetAccountIdentifier() { + m.account_identifier = nil } -// SetFloatingBuyDelta sets the "floating_buy_delta" field. -func (m *ProviderOrderTokenMutation) SetFloatingBuyDelta(d decimal.Decimal) { - m.floating_buy_delta = &d - m.addfloating_buy_delta = nil +// SetAccountName sets the "account_name" field. +func (m *ProviderFiatAccountMutation) SetAccountName(s string) { + m.account_name = &s } -// FloatingBuyDelta returns the value of the "floating_buy_delta" field in the mutation. -func (m *ProviderOrderTokenMutation) FloatingBuyDelta() (r decimal.Decimal, exists bool) { - v := m.floating_buy_delta +// AccountName returns the value of the "account_name" field in the mutation. +func (m *ProviderFiatAccountMutation) AccountName() (r string, exists bool) { + v := m.account_name if v == nil { return } return *v, true } -// OldFloatingBuyDelta returns the old "floating_buy_delta" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// OldAccountName returns the old "account_name" field's value of the ProviderFiatAccount entity. +// If the ProviderFiatAccount object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldFloatingBuyDelta(ctx context.Context) (v decimal.Decimal, err error) { +func (m *ProviderFiatAccountMutation) OldAccountName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldFloatingBuyDelta is only allowed on UpdateOne operations") + return v, errors.New("OldAccountName is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldFloatingBuyDelta requires an ID field in the mutation") + return v, errors.New("OldAccountName requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldFloatingBuyDelta: %w", err) + return v, fmt.Errorf("querying old value for OldAccountName: %w", err) } - return oldValue.FloatingBuyDelta, nil + return oldValue.AccountName, nil } -// AddFloatingBuyDelta adds d to the "floating_buy_delta" field. -func (m *ProviderOrderTokenMutation) AddFloatingBuyDelta(d decimal.Decimal) { - if m.addfloating_buy_delta != nil { - *m.addfloating_buy_delta = m.addfloating_buy_delta.Add(d) - } else { - m.addfloating_buy_delta = &d - } +// ResetAccountName resets all changes to the "account_name" field. +func (m *ProviderFiatAccountMutation) ResetAccountName() { + m.account_name = nil } -// AddedFloatingBuyDelta returns the value that was added to the "floating_buy_delta" field in this mutation. -func (m *ProviderOrderTokenMutation) AddedFloatingBuyDelta() (r decimal.Decimal, exists bool) { - v := m.addfloating_buy_delta - if v == nil { - return - } - return *v, true +// SetProviderID sets the "provider" edge to the ProviderProfile entity by id. +func (m *ProviderFiatAccountMutation) SetProviderID(id string) { + m.provider = &id } -// ClearFloatingBuyDelta clears the value of the "floating_buy_delta" field. -func (m *ProviderOrderTokenMutation) ClearFloatingBuyDelta() { - m.floating_buy_delta = nil - m.addfloating_buy_delta = nil - m.clearedFields[providerordertoken.FieldFloatingBuyDelta] = struct{}{} +// ClearProvider clears the "provider" edge to the ProviderProfile entity. +func (m *ProviderFiatAccountMutation) ClearProvider() { + m.clearedprovider = true } -// FloatingBuyDeltaCleared returns if the "floating_buy_delta" field was cleared in this mutation. -func (m *ProviderOrderTokenMutation) FloatingBuyDeltaCleared() bool { - _, ok := m.clearedFields[providerordertoken.FieldFloatingBuyDelta] - return ok +// ProviderCleared reports if the "provider" edge to the ProviderProfile entity was cleared. +func (m *ProviderFiatAccountMutation) ProviderCleared() bool { + return m.clearedprovider } -// ResetFloatingBuyDelta resets all changes to the "floating_buy_delta" field. -func (m *ProviderOrderTokenMutation) ResetFloatingBuyDelta() { - m.floating_buy_delta = nil - m.addfloating_buy_delta = nil - delete(m.clearedFields, providerordertoken.FieldFloatingBuyDelta) +// ProviderID returns the "provider" edge ID in the mutation. +func (m *ProviderFiatAccountMutation) ProviderID() (id string, exists bool) { + if m.provider != nil { + return *m.provider, true + } + return } -// SetFloatingSellDelta sets the "floating_sell_delta" field. -func (m *ProviderOrderTokenMutation) SetFloatingSellDelta(d decimal.Decimal) { - m.floating_sell_delta = &d - m.addfloating_sell_delta = nil +// ProviderIDs returns the "provider" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ProviderID instead. It exists only for internal usage by the builders. +func (m *ProviderFiatAccountMutation) ProviderIDs() (ids []string) { + if id := m.provider; id != nil { + ids = append(ids, *id) + } + return } -// FloatingSellDelta returns the value of the "floating_sell_delta" field in the mutation. -func (m *ProviderOrderTokenMutation) FloatingSellDelta() (r decimal.Decimal, exists bool) { - v := m.floating_sell_delta - if v == nil { - return - } - return *v, true +// ResetProvider resets all changes to the "provider" edge. +func (m *ProviderFiatAccountMutation) ResetProvider() { + m.provider = nil + m.clearedprovider = false } -// OldFloatingSellDelta returns the old "floating_sell_delta" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldFloatingSellDelta(ctx context.Context) (v decimal.Decimal, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldFloatingSellDelta is only allowed on UpdateOne operations") +// Where appends a list predicates to the ProviderFiatAccountMutation builder. +func (m *ProviderFiatAccountMutation) Where(ps ...predicate.ProviderFiatAccount) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ProviderFiatAccountMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ProviderFiatAccountMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ProviderFiatAccount, len(ps)) + for i := range ps { + p[i] = ps[i] } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldFloatingSellDelta requires an ID field in the mutation") + m.Where(p...) +} + +// Op returns the operation name. +func (m *ProviderFiatAccountMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ProviderFiatAccountMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ProviderFiatAccount). +func (m *ProviderFiatAccountMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *ProviderFiatAccountMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.created_at != nil { + fields = append(fields, providerfiataccount.FieldCreatedAt) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldFloatingSellDelta: %w", err) + if m.updated_at != nil { + fields = append(fields, providerfiataccount.FieldUpdatedAt) } - return oldValue.FloatingSellDelta, nil + if m.institution != nil { + fields = append(fields, providerfiataccount.FieldInstitution) + } + if m.account_identifier != nil { + fields = append(fields, providerfiataccount.FieldAccountIdentifier) + } + if m.account_name != nil { + fields = append(fields, providerfiataccount.FieldAccountName) + } + return fields } -// AddFloatingSellDelta adds d to the "floating_sell_delta" field. -func (m *ProviderOrderTokenMutation) AddFloatingSellDelta(d decimal.Decimal) { - if m.addfloating_sell_delta != nil { - *m.addfloating_sell_delta = m.addfloating_sell_delta.Add(d) - } else { - m.addfloating_sell_delta = &d +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *ProviderFiatAccountMutation) Field(name string) (ent.Value, bool) { + switch name { + case providerfiataccount.FieldCreatedAt: + return m.CreatedAt() + case providerfiataccount.FieldUpdatedAt: + return m.UpdatedAt() + case providerfiataccount.FieldInstitution: + return m.Institution() + case providerfiataccount.FieldAccountIdentifier: + return m.AccountIdentifier() + case providerfiataccount.FieldAccountName: + return m.AccountName() } + return nil, false } -// AddedFloatingSellDelta returns the value that was added to the "floating_sell_delta" field in this mutation. -func (m *ProviderOrderTokenMutation) AddedFloatingSellDelta() (r decimal.Decimal, exists bool) { - v := m.addfloating_sell_delta - if v == nil { - return +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *ProviderFiatAccountMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case providerfiataccount.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case providerfiataccount.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case providerfiataccount.FieldInstitution: + return m.OldInstitution(ctx) + case providerfiataccount.FieldAccountIdentifier: + return m.OldAccountIdentifier(ctx) + case providerfiataccount.FieldAccountName: + return m.OldAccountName(ctx) } - return *v, true + return nil, fmt.Errorf("unknown ProviderFiatAccount field %s", name) } -// ClearFloatingSellDelta clears the value of the "floating_sell_delta" field. -func (m *ProviderOrderTokenMutation) ClearFloatingSellDelta() { - m.floating_sell_delta = nil - m.addfloating_sell_delta = nil - m.clearedFields[providerordertoken.FieldFloatingSellDelta] = struct{}{} +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ProviderFiatAccountMutation) SetField(name string, value ent.Value) error { + switch name { + case providerfiataccount.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case providerfiataccount.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case providerfiataccount.FieldInstitution: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInstitution(v) + return nil + case providerfiataccount.FieldAccountIdentifier: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAccountIdentifier(v) + return nil + case providerfiataccount.FieldAccountName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAccountName(v) + return nil + } + return fmt.Errorf("unknown ProviderFiatAccount field %s", name) } -// FloatingSellDeltaCleared returns if the "floating_sell_delta" field was cleared in this mutation. -func (m *ProviderOrderTokenMutation) FloatingSellDeltaCleared() bool { - _, ok := m.clearedFields[providerordertoken.FieldFloatingSellDelta] +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ProviderFiatAccountMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *ProviderFiatAccountMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ProviderFiatAccountMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ProviderFiatAccount numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ProviderFiatAccountMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ProviderFiatAccountMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] return ok } -// ResetFloatingSellDelta resets all changes to the "floating_sell_delta" field. -func (m *ProviderOrderTokenMutation) ResetFloatingSellDelta() { - m.floating_sell_delta = nil - m.addfloating_sell_delta = nil - delete(m.clearedFields, providerordertoken.FieldFloatingSellDelta) +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *ProviderFiatAccountMutation) ClearField(name string) error { + return fmt.Errorf("unknown ProviderFiatAccount nullable field %s", name) } -// SetMaxOrderAmount sets the "max_order_amount" field. -func (m *ProviderOrderTokenMutation) SetMaxOrderAmount(d decimal.Decimal) { - m.max_order_amount = &d - m.addmax_order_amount = nil +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *ProviderFiatAccountMutation) ResetField(name string) error { + switch name { + case providerfiataccount.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case providerfiataccount.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case providerfiataccount.FieldInstitution: + m.ResetInstitution() + return nil + case providerfiataccount.FieldAccountIdentifier: + m.ResetAccountIdentifier() + return nil + case providerfiataccount.FieldAccountName: + m.ResetAccountName() + return nil + } + return fmt.Errorf("unknown ProviderFiatAccount field %s", name) } -// MaxOrderAmount returns the value of the "max_order_amount" field in the mutation. -func (m *ProviderOrderTokenMutation) MaxOrderAmount() (r decimal.Decimal, exists bool) { - v := m.max_order_amount - if v == nil { - return +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ProviderFiatAccountMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.provider != nil { + edges = append(edges, providerfiataccount.EdgeProvider) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ProviderFiatAccountMutation) AddedIDs(name string) []ent.Value { + switch name { + case providerfiataccount.EdgeProvider: + if id := m.provider; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ProviderFiatAccountMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ProviderFiatAccountMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ProviderFiatAccountMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedprovider { + edges = append(edges, providerfiataccount.EdgeProvider) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ProviderFiatAccountMutation) EdgeCleared(name string) bool { + switch name { + case providerfiataccount.EdgeProvider: + return m.clearedprovider + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *ProviderFiatAccountMutation) ClearEdge(name string) error { + switch name { + case providerfiataccount.EdgeProvider: + m.ClearProvider() + return nil + } + return fmt.Errorf("unknown ProviderFiatAccount unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *ProviderFiatAccountMutation) ResetEdge(name string) error { + switch name { + case providerfiataccount.EdgeProvider: + m.ResetProvider() + return nil + } + return fmt.Errorf("unknown ProviderFiatAccount edge %s", name) +} + +// ProviderOrderTokenMutation represents an operation that mutates the ProviderOrderToken nodes in the graph. +type ProviderOrderTokenMutation struct { + config + op Op + typ string + id *int + created_at *time.Time + updated_at *time.Time + fixed_buy_rate *decimal.Decimal + addfixed_buy_rate *decimal.Decimal + fixed_sell_rate *decimal.Decimal + addfixed_sell_rate *decimal.Decimal + floating_buy_delta *decimal.Decimal + addfloating_buy_delta *decimal.Decimal + floating_sell_delta *decimal.Decimal + addfloating_sell_delta *decimal.Decimal + max_order_amount *decimal.Decimal + addmax_order_amount *decimal.Decimal + min_order_amount *decimal.Decimal + addmin_order_amount *decimal.Decimal + max_order_amount_otc *decimal.Decimal + addmax_order_amount_otc *decimal.Decimal + min_order_amount_otc *decimal.Decimal + addmin_order_amount_otc *decimal.Decimal + rate_slippage *decimal.Decimal + addrate_slippage *decimal.Decimal + settlement_address *string + payout_address *string + network *string + score *decimal.Decimal + addscore *decimal.Decimal + last_order_assigned_at *time.Time + clearedFields map[string]struct{} + provider *string + clearedprovider bool + token *int + clearedtoken bool + currency *uuid.UUID + clearedcurrency bool + score_histories map[uuid.UUID]struct{} + removedscore_histories map[uuid.UUID]struct{} + clearedscore_histories bool + assignment_runs map[uuid.UUID]struct{} + removedassignment_runs map[uuid.UUID]struct{} + clearedassignment_runs bool + done bool + oldValue func(context.Context) (*ProviderOrderToken, error) + predicates []predicate.ProviderOrderToken +} + +var _ ent.Mutation = (*ProviderOrderTokenMutation)(nil) + +// providerordertokenOption allows management of the mutation configuration using functional options. +type providerordertokenOption func(*ProviderOrderTokenMutation) + +// newProviderOrderTokenMutation creates new mutation for the ProviderOrderToken entity. +func newProviderOrderTokenMutation(c config, op Op, opts ...providerordertokenOption) *ProviderOrderTokenMutation { + m := &ProviderOrderTokenMutation{ + config: c, + op: op, + typ: TypeProviderOrderToken, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withProviderOrderTokenID sets the ID field of the mutation. +func withProviderOrderTokenID(id int) providerordertokenOption { + return func(m *ProviderOrderTokenMutation) { + var ( + err error + once sync.Once + value *ProviderOrderToken + ) + m.oldValue = func(ctx context.Context) (*ProviderOrderToken, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ProviderOrderToken.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withProviderOrderToken sets the old ProviderOrderToken of the mutation. +func withProviderOrderToken(node *ProviderOrderToken) providerordertokenOption { + return func(m *ProviderOrderTokenMutation) { + m.oldValue = func(context.Context) (*ProviderOrderToken, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m ProviderOrderTokenMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m ProviderOrderTokenMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *ProviderOrderTokenMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *ProviderOrderTokenMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().ProviderOrderToken.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreatedAt sets the "created_at" field. +func (m *ProviderOrderTokenMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ProviderOrderTokenMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *ProviderOrderTokenMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ProviderOrderTokenMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ProviderOrderTokenMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *ProviderOrderTokenMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetFixedBuyRate sets the "fixed_buy_rate" field. +func (m *ProviderOrderTokenMutation) SetFixedBuyRate(d decimal.Decimal) { + m.fixed_buy_rate = &d + m.addfixed_buy_rate = nil +} + +// FixedBuyRate returns the value of the "fixed_buy_rate" field in the mutation. +func (m *ProviderOrderTokenMutation) FixedBuyRate() (r decimal.Decimal, exists bool) { + v := m.fixed_buy_rate + if v == nil { + return + } + return *v, true +} + +// OldFixedBuyRate returns the old "fixed_buy_rate" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldFixedBuyRate(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFixedBuyRate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFixedBuyRate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFixedBuyRate: %w", err) + } + return oldValue.FixedBuyRate, nil +} + +// AddFixedBuyRate adds d to the "fixed_buy_rate" field. +func (m *ProviderOrderTokenMutation) AddFixedBuyRate(d decimal.Decimal) { + if m.addfixed_buy_rate != nil { + *m.addfixed_buy_rate = m.addfixed_buy_rate.Add(d) + } else { + m.addfixed_buy_rate = &d + } +} + +// AddedFixedBuyRate returns the value that was added to the "fixed_buy_rate" field in this mutation. +func (m *ProviderOrderTokenMutation) AddedFixedBuyRate() (r decimal.Decimal, exists bool) { + v := m.addfixed_buy_rate + if v == nil { + return + } + return *v, true +} + +// ClearFixedBuyRate clears the value of the "fixed_buy_rate" field. +func (m *ProviderOrderTokenMutation) ClearFixedBuyRate() { + m.fixed_buy_rate = nil + m.addfixed_buy_rate = nil + m.clearedFields[providerordertoken.FieldFixedBuyRate] = struct{}{} +} + +// FixedBuyRateCleared returns if the "fixed_buy_rate" field was cleared in this mutation. +func (m *ProviderOrderTokenMutation) FixedBuyRateCleared() bool { + _, ok := m.clearedFields[providerordertoken.FieldFixedBuyRate] + return ok +} + +// ResetFixedBuyRate resets all changes to the "fixed_buy_rate" field. +func (m *ProviderOrderTokenMutation) ResetFixedBuyRate() { + m.fixed_buy_rate = nil + m.addfixed_buy_rate = nil + delete(m.clearedFields, providerordertoken.FieldFixedBuyRate) +} + +// SetFixedSellRate sets the "fixed_sell_rate" field. +func (m *ProviderOrderTokenMutation) SetFixedSellRate(d decimal.Decimal) { + m.fixed_sell_rate = &d + m.addfixed_sell_rate = nil +} + +// FixedSellRate returns the value of the "fixed_sell_rate" field in the mutation. +func (m *ProviderOrderTokenMutation) FixedSellRate() (r decimal.Decimal, exists bool) { + v := m.fixed_sell_rate + if v == nil { + return + } + return *v, true +} + +// OldFixedSellRate returns the old "fixed_sell_rate" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldFixedSellRate(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFixedSellRate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFixedSellRate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFixedSellRate: %w", err) + } + return oldValue.FixedSellRate, nil +} + +// AddFixedSellRate adds d to the "fixed_sell_rate" field. +func (m *ProviderOrderTokenMutation) AddFixedSellRate(d decimal.Decimal) { + if m.addfixed_sell_rate != nil { + *m.addfixed_sell_rate = m.addfixed_sell_rate.Add(d) + } else { + m.addfixed_sell_rate = &d + } +} + +// AddedFixedSellRate returns the value that was added to the "fixed_sell_rate" field in this mutation. +func (m *ProviderOrderTokenMutation) AddedFixedSellRate() (r decimal.Decimal, exists bool) { + v := m.addfixed_sell_rate + if v == nil { + return + } + return *v, true +} + +// ClearFixedSellRate clears the value of the "fixed_sell_rate" field. +func (m *ProviderOrderTokenMutation) ClearFixedSellRate() { + m.fixed_sell_rate = nil + m.addfixed_sell_rate = nil + m.clearedFields[providerordertoken.FieldFixedSellRate] = struct{}{} +} + +// FixedSellRateCleared returns if the "fixed_sell_rate" field was cleared in this mutation. +func (m *ProviderOrderTokenMutation) FixedSellRateCleared() bool { + _, ok := m.clearedFields[providerordertoken.FieldFixedSellRate] + return ok +} + +// ResetFixedSellRate resets all changes to the "fixed_sell_rate" field. +func (m *ProviderOrderTokenMutation) ResetFixedSellRate() { + m.fixed_sell_rate = nil + m.addfixed_sell_rate = nil + delete(m.clearedFields, providerordertoken.FieldFixedSellRate) +} + +// SetFloatingBuyDelta sets the "floating_buy_delta" field. +func (m *ProviderOrderTokenMutation) SetFloatingBuyDelta(d decimal.Decimal) { + m.floating_buy_delta = &d + m.addfloating_buy_delta = nil +} + +// FloatingBuyDelta returns the value of the "floating_buy_delta" field in the mutation. +func (m *ProviderOrderTokenMutation) FloatingBuyDelta() (r decimal.Decimal, exists bool) { + v := m.floating_buy_delta + if v == nil { + return + } + return *v, true +} + +// OldFloatingBuyDelta returns the old "floating_buy_delta" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldFloatingBuyDelta(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFloatingBuyDelta is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFloatingBuyDelta requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFloatingBuyDelta: %w", err) + } + return oldValue.FloatingBuyDelta, nil +} + +// AddFloatingBuyDelta adds d to the "floating_buy_delta" field. +func (m *ProviderOrderTokenMutation) AddFloatingBuyDelta(d decimal.Decimal) { + if m.addfloating_buy_delta != nil { + *m.addfloating_buy_delta = m.addfloating_buy_delta.Add(d) + } else { + m.addfloating_buy_delta = &d + } +} + +// AddedFloatingBuyDelta returns the value that was added to the "floating_buy_delta" field in this mutation. +func (m *ProviderOrderTokenMutation) AddedFloatingBuyDelta() (r decimal.Decimal, exists bool) { + v := m.addfloating_buy_delta + if v == nil { + return + } + return *v, true +} + +// ClearFloatingBuyDelta clears the value of the "floating_buy_delta" field. +func (m *ProviderOrderTokenMutation) ClearFloatingBuyDelta() { + m.floating_buy_delta = nil + m.addfloating_buy_delta = nil + m.clearedFields[providerordertoken.FieldFloatingBuyDelta] = struct{}{} +} + +// FloatingBuyDeltaCleared returns if the "floating_buy_delta" field was cleared in this mutation. +func (m *ProviderOrderTokenMutation) FloatingBuyDeltaCleared() bool { + _, ok := m.clearedFields[providerordertoken.FieldFloatingBuyDelta] + return ok +} + +// ResetFloatingBuyDelta resets all changes to the "floating_buy_delta" field. +func (m *ProviderOrderTokenMutation) ResetFloatingBuyDelta() { + m.floating_buy_delta = nil + m.addfloating_buy_delta = nil + delete(m.clearedFields, providerordertoken.FieldFloatingBuyDelta) +} + +// SetFloatingSellDelta sets the "floating_sell_delta" field. +func (m *ProviderOrderTokenMutation) SetFloatingSellDelta(d decimal.Decimal) { + m.floating_sell_delta = &d + m.addfloating_sell_delta = nil +} + +// FloatingSellDelta returns the value of the "floating_sell_delta" field in the mutation. +func (m *ProviderOrderTokenMutation) FloatingSellDelta() (r decimal.Decimal, exists bool) { + v := m.floating_sell_delta + if v == nil { + return + } + return *v, true +} + +// OldFloatingSellDelta returns the old "floating_sell_delta" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldFloatingSellDelta(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFloatingSellDelta is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFloatingSellDelta requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFloatingSellDelta: %w", err) + } + return oldValue.FloatingSellDelta, nil +} + +// AddFloatingSellDelta adds d to the "floating_sell_delta" field. +func (m *ProviderOrderTokenMutation) AddFloatingSellDelta(d decimal.Decimal) { + if m.addfloating_sell_delta != nil { + *m.addfloating_sell_delta = m.addfloating_sell_delta.Add(d) + } else { + m.addfloating_sell_delta = &d + } +} + +// AddedFloatingSellDelta returns the value that was added to the "floating_sell_delta" field in this mutation. +func (m *ProviderOrderTokenMutation) AddedFloatingSellDelta() (r decimal.Decimal, exists bool) { + v := m.addfloating_sell_delta + if v == nil { + return + } + return *v, true +} + +// ClearFloatingSellDelta clears the value of the "floating_sell_delta" field. +func (m *ProviderOrderTokenMutation) ClearFloatingSellDelta() { + m.floating_sell_delta = nil + m.addfloating_sell_delta = nil + m.clearedFields[providerordertoken.FieldFloatingSellDelta] = struct{}{} +} + +// FloatingSellDeltaCleared returns if the "floating_sell_delta" field was cleared in this mutation. +func (m *ProviderOrderTokenMutation) FloatingSellDeltaCleared() bool { + _, ok := m.clearedFields[providerordertoken.FieldFloatingSellDelta] + return ok +} + +// ResetFloatingSellDelta resets all changes to the "floating_sell_delta" field. +func (m *ProviderOrderTokenMutation) ResetFloatingSellDelta() { + m.floating_sell_delta = nil + m.addfloating_sell_delta = nil + delete(m.clearedFields, providerordertoken.FieldFloatingSellDelta) +} + +// SetMaxOrderAmount sets the "max_order_amount" field. +func (m *ProviderOrderTokenMutation) SetMaxOrderAmount(d decimal.Decimal) { + m.max_order_amount = &d + m.addmax_order_amount = nil +} + +// MaxOrderAmount returns the value of the "max_order_amount" field in the mutation. +func (m *ProviderOrderTokenMutation) MaxOrderAmount() (r decimal.Decimal, exists bool) { + v := m.max_order_amount + if v == nil { + return + } + return *v, true +} + +// OldMaxOrderAmount returns the old "max_order_amount" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldMaxOrderAmount(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMaxOrderAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMaxOrderAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMaxOrderAmount: %w", err) + } + return oldValue.MaxOrderAmount, nil +} + +// AddMaxOrderAmount adds d to the "max_order_amount" field. +func (m *ProviderOrderTokenMutation) AddMaxOrderAmount(d decimal.Decimal) { + if m.addmax_order_amount != nil { + *m.addmax_order_amount = m.addmax_order_amount.Add(d) + } else { + m.addmax_order_amount = &d + } +} + +// AddedMaxOrderAmount returns the value that was added to the "max_order_amount" field in this mutation. +func (m *ProviderOrderTokenMutation) AddedMaxOrderAmount() (r decimal.Decimal, exists bool) { + v := m.addmax_order_amount + if v == nil { + return + } + return *v, true +} + +// ResetMaxOrderAmount resets all changes to the "max_order_amount" field. +func (m *ProviderOrderTokenMutation) ResetMaxOrderAmount() { + m.max_order_amount = nil + m.addmax_order_amount = nil +} + +// SetMinOrderAmount sets the "min_order_amount" field. +func (m *ProviderOrderTokenMutation) SetMinOrderAmount(d decimal.Decimal) { + m.min_order_amount = &d + m.addmin_order_amount = nil +} + +// MinOrderAmount returns the value of the "min_order_amount" field in the mutation. +func (m *ProviderOrderTokenMutation) MinOrderAmount() (r decimal.Decimal, exists bool) { + v := m.min_order_amount + if v == nil { + return + } + return *v, true +} + +// OldMinOrderAmount returns the old "min_order_amount" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldMinOrderAmount(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMinOrderAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMinOrderAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMinOrderAmount: %w", err) + } + return oldValue.MinOrderAmount, nil +} + +// AddMinOrderAmount adds d to the "min_order_amount" field. +func (m *ProviderOrderTokenMutation) AddMinOrderAmount(d decimal.Decimal) { + if m.addmin_order_amount != nil { + *m.addmin_order_amount = m.addmin_order_amount.Add(d) + } else { + m.addmin_order_amount = &d + } +} + +// AddedMinOrderAmount returns the value that was added to the "min_order_amount" field in this mutation. +func (m *ProviderOrderTokenMutation) AddedMinOrderAmount() (r decimal.Decimal, exists bool) { + v := m.addmin_order_amount + if v == nil { + return + } + return *v, true +} + +// ResetMinOrderAmount resets all changes to the "min_order_amount" field. +func (m *ProviderOrderTokenMutation) ResetMinOrderAmount() { + m.min_order_amount = nil + m.addmin_order_amount = nil +} + +// SetMaxOrderAmountOtc sets the "max_order_amount_otc" field. +func (m *ProviderOrderTokenMutation) SetMaxOrderAmountOtc(d decimal.Decimal) { + m.max_order_amount_otc = &d + m.addmax_order_amount_otc = nil +} + +// MaxOrderAmountOtc returns the value of the "max_order_amount_otc" field in the mutation. +func (m *ProviderOrderTokenMutation) MaxOrderAmountOtc() (r decimal.Decimal, exists bool) { + v := m.max_order_amount_otc + if v == nil { + return + } + return *v, true +} + +// OldMaxOrderAmountOtc returns the old "max_order_amount_otc" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldMaxOrderAmountOtc(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMaxOrderAmountOtc is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMaxOrderAmountOtc requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMaxOrderAmountOtc: %w", err) + } + return oldValue.MaxOrderAmountOtc, nil +} + +// AddMaxOrderAmountOtc adds d to the "max_order_amount_otc" field. +func (m *ProviderOrderTokenMutation) AddMaxOrderAmountOtc(d decimal.Decimal) { + if m.addmax_order_amount_otc != nil { + *m.addmax_order_amount_otc = m.addmax_order_amount_otc.Add(d) + } else { + m.addmax_order_amount_otc = &d + } +} + +// AddedMaxOrderAmountOtc returns the value that was added to the "max_order_amount_otc" field in this mutation. +func (m *ProviderOrderTokenMutation) AddedMaxOrderAmountOtc() (r decimal.Decimal, exists bool) { + v := m.addmax_order_amount_otc + if v == nil { + return + } + return *v, true +} + +// ResetMaxOrderAmountOtc resets all changes to the "max_order_amount_otc" field. +func (m *ProviderOrderTokenMutation) ResetMaxOrderAmountOtc() { + m.max_order_amount_otc = nil + m.addmax_order_amount_otc = nil +} + +// SetMinOrderAmountOtc sets the "min_order_amount_otc" field. +func (m *ProviderOrderTokenMutation) SetMinOrderAmountOtc(d decimal.Decimal) { + m.min_order_amount_otc = &d + m.addmin_order_amount_otc = nil +} + +// MinOrderAmountOtc returns the value of the "min_order_amount_otc" field in the mutation. +func (m *ProviderOrderTokenMutation) MinOrderAmountOtc() (r decimal.Decimal, exists bool) { + v := m.min_order_amount_otc + if v == nil { + return + } + return *v, true +} + +// OldMinOrderAmountOtc returns the old "min_order_amount_otc" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldMinOrderAmountOtc(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMinOrderAmountOtc is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMinOrderAmountOtc requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMinOrderAmountOtc: %w", err) + } + return oldValue.MinOrderAmountOtc, nil +} + +// AddMinOrderAmountOtc adds d to the "min_order_amount_otc" field. +func (m *ProviderOrderTokenMutation) AddMinOrderAmountOtc(d decimal.Decimal) { + if m.addmin_order_amount_otc != nil { + *m.addmin_order_amount_otc = m.addmin_order_amount_otc.Add(d) + } else { + m.addmin_order_amount_otc = &d + } +} + +// AddedMinOrderAmountOtc returns the value that was added to the "min_order_amount_otc" field in this mutation. +func (m *ProviderOrderTokenMutation) AddedMinOrderAmountOtc() (r decimal.Decimal, exists bool) { + v := m.addmin_order_amount_otc + if v == nil { + return + } + return *v, true +} + +// ResetMinOrderAmountOtc resets all changes to the "min_order_amount_otc" field. +func (m *ProviderOrderTokenMutation) ResetMinOrderAmountOtc() { + m.min_order_amount_otc = nil + m.addmin_order_amount_otc = nil +} + +// SetRateSlippage sets the "rate_slippage" field. +func (m *ProviderOrderTokenMutation) SetRateSlippage(d decimal.Decimal) { + m.rate_slippage = &d + m.addrate_slippage = nil +} + +// RateSlippage returns the value of the "rate_slippage" field in the mutation. +func (m *ProviderOrderTokenMutation) RateSlippage() (r decimal.Decimal, exists bool) { + v := m.rate_slippage + if v == nil { + return + } + return *v, true +} + +// OldRateSlippage returns the old "rate_slippage" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldRateSlippage(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRateSlippage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRateSlippage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRateSlippage: %w", err) + } + return oldValue.RateSlippage, nil +} + +// AddRateSlippage adds d to the "rate_slippage" field. +func (m *ProviderOrderTokenMutation) AddRateSlippage(d decimal.Decimal) { + if m.addrate_slippage != nil { + *m.addrate_slippage = m.addrate_slippage.Add(d) + } else { + m.addrate_slippage = &d + } +} + +// AddedRateSlippage returns the value that was added to the "rate_slippage" field in this mutation. +func (m *ProviderOrderTokenMutation) AddedRateSlippage() (r decimal.Decimal, exists bool) { + v := m.addrate_slippage + if v == nil { + return + } + return *v, true +} + +// ResetRateSlippage resets all changes to the "rate_slippage" field. +func (m *ProviderOrderTokenMutation) ResetRateSlippage() { + m.rate_slippage = nil + m.addrate_slippage = nil +} + +// SetSettlementAddress sets the "settlement_address" field. +func (m *ProviderOrderTokenMutation) SetSettlementAddress(s string) { + m.settlement_address = &s +} + +// SettlementAddress returns the value of the "settlement_address" field in the mutation. +func (m *ProviderOrderTokenMutation) SettlementAddress() (r string, exists bool) { + v := m.settlement_address + if v == nil { + return + } + return *v, true +} + +// OldSettlementAddress returns the old "settlement_address" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldSettlementAddress(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSettlementAddress is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSettlementAddress requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSettlementAddress: %w", err) + } + return oldValue.SettlementAddress, nil +} + +// ClearSettlementAddress clears the value of the "settlement_address" field. +func (m *ProviderOrderTokenMutation) ClearSettlementAddress() { + m.settlement_address = nil + m.clearedFields[providerordertoken.FieldSettlementAddress] = struct{}{} +} + +// SettlementAddressCleared returns if the "settlement_address" field was cleared in this mutation. +func (m *ProviderOrderTokenMutation) SettlementAddressCleared() bool { + _, ok := m.clearedFields[providerordertoken.FieldSettlementAddress] + return ok +} + +// ResetSettlementAddress resets all changes to the "settlement_address" field. +func (m *ProviderOrderTokenMutation) ResetSettlementAddress() { + m.settlement_address = nil + delete(m.clearedFields, providerordertoken.FieldSettlementAddress) +} + +// SetPayoutAddress sets the "payout_address" field. +func (m *ProviderOrderTokenMutation) SetPayoutAddress(s string) { + m.payout_address = &s +} + +// PayoutAddress returns the value of the "payout_address" field in the mutation. +func (m *ProviderOrderTokenMutation) PayoutAddress() (r string, exists bool) { + v := m.payout_address + if v == nil { + return + } + return *v, true +} + +// OldPayoutAddress returns the old "payout_address" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldPayoutAddress(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPayoutAddress is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPayoutAddress requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPayoutAddress: %w", err) + } + return oldValue.PayoutAddress, nil +} + +// ClearPayoutAddress clears the value of the "payout_address" field. +func (m *ProviderOrderTokenMutation) ClearPayoutAddress() { + m.payout_address = nil + m.clearedFields[providerordertoken.FieldPayoutAddress] = struct{}{} +} + +// PayoutAddressCleared returns if the "payout_address" field was cleared in this mutation. +func (m *ProviderOrderTokenMutation) PayoutAddressCleared() bool { + _, ok := m.clearedFields[providerordertoken.FieldPayoutAddress] + return ok +} + +// ResetPayoutAddress resets all changes to the "payout_address" field. +func (m *ProviderOrderTokenMutation) ResetPayoutAddress() { + m.payout_address = nil + delete(m.clearedFields, providerordertoken.FieldPayoutAddress) +} + +// SetNetwork sets the "network" field. +func (m *ProviderOrderTokenMutation) SetNetwork(s string) { + m.network = &s +} + +// Network returns the value of the "network" field in the mutation. +func (m *ProviderOrderTokenMutation) Network() (r string, exists bool) { + v := m.network + if v == nil { + return + } + return *v, true +} + +// OldNetwork returns the old "network" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldNetwork(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNetwork is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNetwork requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNetwork: %w", err) + } + return oldValue.Network, nil +} + +// ResetNetwork resets all changes to the "network" field. +func (m *ProviderOrderTokenMutation) ResetNetwork() { + m.network = nil +} + +// SetScore sets the "score" field. +func (m *ProviderOrderTokenMutation) SetScore(d decimal.Decimal) { + m.score = &d + m.addscore = nil +} + +// Score returns the value of the "score" field in the mutation. +func (m *ProviderOrderTokenMutation) Score() (r decimal.Decimal, exists bool) { + v := m.score + if v == nil { + return + } + return *v, true +} + +// OldScore returns the old "score" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldScore(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScore is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScore requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScore: %w", err) + } + return oldValue.Score, nil +} + +// AddScore adds d to the "score" field. +func (m *ProviderOrderTokenMutation) AddScore(d decimal.Decimal) { + if m.addscore != nil { + *m.addscore = m.addscore.Add(d) + } else { + m.addscore = &d + } +} + +// AddedScore returns the value that was added to the "score" field in this mutation. +func (m *ProviderOrderTokenMutation) AddedScore() (r decimal.Decimal, exists bool) { + v := m.addscore + if v == nil { + return + } + return *v, true +} + +// ResetScore resets all changes to the "score" field. +func (m *ProviderOrderTokenMutation) ResetScore() { + m.score = nil + m.addscore = nil +} + +// SetLastOrderAssignedAt sets the "last_order_assigned_at" field. +func (m *ProviderOrderTokenMutation) SetLastOrderAssignedAt(t time.Time) { + m.last_order_assigned_at = &t +} + +// LastOrderAssignedAt returns the value of the "last_order_assigned_at" field in the mutation. +func (m *ProviderOrderTokenMutation) LastOrderAssignedAt() (r time.Time, exists bool) { + v := m.last_order_assigned_at + if v == nil { + return + } + return *v, true +} + +// OldLastOrderAssignedAt returns the old "last_order_assigned_at" field's value of the ProviderOrderToken entity. +// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProviderOrderTokenMutation) OldLastOrderAssignedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLastOrderAssignedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLastOrderAssignedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLastOrderAssignedAt: %w", err) + } + return oldValue.LastOrderAssignedAt, nil +} + +// ClearLastOrderAssignedAt clears the value of the "last_order_assigned_at" field. +func (m *ProviderOrderTokenMutation) ClearLastOrderAssignedAt() { + m.last_order_assigned_at = nil + m.clearedFields[providerordertoken.FieldLastOrderAssignedAt] = struct{}{} +} + +// LastOrderAssignedAtCleared returns if the "last_order_assigned_at" field was cleared in this mutation. +func (m *ProviderOrderTokenMutation) LastOrderAssignedAtCleared() bool { + _, ok := m.clearedFields[providerordertoken.FieldLastOrderAssignedAt] + return ok +} + +// ResetLastOrderAssignedAt resets all changes to the "last_order_assigned_at" field. +func (m *ProviderOrderTokenMutation) ResetLastOrderAssignedAt() { + m.last_order_assigned_at = nil + delete(m.clearedFields, providerordertoken.FieldLastOrderAssignedAt) +} + +// SetProviderID sets the "provider" edge to the ProviderProfile entity by id. +func (m *ProviderOrderTokenMutation) SetProviderID(id string) { + m.provider = &id +} + +// ClearProvider clears the "provider" edge to the ProviderProfile entity. +func (m *ProviderOrderTokenMutation) ClearProvider() { + m.clearedprovider = true +} + +// ProviderCleared reports if the "provider" edge to the ProviderProfile entity was cleared. +func (m *ProviderOrderTokenMutation) ProviderCleared() bool { + return m.clearedprovider +} + +// ProviderID returns the "provider" edge ID in the mutation. +func (m *ProviderOrderTokenMutation) ProviderID() (id string, exists bool) { + if m.provider != nil { + return *m.provider, true + } + return +} + +// ProviderIDs returns the "provider" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ProviderID instead. It exists only for internal usage by the builders. +func (m *ProviderOrderTokenMutation) ProviderIDs() (ids []string) { + if id := m.provider; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetProvider resets all changes to the "provider" edge. +func (m *ProviderOrderTokenMutation) ResetProvider() { + m.provider = nil + m.clearedprovider = false +} + +// SetTokenID sets the "token" edge to the Token entity by id. +func (m *ProviderOrderTokenMutation) SetTokenID(id int) { + m.token = &id +} + +// ClearToken clears the "token" edge to the Token entity. +func (m *ProviderOrderTokenMutation) ClearToken() { + m.clearedtoken = true +} + +// TokenCleared reports if the "token" edge to the Token entity was cleared. +func (m *ProviderOrderTokenMutation) TokenCleared() bool { + return m.clearedtoken +} + +// TokenID returns the "token" edge ID in the mutation. +func (m *ProviderOrderTokenMutation) TokenID() (id int, exists bool) { + if m.token != nil { + return *m.token, true + } + return +} + +// TokenIDs returns the "token" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TokenID instead. It exists only for internal usage by the builders. +func (m *ProviderOrderTokenMutation) TokenIDs() (ids []int) { + if id := m.token; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetToken resets all changes to the "token" edge. +func (m *ProviderOrderTokenMutation) ResetToken() { + m.token = nil + m.clearedtoken = false +} + +// SetCurrencyID sets the "currency" edge to the FiatCurrency entity by id. +func (m *ProviderOrderTokenMutation) SetCurrencyID(id uuid.UUID) { + m.currency = &id +} + +// ClearCurrency clears the "currency" edge to the FiatCurrency entity. +func (m *ProviderOrderTokenMutation) ClearCurrency() { + m.clearedcurrency = true +} + +// CurrencyCleared reports if the "currency" edge to the FiatCurrency entity was cleared. +func (m *ProviderOrderTokenMutation) CurrencyCleared() bool { + return m.clearedcurrency +} + +// CurrencyID returns the "currency" edge ID in the mutation. +func (m *ProviderOrderTokenMutation) CurrencyID() (id uuid.UUID, exists bool) { + if m.currency != nil { + return *m.currency, true + } + return +} + +// CurrencyIDs returns the "currency" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CurrencyID instead. It exists only for internal usage by the builders. +func (m *ProviderOrderTokenMutation) CurrencyIDs() (ids []uuid.UUID) { + if id := m.currency; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCurrency resets all changes to the "currency" edge. +func (m *ProviderOrderTokenMutation) ResetCurrency() { + m.currency = nil + m.clearedcurrency = false +} + +// AddScoreHistoryIDs adds the "score_histories" edge to the ProviderOrderTokenScoreHistory entity by ids. +func (m *ProviderOrderTokenMutation) AddScoreHistoryIDs(ids ...uuid.UUID) { + if m.score_histories == nil { + m.score_histories = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.score_histories[ids[i]] = struct{}{} + } +} + +// ClearScoreHistories clears the "score_histories" edge to the ProviderOrderTokenScoreHistory entity. +func (m *ProviderOrderTokenMutation) ClearScoreHistories() { + m.clearedscore_histories = true +} + +// ScoreHistoriesCleared reports if the "score_histories" edge to the ProviderOrderTokenScoreHistory entity was cleared. +func (m *ProviderOrderTokenMutation) ScoreHistoriesCleared() bool { + return m.clearedscore_histories +} + +// RemoveScoreHistoryIDs removes the "score_histories" edge to the ProviderOrderTokenScoreHistory entity by IDs. +func (m *ProviderOrderTokenMutation) RemoveScoreHistoryIDs(ids ...uuid.UUID) { + if m.removedscore_histories == nil { + m.removedscore_histories = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.score_histories, ids[i]) + m.removedscore_histories[ids[i]] = struct{}{} + } +} + +// RemovedScoreHistories returns the removed IDs of the "score_histories" edge to the ProviderOrderTokenScoreHistory entity. +func (m *ProviderOrderTokenMutation) RemovedScoreHistoriesIDs() (ids []uuid.UUID) { + for id := range m.removedscore_histories { + ids = append(ids, id) + } + return +} + +// ScoreHistoriesIDs returns the "score_histories" edge IDs in the mutation. +func (m *ProviderOrderTokenMutation) ScoreHistoriesIDs() (ids []uuid.UUID) { + for id := range m.score_histories { + ids = append(ids, id) + } + return +} + +// ResetScoreHistories resets all changes to the "score_histories" edge. +func (m *ProviderOrderTokenMutation) ResetScoreHistories() { + m.score_histories = nil + m.clearedscore_histories = false + m.removedscore_histories = nil +} + +// AddAssignmentRunIDs adds the "assignment_runs" edge to the ProviderAssignmentRun entity by ids. +func (m *ProviderOrderTokenMutation) AddAssignmentRunIDs(ids ...uuid.UUID) { + if m.assignment_runs == nil { + m.assignment_runs = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.assignment_runs[ids[i]] = struct{}{} + } +} + +// ClearAssignmentRuns clears the "assignment_runs" edge to the ProviderAssignmentRun entity. +func (m *ProviderOrderTokenMutation) ClearAssignmentRuns() { + m.clearedassignment_runs = true +} + +// AssignmentRunsCleared reports if the "assignment_runs" edge to the ProviderAssignmentRun entity was cleared. +func (m *ProviderOrderTokenMutation) AssignmentRunsCleared() bool { + return m.clearedassignment_runs +} + +// RemoveAssignmentRunIDs removes the "assignment_runs" edge to the ProviderAssignmentRun entity by IDs. +func (m *ProviderOrderTokenMutation) RemoveAssignmentRunIDs(ids ...uuid.UUID) { + if m.removedassignment_runs == nil { + m.removedassignment_runs = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.assignment_runs, ids[i]) + m.removedassignment_runs[ids[i]] = struct{}{} + } +} + +// RemovedAssignmentRuns returns the removed IDs of the "assignment_runs" edge to the ProviderAssignmentRun entity. +func (m *ProviderOrderTokenMutation) RemovedAssignmentRunsIDs() (ids []uuid.UUID) { + for id := range m.removedassignment_runs { + ids = append(ids, id) + } + return +} + +// AssignmentRunsIDs returns the "assignment_runs" edge IDs in the mutation. +func (m *ProviderOrderTokenMutation) AssignmentRunsIDs() (ids []uuid.UUID) { + for id := range m.assignment_runs { + ids = append(ids, id) + } + return +} + +// ResetAssignmentRuns resets all changes to the "assignment_runs" edge. +func (m *ProviderOrderTokenMutation) ResetAssignmentRuns() { + m.assignment_runs = nil + m.clearedassignment_runs = false + m.removedassignment_runs = nil +} + +// Where appends a list predicates to the ProviderOrderTokenMutation builder. +func (m *ProviderOrderTokenMutation) Where(ps ...predicate.ProviderOrderToken) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ProviderOrderTokenMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ProviderOrderTokenMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ProviderOrderToken, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ProviderOrderTokenMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ProviderOrderTokenMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ProviderOrderToken). +func (m *ProviderOrderTokenMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *ProviderOrderTokenMutation) Fields() []string { + fields := make([]string, 0, 16) + if m.created_at != nil { + fields = append(fields, providerordertoken.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, providerordertoken.FieldUpdatedAt) + } + if m.fixed_buy_rate != nil { + fields = append(fields, providerordertoken.FieldFixedBuyRate) + } + if m.fixed_sell_rate != nil { + fields = append(fields, providerordertoken.FieldFixedSellRate) + } + if m.floating_buy_delta != nil { + fields = append(fields, providerordertoken.FieldFloatingBuyDelta) + } + if m.floating_sell_delta != nil { + fields = append(fields, providerordertoken.FieldFloatingSellDelta) + } + if m.max_order_amount != nil { + fields = append(fields, providerordertoken.FieldMaxOrderAmount) + } + if m.min_order_amount != nil { + fields = append(fields, providerordertoken.FieldMinOrderAmount) + } + if m.max_order_amount_otc != nil { + fields = append(fields, providerordertoken.FieldMaxOrderAmountOtc) + } + if m.min_order_amount_otc != nil { + fields = append(fields, providerordertoken.FieldMinOrderAmountOtc) + } + if m.rate_slippage != nil { + fields = append(fields, providerordertoken.FieldRateSlippage) + } + if m.settlement_address != nil { + fields = append(fields, providerordertoken.FieldSettlementAddress) + } + if m.payout_address != nil { + fields = append(fields, providerordertoken.FieldPayoutAddress) + } + if m.network != nil { + fields = append(fields, providerordertoken.FieldNetwork) + } + if m.score != nil { + fields = append(fields, providerordertoken.FieldScore) + } + if m.last_order_assigned_at != nil { + fields = append(fields, providerordertoken.FieldLastOrderAssignedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *ProviderOrderTokenMutation) Field(name string) (ent.Value, bool) { + switch name { + case providerordertoken.FieldCreatedAt: + return m.CreatedAt() + case providerordertoken.FieldUpdatedAt: + return m.UpdatedAt() + case providerordertoken.FieldFixedBuyRate: + return m.FixedBuyRate() + case providerordertoken.FieldFixedSellRate: + return m.FixedSellRate() + case providerordertoken.FieldFloatingBuyDelta: + return m.FloatingBuyDelta() + case providerordertoken.FieldFloatingSellDelta: + return m.FloatingSellDelta() + case providerordertoken.FieldMaxOrderAmount: + return m.MaxOrderAmount() + case providerordertoken.FieldMinOrderAmount: + return m.MinOrderAmount() + case providerordertoken.FieldMaxOrderAmountOtc: + return m.MaxOrderAmountOtc() + case providerordertoken.FieldMinOrderAmountOtc: + return m.MinOrderAmountOtc() + case providerordertoken.FieldRateSlippage: + return m.RateSlippage() + case providerordertoken.FieldSettlementAddress: + return m.SettlementAddress() + case providerordertoken.FieldPayoutAddress: + return m.PayoutAddress() + case providerordertoken.FieldNetwork: + return m.Network() + case providerordertoken.FieldScore: + return m.Score() + case providerordertoken.FieldLastOrderAssignedAt: + return m.LastOrderAssignedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *ProviderOrderTokenMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case providerordertoken.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case providerordertoken.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case providerordertoken.FieldFixedBuyRate: + return m.OldFixedBuyRate(ctx) + case providerordertoken.FieldFixedSellRate: + return m.OldFixedSellRate(ctx) + case providerordertoken.FieldFloatingBuyDelta: + return m.OldFloatingBuyDelta(ctx) + case providerordertoken.FieldFloatingSellDelta: + return m.OldFloatingSellDelta(ctx) + case providerordertoken.FieldMaxOrderAmount: + return m.OldMaxOrderAmount(ctx) + case providerordertoken.FieldMinOrderAmount: + return m.OldMinOrderAmount(ctx) + case providerordertoken.FieldMaxOrderAmountOtc: + return m.OldMaxOrderAmountOtc(ctx) + case providerordertoken.FieldMinOrderAmountOtc: + return m.OldMinOrderAmountOtc(ctx) + case providerordertoken.FieldRateSlippage: + return m.OldRateSlippage(ctx) + case providerordertoken.FieldSettlementAddress: + return m.OldSettlementAddress(ctx) + case providerordertoken.FieldPayoutAddress: + return m.OldPayoutAddress(ctx) + case providerordertoken.FieldNetwork: + return m.OldNetwork(ctx) + case providerordertoken.FieldScore: + return m.OldScore(ctx) + case providerordertoken.FieldLastOrderAssignedAt: + return m.OldLastOrderAssignedAt(ctx) + } + return nil, fmt.Errorf("unknown ProviderOrderToken field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ProviderOrderTokenMutation) SetField(name string, value ent.Value) error { + switch name { + case providerordertoken.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case providerordertoken.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case providerordertoken.FieldFixedBuyRate: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFixedBuyRate(v) + return nil + case providerordertoken.FieldFixedSellRate: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFixedSellRate(v) + return nil + case providerordertoken.FieldFloatingBuyDelta: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFloatingBuyDelta(v) + return nil + case providerordertoken.FieldFloatingSellDelta: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFloatingSellDelta(v) + return nil + case providerordertoken.FieldMaxOrderAmount: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMaxOrderAmount(v) + return nil + case providerordertoken.FieldMinOrderAmount: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMinOrderAmount(v) + return nil + case providerordertoken.FieldMaxOrderAmountOtc: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMaxOrderAmountOtc(v) + return nil + case providerordertoken.FieldMinOrderAmountOtc: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMinOrderAmountOtc(v) + return nil + case providerordertoken.FieldRateSlippage: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRateSlippage(v) + return nil + case providerordertoken.FieldSettlementAddress: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSettlementAddress(v) + return nil + case providerordertoken.FieldPayoutAddress: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPayoutAddress(v) + return nil + case providerordertoken.FieldNetwork: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNetwork(v) + return nil + case providerordertoken.FieldScore: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScore(v) + return nil + case providerordertoken.FieldLastOrderAssignedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLastOrderAssignedAt(v) + return nil + } + return fmt.Errorf("unknown ProviderOrderToken field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ProviderOrderTokenMutation) AddedFields() []string { + var fields []string + if m.addfixed_buy_rate != nil { + fields = append(fields, providerordertoken.FieldFixedBuyRate) + } + if m.addfixed_sell_rate != nil { + fields = append(fields, providerordertoken.FieldFixedSellRate) + } + if m.addfloating_buy_delta != nil { + fields = append(fields, providerordertoken.FieldFloatingBuyDelta) + } + if m.addfloating_sell_delta != nil { + fields = append(fields, providerordertoken.FieldFloatingSellDelta) + } + if m.addmax_order_amount != nil { + fields = append(fields, providerordertoken.FieldMaxOrderAmount) + } + if m.addmin_order_amount != nil { + fields = append(fields, providerordertoken.FieldMinOrderAmount) + } + if m.addmax_order_amount_otc != nil { + fields = append(fields, providerordertoken.FieldMaxOrderAmountOtc) + } + if m.addmin_order_amount_otc != nil { + fields = append(fields, providerordertoken.FieldMinOrderAmountOtc) + } + if m.addrate_slippage != nil { + fields = append(fields, providerordertoken.FieldRateSlippage) + } + if m.addscore != nil { + fields = append(fields, providerordertoken.FieldScore) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *ProviderOrderTokenMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case providerordertoken.FieldFixedBuyRate: + return m.AddedFixedBuyRate() + case providerordertoken.FieldFixedSellRate: + return m.AddedFixedSellRate() + case providerordertoken.FieldFloatingBuyDelta: + return m.AddedFloatingBuyDelta() + case providerordertoken.FieldFloatingSellDelta: + return m.AddedFloatingSellDelta() + case providerordertoken.FieldMaxOrderAmount: + return m.AddedMaxOrderAmount() + case providerordertoken.FieldMinOrderAmount: + return m.AddedMinOrderAmount() + case providerordertoken.FieldMaxOrderAmountOtc: + return m.AddedMaxOrderAmountOtc() + case providerordertoken.FieldMinOrderAmountOtc: + return m.AddedMinOrderAmountOtc() + case providerordertoken.FieldRateSlippage: + return m.AddedRateSlippage() + case providerordertoken.FieldScore: + return m.AddedScore() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ProviderOrderTokenMutation) AddField(name string, value ent.Value) error { + switch name { + case providerordertoken.FieldFixedBuyRate: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddFixedBuyRate(v) + return nil + case providerordertoken.FieldFixedSellRate: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddFixedSellRate(v) + return nil + case providerordertoken.FieldFloatingBuyDelta: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddFloatingBuyDelta(v) + return nil + case providerordertoken.FieldFloatingSellDelta: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddFloatingSellDelta(v) + return nil + case providerordertoken.FieldMaxOrderAmount: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMaxOrderAmount(v) + return nil + case providerordertoken.FieldMinOrderAmount: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMinOrderAmount(v) + return nil + case providerordertoken.FieldMaxOrderAmountOtc: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMaxOrderAmountOtc(v) + return nil + case providerordertoken.FieldMinOrderAmountOtc: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMinOrderAmountOtc(v) + return nil + case providerordertoken.FieldRateSlippage: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddRateSlippage(v) + return nil + case providerordertoken.FieldScore: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddScore(v) + return nil + } + return fmt.Errorf("unknown ProviderOrderToken numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ProviderOrderTokenMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(providerordertoken.FieldFixedBuyRate) { + fields = append(fields, providerordertoken.FieldFixedBuyRate) + } + if m.FieldCleared(providerordertoken.FieldFixedSellRate) { + fields = append(fields, providerordertoken.FieldFixedSellRate) + } + if m.FieldCleared(providerordertoken.FieldFloatingBuyDelta) { + fields = append(fields, providerordertoken.FieldFloatingBuyDelta) + } + if m.FieldCleared(providerordertoken.FieldFloatingSellDelta) { + fields = append(fields, providerordertoken.FieldFloatingSellDelta) + } + if m.FieldCleared(providerordertoken.FieldSettlementAddress) { + fields = append(fields, providerordertoken.FieldSettlementAddress) + } + if m.FieldCleared(providerordertoken.FieldPayoutAddress) { + fields = append(fields, providerordertoken.FieldPayoutAddress) + } + if m.FieldCleared(providerordertoken.FieldLastOrderAssignedAt) { + fields = append(fields, providerordertoken.FieldLastOrderAssignedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ProviderOrderTokenMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *ProviderOrderTokenMutation) ClearField(name string) error { + switch name { + case providerordertoken.FieldFixedBuyRate: + m.ClearFixedBuyRate() + return nil + case providerordertoken.FieldFixedSellRate: + m.ClearFixedSellRate() + return nil + case providerordertoken.FieldFloatingBuyDelta: + m.ClearFloatingBuyDelta() + return nil + case providerordertoken.FieldFloatingSellDelta: + m.ClearFloatingSellDelta() + return nil + case providerordertoken.FieldSettlementAddress: + m.ClearSettlementAddress() + return nil + case providerordertoken.FieldPayoutAddress: + m.ClearPayoutAddress() + return nil + case providerordertoken.FieldLastOrderAssignedAt: + m.ClearLastOrderAssignedAt() + return nil + } + return fmt.Errorf("unknown ProviderOrderToken nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *ProviderOrderTokenMutation) ResetField(name string) error { + switch name { + case providerordertoken.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case providerordertoken.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case providerordertoken.FieldFixedBuyRate: + m.ResetFixedBuyRate() + return nil + case providerordertoken.FieldFixedSellRate: + m.ResetFixedSellRate() + return nil + case providerordertoken.FieldFloatingBuyDelta: + m.ResetFloatingBuyDelta() + return nil + case providerordertoken.FieldFloatingSellDelta: + m.ResetFloatingSellDelta() + return nil + case providerordertoken.FieldMaxOrderAmount: + m.ResetMaxOrderAmount() + return nil + case providerordertoken.FieldMinOrderAmount: + m.ResetMinOrderAmount() + return nil + case providerordertoken.FieldMaxOrderAmountOtc: + m.ResetMaxOrderAmountOtc() + return nil + case providerordertoken.FieldMinOrderAmountOtc: + m.ResetMinOrderAmountOtc() + return nil + case providerordertoken.FieldRateSlippage: + m.ResetRateSlippage() + return nil + case providerordertoken.FieldSettlementAddress: + m.ResetSettlementAddress() + return nil + case providerordertoken.FieldPayoutAddress: + m.ResetPayoutAddress() + return nil + case providerordertoken.FieldNetwork: + m.ResetNetwork() + return nil + case providerordertoken.FieldScore: + m.ResetScore() + return nil + case providerordertoken.FieldLastOrderAssignedAt: + m.ResetLastOrderAssignedAt() + return nil } - return *v, true + return fmt.Errorf("unknown ProviderOrderToken field %s", name) } -// OldMaxOrderAmount returns the old "max_order_amount" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldMaxOrderAmount(ctx context.Context) (v decimal.Decimal, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMaxOrderAmount is only allowed on UpdateOne operations") +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ProviderOrderTokenMutation) AddedEdges() []string { + edges := make([]string, 0, 5) + if m.provider != nil { + edges = append(edges, providerordertoken.EdgeProvider) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMaxOrderAmount requires an ID field in the mutation") + if m.token != nil { + edges = append(edges, providerordertoken.EdgeToken) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMaxOrderAmount: %w", err) + if m.currency != nil { + edges = append(edges, providerordertoken.EdgeCurrency) } - return oldValue.MaxOrderAmount, nil -} - -// AddMaxOrderAmount adds d to the "max_order_amount" field. -func (m *ProviderOrderTokenMutation) AddMaxOrderAmount(d decimal.Decimal) { - if m.addmax_order_amount != nil { - *m.addmax_order_amount = m.addmax_order_amount.Add(d) - } else { - m.addmax_order_amount = &d + if m.score_histories != nil { + edges = append(edges, providerordertoken.EdgeScoreHistories) } -} - -// AddedMaxOrderAmount returns the value that was added to the "max_order_amount" field in this mutation. -func (m *ProviderOrderTokenMutation) AddedMaxOrderAmount() (r decimal.Decimal, exists bool) { - v := m.addmax_order_amount - if v == nil { - return + if m.assignment_runs != nil { + edges = append(edges, providerordertoken.EdgeAssignmentRuns) } - return *v, true + return edges } -// ResetMaxOrderAmount resets all changes to the "max_order_amount" field. -func (m *ProviderOrderTokenMutation) ResetMaxOrderAmount() { - m.max_order_amount = nil - m.addmax_order_amount = nil +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ProviderOrderTokenMutation) AddedIDs(name string) []ent.Value { + switch name { + case providerordertoken.EdgeProvider: + if id := m.provider; id != nil { + return []ent.Value{*id} + } + case providerordertoken.EdgeToken: + if id := m.token; id != nil { + return []ent.Value{*id} + } + case providerordertoken.EdgeCurrency: + if id := m.currency; id != nil { + return []ent.Value{*id} + } + case providerordertoken.EdgeScoreHistories: + ids := make([]ent.Value, 0, len(m.score_histories)) + for id := range m.score_histories { + ids = append(ids, id) + } + return ids + case providerordertoken.EdgeAssignmentRuns: + ids := make([]ent.Value, 0, len(m.assignment_runs)) + for id := range m.assignment_runs { + ids = append(ids, id) + } + return ids + } + return nil } -// SetMinOrderAmount sets the "min_order_amount" field. -func (m *ProviderOrderTokenMutation) SetMinOrderAmount(d decimal.Decimal) { - m.min_order_amount = &d - m.addmin_order_amount = nil +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ProviderOrderTokenMutation) RemovedEdges() []string { + edges := make([]string, 0, 5) + if m.removedscore_histories != nil { + edges = append(edges, providerordertoken.EdgeScoreHistories) + } + if m.removedassignment_runs != nil { + edges = append(edges, providerordertoken.EdgeAssignmentRuns) + } + return edges } -// MinOrderAmount returns the value of the "min_order_amount" field in the mutation. -func (m *ProviderOrderTokenMutation) MinOrderAmount() (r decimal.Decimal, exists bool) { - v := m.min_order_amount - if v == nil { - return +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ProviderOrderTokenMutation) RemovedIDs(name string) []ent.Value { + switch name { + case providerordertoken.EdgeScoreHistories: + ids := make([]ent.Value, 0, len(m.removedscore_histories)) + for id := range m.removedscore_histories { + ids = append(ids, id) + } + return ids + case providerordertoken.EdgeAssignmentRuns: + ids := make([]ent.Value, 0, len(m.removedassignment_runs)) + for id := range m.removedassignment_runs { + ids = append(ids, id) + } + return ids } - return *v, true + return nil } -// OldMinOrderAmount returns the old "min_order_amount" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldMinOrderAmount(ctx context.Context) (v decimal.Decimal, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMinOrderAmount is only allowed on UpdateOne operations") +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ProviderOrderTokenMutation) ClearedEdges() []string { + edges := make([]string, 0, 5) + if m.clearedprovider { + edges = append(edges, providerordertoken.EdgeProvider) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMinOrderAmount requires an ID field in the mutation") + if m.clearedtoken { + edges = append(edges, providerordertoken.EdgeToken) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMinOrderAmount: %w", err) + if m.clearedcurrency { + edges = append(edges, providerordertoken.EdgeCurrency) } - return oldValue.MinOrderAmount, nil + if m.clearedscore_histories { + edges = append(edges, providerordertoken.EdgeScoreHistories) + } + if m.clearedassignment_runs { + edges = append(edges, providerordertoken.EdgeAssignmentRuns) + } + return edges } -// AddMinOrderAmount adds d to the "min_order_amount" field. -func (m *ProviderOrderTokenMutation) AddMinOrderAmount(d decimal.Decimal) { - if m.addmin_order_amount != nil { - *m.addmin_order_amount = m.addmin_order_amount.Add(d) - } else { - m.addmin_order_amount = &d +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ProviderOrderTokenMutation) EdgeCleared(name string) bool { + switch name { + case providerordertoken.EdgeProvider: + return m.clearedprovider + case providerordertoken.EdgeToken: + return m.clearedtoken + case providerordertoken.EdgeCurrency: + return m.clearedcurrency + case providerordertoken.EdgeScoreHistories: + return m.clearedscore_histories + case providerordertoken.EdgeAssignmentRuns: + return m.clearedassignment_runs } + return false } -// AddedMinOrderAmount returns the value that was added to the "min_order_amount" field in this mutation. -func (m *ProviderOrderTokenMutation) AddedMinOrderAmount() (r decimal.Decimal, exists bool) { - v := m.addmin_order_amount - if v == nil { - return +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *ProviderOrderTokenMutation) ClearEdge(name string) error { + switch name { + case providerordertoken.EdgeProvider: + m.ClearProvider() + return nil + case providerordertoken.EdgeToken: + m.ClearToken() + return nil + case providerordertoken.EdgeCurrency: + m.ClearCurrency() + return nil } - return *v, true + return fmt.Errorf("unknown ProviderOrderToken unique edge %s", name) } -// ResetMinOrderAmount resets all changes to the "min_order_amount" field. -func (m *ProviderOrderTokenMutation) ResetMinOrderAmount() { - m.min_order_amount = nil - m.addmin_order_amount = nil +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *ProviderOrderTokenMutation) ResetEdge(name string) error { + switch name { + case providerordertoken.EdgeProvider: + m.ResetProvider() + return nil + case providerordertoken.EdgeToken: + m.ResetToken() + return nil + case providerordertoken.EdgeCurrency: + m.ResetCurrency() + return nil + case providerordertoken.EdgeScoreHistories: + m.ResetScoreHistories() + return nil + case providerordertoken.EdgeAssignmentRuns: + m.ResetAssignmentRuns() + return nil + } + return fmt.Errorf("unknown ProviderOrderToken edge %s", name) } -// SetMaxOrderAmountOtc sets the "max_order_amount_otc" field. -func (m *ProviderOrderTokenMutation) SetMaxOrderAmountOtc(d decimal.Decimal) { - m.max_order_amount_otc = &d - m.addmax_order_amount_otc = nil +// ProviderOrderTokenScoreHistoryMutation represents an operation that mutates the ProviderOrderTokenScoreHistory nodes in the graph. +type ProviderOrderTokenScoreHistoryMutation struct { + config + op Op + typ string + id *uuid.UUID + created_at *time.Time + updated_at *time.Time + event_type *string + delta *decimal.Decimal + adddelta *decimal.Decimal + clearedFields map[string]struct{} + payment_order *uuid.UUID + clearedpayment_order bool + provider_order_token *int + clearedprovider_order_token bool + done bool + oldValue func(context.Context) (*ProviderOrderTokenScoreHistory, error) + predicates []predicate.ProviderOrderTokenScoreHistory } -// MaxOrderAmountOtc returns the value of the "max_order_amount_otc" field in the mutation. -func (m *ProviderOrderTokenMutation) MaxOrderAmountOtc() (r decimal.Decimal, exists bool) { - v := m.max_order_amount_otc - if v == nil { - return - } - return *v, true -} +var _ ent.Mutation = (*ProviderOrderTokenScoreHistoryMutation)(nil) -// OldMaxOrderAmountOtc returns the old "max_order_amount_otc" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldMaxOrderAmountOtc(ctx context.Context) (v decimal.Decimal, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMaxOrderAmountOtc is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMaxOrderAmountOtc requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMaxOrderAmountOtc: %w", err) - } - return oldValue.MaxOrderAmountOtc, nil -} +// providerordertokenscorehistoryOption allows management of the mutation configuration using functional options. +type providerordertokenscorehistoryOption func(*ProviderOrderTokenScoreHistoryMutation) -// AddMaxOrderAmountOtc adds d to the "max_order_amount_otc" field. -func (m *ProviderOrderTokenMutation) AddMaxOrderAmountOtc(d decimal.Decimal) { - if m.addmax_order_amount_otc != nil { - *m.addmax_order_amount_otc = m.addmax_order_amount_otc.Add(d) - } else { - m.addmax_order_amount_otc = &d +// newProviderOrderTokenScoreHistoryMutation creates new mutation for the ProviderOrderTokenScoreHistory entity. +func newProviderOrderTokenScoreHistoryMutation(c config, op Op, opts ...providerordertokenscorehistoryOption) *ProviderOrderTokenScoreHistoryMutation { + m := &ProviderOrderTokenScoreHistoryMutation{ + config: c, + op: op, + typ: TypeProviderOrderTokenScoreHistory, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) } + return m } -// AddedMaxOrderAmountOtc returns the value that was added to the "max_order_amount_otc" field in this mutation. -func (m *ProviderOrderTokenMutation) AddedMaxOrderAmountOtc() (r decimal.Decimal, exists bool) { - v := m.addmax_order_amount_otc - if v == nil { - return +// withProviderOrderTokenScoreHistoryID sets the ID field of the mutation. +func withProviderOrderTokenScoreHistoryID(id uuid.UUID) providerordertokenscorehistoryOption { + return func(m *ProviderOrderTokenScoreHistoryMutation) { + var ( + err error + once sync.Once + value *ProviderOrderTokenScoreHistory + ) + m.oldValue = func(ctx context.Context) (*ProviderOrderTokenScoreHistory, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ProviderOrderTokenScoreHistory.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } - return *v, true -} - -// ResetMaxOrderAmountOtc resets all changes to the "max_order_amount_otc" field. -func (m *ProviderOrderTokenMutation) ResetMaxOrderAmountOtc() { - m.max_order_amount_otc = nil - m.addmax_order_amount_otc = nil } -// SetMinOrderAmountOtc sets the "min_order_amount_otc" field. -func (m *ProviderOrderTokenMutation) SetMinOrderAmountOtc(d decimal.Decimal) { - m.min_order_amount_otc = &d - m.addmin_order_amount_otc = nil +// withProviderOrderTokenScoreHistory sets the old ProviderOrderTokenScoreHistory of the mutation. +func withProviderOrderTokenScoreHistory(node *ProviderOrderTokenScoreHistory) providerordertokenscorehistoryOption { + return func(m *ProviderOrderTokenScoreHistoryMutation) { + m.oldValue = func(context.Context) (*ProviderOrderTokenScoreHistory, error) { + return node, nil + } + m.id = &node.ID + } } -// MinOrderAmountOtc returns the value of the "min_order_amount_otc" field in the mutation. -func (m *ProviderOrderTokenMutation) MinOrderAmountOtc() (r decimal.Decimal, exists bool) { - v := m.min_order_amount_otc - if v == nil { - return - } - return *v, true +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m ProviderOrderTokenScoreHistoryMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// OldMinOrderAmountOtc returns the old "min_order_amount_otc" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldMinOrderAmountOtc(ctx context.Context) (v decimal.Decimal, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMinOrderAmountOtc is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMinOrderAmountOtc requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMinOrderAmountOtc: %w", err) +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m ProviderOrderTokenScoreHistoryMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") } - return oldValue.MinOrderAmountOtc, nil + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// AddMinOrderAmountOtc adds d to the "min_order_amount_otc" field. -func (m *ProviderOrderTokenMutation) AddMinOrderAmountOtc(d decimal.Decimal) { - if m.addmin_order_amount_otc != nil { - *m.addmin_order_amount_otc = m.addmin_order_amount_otc.Add(d) - } else { - m.addmin_order_amount_otc = &d - } +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of ProviderOrderTokenScoreHistory entities. +func (m *ProviderOrderTokenScoreHistoryMutation) SetID(id uuid.UUID) { + m.id = &id } -// AddedMinOrderAmountOtc returns the value that was added to the "min_order_amount_otc" field in this mutation. -func (m *ProviderOrderTokenMutation) AddedMinOrderAmountOtc() (r decimal.Decimal, exists bool) { - v := m.addmin_order_amount_otc - if v == nil { +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *ProviderOrderTokenScoreHistoryMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { return } - return *v, true + return *m.id, true } -// ResetMinOrderAmountOtc resets all changes to the "min_order_amount_otc" field. -func (m *ProviderOrderTokenMutation) ResetMinOrderAmountOtc() { - m.min_order_amount_otc = nil - m.addmin_order_amount_otc = nil +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *ProviderOrderTokenScoreHistoryMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []uuid.UUID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().ProviderOrderTokenScoreHistory.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } } -// SetRateSlippage sets the "rate_slippage" field. -func (m *ProviderOrderTokenMutation) SetRateSlippage(d decimal.Decimal) { - m.rate_slippage = &d - m.addrate_slippage = nil +// SetCreatedAt sets the "created_at" field. +func (m *ProviderOrderTokenScoreHistoryMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// RateSlippage returns the value of the "rate_slippage" field in the mutation. -func (m *ProviderOrderTokenMutation) RateSlippage() (r decimal.Decimal, exists bool) { - v := m.rate_slippage +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ProviderOrderTokenScoreHistoryMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldRateSlippage returns the old "rate_slippage" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the ProviderOrderTokenScoreHistory entity. +// If the ProviderOrderTokenScoreHistory object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldRateSlippage(ctx context.Context) (v decimal.Decimal, err error) { +func (m *ProviderOrderTokenScoreHistoryMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRateSlippage is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRateSlippage requires an ID field in the mutation") + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldRateSlippage: %w", err) - } - return oldValue.RateSlippage, nil -} - -// AddRateSlippage adds d to the "rate_slippage" field. -func (m *ProviderOrderTokenMutation) AddRateSlippage(d decimal.Decimal) { - if m.addrate_slippage != nil { - *m.addrate_slippage = m.addrate_slippage.Add(d) - } else { - m.addrate_slippage = &d - } -} - -// AddedRateSlippage returns the value that was added to the "rate_slippage" field in this mutation. -func (m *ProviderOrderTokenMutation) AddedRateSlippage() (r decimal.Decimal, exists bool) { - v := m.addrate_slippage - if v == nil { - return + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } - return *v, true + return oldValue.CreatedAt, nil } -// ResetRateSlippage resets all changes to the "rate_slippage" field. -func (m *ProviderOrderTokenMutation) ResetRateSlippage() { - m.rate_slippage = nil - m.addrate_slippage = nil +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *ProviderOrderTokenScoreHistoryMutation) ResetCreatedAt() { + m.created_at = nil } -// SetSettlementAddress sets the "settlement_address" field. -func (m *ProviderOrderTokenMutation) SetSettlementAddress(s string) { - m.settlement_address = &s +// SetUpdatedAt sets the "updated_at" field. +func (m *ProviderOrderTokenScoreHistoryMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t } -// SettlementAddress returns the value of the "settlement_address" field in the mutation. -func (m *ProviderOrderTokenMutation) SettlementAddress() (r string, exists bool) { - v := m.settlement_address +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ProviderOrderTokenScoreHistoryMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at if v == nil { return } return *v, true } -// OldSettlementAddress returns the old "settlement_address" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the ProviderOrderTokenScoreHistory entity. +// If the ProviderOrderTokenScoreHistory object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldSettlementAddress(ctx context.Context) (v string, err error) { +func (m *ProviderOrderTokenScoreHistoryMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSettlementAddress is only allowed on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSettlementAddress requires an ID field in the mutation") + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldSettlementAddress: %w", err) + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } - return oldValue.SettlementAddress, nil -} - -// ClearSettlementAddress clears the value of the "settlement_address" field. -func (m *ProviderOrderTokenMutation) ClearSettlementAddress() { - m.settlement_address = nil - m.clearedFields[providerordertoken.FieldSettlementAddress] = struct{}{} -} - -// SettlementAddressCleared returns if the "settlement_address" field was cleared in this mutation. -func (m *ProviderOrderTokenMutation) SettlementAddressCleared() bool { - _, ok := m.clearedFields[providerordertoken.FieldSettlementAddress] - return ok + return oldValue.UpdatedAt, nil } -// ResetSettlementAddress resets all changes to the "settlement_address" field. -func (m *ProviderOrderTokenMutation) ResetSettlementAddress() { - m.settlement_address = nil - delete(m.clearedFields, providerordertoken.FieldSettlementAddress) +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *ProviderOrderTokenScoreHistoryMutation) ResetUpdatedAt() { + m.updated_at = nil } -// SetPayoutAddress sets the "payout_address" field. -func (m *ProviderOrderTokenMutation) SetPayoutAddress(s string) { - m.payout_address = &s +// SetEventType sets the "event_type" field. +func (m *ProviderOrderTokenScoreHistoryMutation) SetEventType(s string) { + m.event_type = &s } -// PayoutAddress returns the value of the "payout_address" field in the mutation. -func (m *ProviderOrderTokenMutation) PayoutAddress() (r string, exists bool) { - v := m.payout_address +// EventType returns the value of the "event_type" field in the mutation. +func (m *ProviderOrderTokenScoreHistoryMutation) EventType() (r string, exists bool) { + v := m.event_type if v == nil { return } return *v, true } -// OldPayoutAddress returns the old "payout_address" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// OldEventType returns the old "event_type" field's value of the ProviderOrderTokenScoreHistory entity. +// If the ProviderOrderTokenScoreHistory object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldPayoutAddress(ctx context.Context) (v string, err error) { +func (m *ProviderOrderTokenScoreHistoryMutation) OldEventType(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPayoutAddress is only allowed on UpdateOne operations") + return v, errors.New("OldEventType is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPayoutAddress requires an ID field in the mutation") + return v, errors.New("OldEventType requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldPayoutAddress: %w", err) + return v, fmt.Errorf("querying old value for OldEventType: %w", err) } - return oldValue.PayoutAddress, nil -} - -// ClearPayoutAddress clears the value of the "payout_address" field. -func (m *ProviderOrderTokenMutation) ClearPayoutAddress() { - m.payout_address = nil - m.clearedFields[providerordertoken.FieldPayoutAddress] = struct{}{} -} - -// PayoutAddressCleared returns if the "payout_address" field was cleared in this mutation. -func (m *ProviderOrderTokenMutation) PayoutAddressCleared() bool { - _, ok := m.clearedFields[providerordertoken.FieldPayoutAddress] - return ok + return oldValue.EventType, nil } -// ResetPayoutAddress resets all changes to the "payout_address" field. -func (m *ProviderOrderTokenMutation) ResetPayoutAddress() { - m.payout_address = nil - delete(m.clearedFields, providerordertoken.FieldPayoutAddress) +// ResetEventType resets all changes to the "event_type" field. +func (m *ProviderOrderTokenScoreHistoryMutation) ResetEventType() { + m.event_type = nil } -// SetNetwork sets the "network" field. -func (m *ProviderOrderTokenMutation) SetNetwork(s string) { - m.network = &s +// SetDelta sets the "delta" field. +func (m *ProviderOrderTokenScoreHistoryMutation) SetDelta(d decimal.Decimal) { + m.delta = &d + m.adddelta = nil } -// Network returns the value of the "network" field in the mutation. -func (m *ProviderOrderTokenMutation) Network() (r string, exists bool) { - v := m.network +// Delta returns the value of the "delta" field in the mutation. +func (m *ProviderOrderTokenScoreHistoryMutation) Delta() (r decimal.Decimal, exists bool) { + v := m.delta if v == nil { return } return *v, true } -// OldNetwork returns the old "network" field's value of the ProviderOrderToken entity. -// If the ProviderOrderToken object wasn't provided to the builder, the object is fetched from the database. +// OldDelta returns the old "delta" field's value of the ProviderOrderTokenScoreHistory entity. +// If the ProviderOrderTokenScoreHistory object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *ProviderOrderTokenMutation) OldNetwork(ctx context.Context) (v string, err error) { +func (m *ProviderOrderTokenScoreHistoryMutation) OldDelta(ctx context.Context) (v decimal.Decimal, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldNetwork is only allowed on UpdateOne operations") + return v, errors.New("OldDelta is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldNetwork requires an ID field in the mutation") + return v, errors.New("OldDelta requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldNetwork: %w", err) + return v, fmt.Errorf("querying old value for OldDelta: %w", err) } - return oldValue.Network, nil -} - -// ResetNetwork resets all changes to the "network" field. -func (m *ProviderOrderTokenMutation) ResetNetwork() { - m.network = nil -} - -// SetProviderID sets the "provider" edge to the ProviderProfile entity by id. -func (m *ProviderOrderTokenMutation) SetProviderID(id string) { - m.provider = &id -} - -// ClearProvider clears the "provider" edge to the ProviderProfile entity. -func (m *ProviderOrderTokenMutation) ClearProvider() { - m.clearedprovider = true -} - -// ProviderCleared reports if the "provider" edge to the ProviderProfile entity was cleared. -func (m *ProviderOrderTokenMutation) ProviderCleared() bool { - return m.clearedprovider + return oldValue.Delta, nil } -// ProviderID returns the "provider" edge ID in the mutation. -func (m *ProviderOrderTokenMutation) ProviderID() (id string, exists bool) { - if m.provider != nil { - return *m.provider, true +// AddDelta adds d to the "delta" field. +func (m *ProviderOrderTokenScoreHistoryMutation) AddDelta(d decimal.Decimal) { + if m.adddelta != nil { + *m.adddelta = m.adddelta.Add(d) + } else { + m.adddelta = &d } - return } -// ProviderIDs returns the "provider" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// ProviderID instead. It exists only for internal usage by the builders. -func (m *ProviderOrderTokenMutation) ProviderIDs() (ids []string) { - if id := m.provider; id != nil { - ids = append(ids, *id) +// AddedDelta returns the value that was added to the "delta" field in this mutation. +func (m *ProviderOrderTokenScoreHistoryMutation) AddedDelta() (r decimal.Decimal, exists bool) { + v := m.adddelta + if v == nil { + return } - return + return *v, true } -// ResetProvider resets all changes to the "provider" edge. -func (m *ProviderOrderTokenMutation) ResetProvider() { - m.provider = nil - m.clearedprovider = false +// ResetDelta resets all changes to the "delta" field. +func (m *ProviderOrderTokenScoreHistoryMutation) ResetDelta() { + m.delta = nil + m.adddelta = nil } - -// SetTokenID sets the "token" edge to the Token entity by id. -func (m *ProviderOrderTokenMutation) SetTokenID(id int) { - m.token = &id + +// SetPaymentOrderID sets the "payment_order" edge to the PaymentOrder entity by id. +func (m *ProviderOrderTokenScoreHistoryMutation) SetPaymentOrderID(id uuid.UUID) { + m.payment_order = &id } -// ClearToken clears the "token" edge to the Token entity. -func (m *ProviderOrderTokenMutation) ClearToken() { - m.clearedtoken = true +// ClearPaymentOrder clears the "payment_order" edge to the PaymentOrder entity. +func (m *ProviderOrderTokenScoreHistoryMutation) ClearPaymentOrder() { + m.clearedpayment_order = true } -// TokenCleared reports if the "token" edge to the Token entity was cleared. -func (m *ProviderOrderTokenMutation) TokenCleared() bool { - return m.clearedtoken +// PaymentOrderCleared reports if the "payment_order" edge to the PaymentOrder entity was cleared. +func (m *ProviderOrderTokenScoreHistoryMutation) PaymentOrderCleared() bool { + return m.clearedpayment_order } -// TokenID returns the "token" edge ID in the mutation. -func (m *ProviderOrderTokenMutation) TokenID() (id int, exists bool) { - if m.token != nil { - return *m.token, true +// PaymentOrderID returns the "payment_order" edge ID in the mutation. +func (m *ProviderOrderTokenScoreHistoryMutation) PaymentOrderID() (id uuid.UUID, exists bool) { + if m.payment_order != nil { + return *m.payment_order, true } return } -// TokenIDs returns the "token" edge IDs in the mutation. +// PaymentOrderIDs returns the "payment_order" edge IDs in the mutation. // Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// TokenID instead. It exists only for internal usage by the builders. -func (m *ProviderOrderTokenMutation) TokenIDs() (ids []int) { - if id := m.token; id != nil { +// PaymentOrderID instead. It exists only for internal usage by the builders. +func (m *ProviderOrderTokenScoreHistoryMutation) PaymentOrderIDs() (ids []uuid.UUID) { + if id := m.payment_order; id != nil { ids = append(ids, *id) } return } -// ResetToken resets all changes to the "token" edge. -func (m *ProviderOrderTokenMutation) ResetToken() { - m.token = nil - m.clearedtoken = false +// ResetPaymentOrder resets all changes to the "payment_order" edge. +func (m *ProviderOrderTokenScoreHistoryMutation) ResetPaymentOrder() { + m.payment_order = nil + m.clearedpayment_order = false } -// SetCurrencyID sets the "currency" edge to the FiatCurrency entity by id. -func (m *ProviderOrderTokenMutation) SetCurrencyID(id uuid.UUID) { - m.currency = &id +// SetProviderOrderTokenID sets the "provider_order_token" edge to the ProviderOrderToken entity by id. +func (m *ProviderOrderTokenScoreHistoryMutation) SetProviderOrderTokenID(id int) { + m.provider_order_token = &id } -// ClearCurrency clears the "currency" edge to the FiatCurrency entity. -func (m *ProviderOrderTokenMutation) ClearCurrency() { - m.clearedcurrency = true +// ClearProviderOrderToken clears the "provider_order_token" edge to the ProviderOrderToken entity. +func (m *ProviderOrderTokenScoreHistoryMutation) ClearProviderOrderToken() { + m.clearedprovider_order_token = true } -// CurrencyCleared reports if the "currency" edge to the FiatCurrency entity was cleared. -func (m *ProviderOrderTokenMutation) CurrencyCleared() bool { - return m.clearedcurrency +// ProviderOrderTokenCleared reports if the "provider_order_token" edge to the ProviderOrderToken entity was cleared. +func (m *ProviderOrderTokenScoreHistoryMutation) ProviderOrderTokenCleared() bool { + return m.clearedprovider_order_token } -// CurrencyID returns the "currency" edge ID in the mutation. -func (m *ProviderOrderTokenMutation) CurrencyID() (id uuid.UUID, exists bool) { - if m.currency != nil { - return *m.currency, true +// ProviderOrderTokenID returns the "provider_order_token" edge ID in the mutation. +func (m *ProviderOrderTokenScoreHistoryMutation) ProviderOrderTokenID() (id int, exists bool) { + if m.provider_order_token != nil { + return *m.provider_order_token, true } return } -// CurrencyIDs returns the "currency" edge IDs in the mutation. +// ProviderOrderTokenIDs returns the "provider_order_token" edge IDs in the mutation. // Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// CurrencyID instead. It exists only for internal usage by the builders. -func (m *ProviderOrderTokenMutation) CurrencyIDs() (ids []uuid.UUID) { - if id := m.currency; id != nil { +// ProviderOrderTokenID instead. It exists only for internal usage by the builders. +func (m *ProviderOrderTokenScoreHistoryMutation) ProviderOrderTokenIDs() (ids []int) { + if id := m.provider_order_token; id != nil { ids = append(ids, *id) } return } -// ResetCurrency resets all changes to the "currency" edge. -func (m *ProviderOrderTokenMutation) ResetCurrency() { - m.currency = nil - m.clearedcurrency = false +// ResetProviderOrderToken resets all changes to the "provider_order_token" edge. +func (m *ProviderOrderTokenScoreHistoryMutation) ResetProviderOrderToken() { + m.provider_order_token = nil + m.clearedprovider_order_token = false } -// Where appends a list predicates to the ProviderOrderTokenMutation builder. -func (m *ProviderOrderTokenMutation) Where(ps ...predicate.ProviderOrderToken) { +// Where appends a list predicates to the ProviderOrderTokenScoreHistoryMutation builder. +func (m *ProviderOrderTokenScoreHistoryMutation) Where(ps ...predicate.ProviderOrderTokenScoreHistory) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the ProviderOrderTokenMutation builder. Using this method, +// WhereP appends storage-level predicates to the ProviderOrderTokenScoreHistoryMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *ProviderOrderTokenMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.ProviderOrderToken, len(ps)) +func (m *ProviderOrderTokenScoreHistoryMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ProviderOrderTokenScoreHistory, len(ps)) for i := range ps { p[i] = ps[i] } @@ -14002,281 +16644,117 @@ func (m *ProviderOrderTokenMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *ProviderOrderTokenMutation) Op() Op { +func (m *ProviderOrderTokenScoreHistoryMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *ProviderOrderTokenMutation) SetOp(op Op) { +func (m *ProviderOrderTokenScoreHistoryMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (ProviderOrderToken). -func (m *ProviderOrderTokenMutation) Type() string { +// Type returns the node type of this mutation (ProviderOrderTokenScoreHistory). +func (m *ProviderOrderTokenScoreHistoryMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). -func (m *ProviderOrderTokenMutation) Fields() []string { - fields := make([]string, 0, 14) +func (m *ProviderOrderTokenScoreHistoryMutation) Fields() []string { + fields := make([]string, 0, 4) if m.created_at != nil { - fields = append(fields, providerordertoken.FieldCreatedAt) + fields = append(fields, providerordertokenscorehistory.FieldCreatedAt) } if m.updated_at != nil { - fields = append(fields, providerordertoken.FieldUpdatedAt) - } - if m.fixed_buy_rate != nil { - fields = append(fields, providerordertoken.FieldFixedBuyRate) - } - if m.fixed_sell_rate != nil { - fields = append(fields, providerordertoken.FieldFixedSellRate) - } - if m.floating_buy_delta != nil { - fields = append(fields, providerordertoken.FieldFloatingBuyDelta) - } - if m.floating_sell_delta != nil { - fields = append(fields, providerordertoken.FieldFloatingSellDelta) - } - if m.max_order_amount != nil { - fields = append(fields, providerordertoken.FieldMaxOrderAmount) - } - if m.min_order_amount != nil { - fields = append(fields, providerordertoken.FieldMinOrderAmount) - } - if m.max_order_amount_otc != nil { - fields = append(fields, providerordertoken.FieldMaxOrderAmountOtc) - } - if m.min_order_amount_otc != nil { - fields = append(fields, providerordertoken.FieldMinOrderAmountOtc) - } - if m.rate_slippage != nil { - fields = append(fields, providerordertoken.FieldRateSlippage) - } - if m.settlement_address != nil { - fields = append(fields, providerordertoken.FieldSettlementAddress) - } - if m.payout_address != nil { - fields = append(fields, providerordertoken.FieldPayoutAddress) - } - if m.network != nil { - fields = append(fields, providerordertoken.FieldNetwork) - } - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *ProviderOrderTokenMutation) Field(name string) (ent.Value, bool) { - switch name { - case providerordertoken.FieldCreatedAt: - return m.CreatedAt() - case providerordertoken.FieldUpdatedAt: - return m.UpdatedAt() - case providerordertoken.FieldFixedBuyRate: - return m.FixedBuyRate() - case providerordertoken.FieldFixedSellRate: - return m.FixedSellRate() - case providerordertoken.FieldFloatingBuyDelta: - return m.FloatingBuyDelta() - case providerordertoken.FieldFloatingSellDelta: - return m.FloatingSellDelta() - case providerordertoken.FieldMaxOrderAmount: - return m.MaxOrderAmount() - case providerordertoken.FieldMinOrderAmount: - return m.MinOrderAmount() - case providerordertoken.FieldMaxOrderAmountOtc: - return m.MaxOrderAmountOtc() - case providerordertoken.FieldMinOrderAmountOtc: - return m.MinOrderAmountOtc() - case providerordertoken.FieldRateSlippage: - return m.RateSlippage() - case providerordertoken.FieldSettlementAddress: - return m.SettlementAddress() - case providerordertoken.FieldPayoutAddress: - return m.PayoutAddress() - case providerordertoken.FieldNetwork: - return m.Network() + fields = append(fields, providerordertokenscorehistory.FieldUpdatedAt) } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *ProviderOrderTokenMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case providerordertoken.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case providerordertoken.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - case providerordertoken.FieldFixedBuyRate: - return m.OldFixedBuyRate(ctx) - case providerordertoken.FieldFixedSellRate: - return m.OldFixedSellRate(ctx) - case providerordertoken.FieldFloatingBuyDelta: - return m.OldFloatingBuyDelta(ctx) - case providerordertoken.FieldFloatingSellDelta: - return m.OldFloatingSellDelta(ctx) - case providerordertoken.FieldMaxOrderAmount: - return m.OldMaxOrderAmount(ctx) - case providerordertoken.FieldMinOrderAmount: - return m.OldMinOrderAmount(ctx) - case providerordertoken.FieldMaxOrderAmountOtc: - return m.OldMaxOrderAmountOtc(ctx) - case providerordertoken.FieldMinOrderAmountOtc: - return m.OldMinOrderAmountOtc(ctx) - case providerordertoken.FieldRateSlippage: - return m.OldRateSlippage(ctx) - case providerordertoken.FieldSettlementAddress: - return m.OldSettlementAddress(ctx) - case providerordertoken.FieldPayoutAddress: - return m.OldPayoutAddress(ctx) - case providerordertoken.FieldNetwork: - return m.OldNetwork(ctx) + if m.event_type != nil { + fields = append(fields, providerordertokenscorehistory.FieldEventType) } - return nil, fmt.Errorf("unknown ProviderOrderToken field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *ProviderOrderTokenMutation) SetField(name string, value ent.Value) error { - switch name { - case providerordertoken.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - case providerordertoken.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil - case providerordertoken.FieldFixedBuyRate: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetFixedBuyRate(v) - return nil - case providerordertoken.FieldFixedSellRate: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetFixedSellRate(v) - return nil - case providerordertoken.FieldFloatingBuyDelta: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetFloatingBuyDelta(v) - return nil - case providerordertoken.FieldFloatingSellDelta: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetFloatingSellDelta(v) - return nil - case providerordertoken.FieldMaxOrderAmount: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMaxOrderAmount(v) - return nil - case providerordertoken.FieldMinOrderAmount: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMinOrderAmount(v) - return nil - case providerordertoken.FieldMaxOrderAmountOtc: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMaxOrderAmountOtc(v) - return nil - case providerordertoken.FieldMinOrderAmountOtc: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMinOrderAmountOtc(v) - return nil - case providerordertoken.FieldRateSlippage: - v, ok := value.(decimal.Decimal) + if m.delta != nil { + fields = append(fields, providerordertokenscorehistory.FieldDelta) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *ProviderOrderTokenScoreHistoryMutation) Field(name string) (ent.Value, bool) { + switch name { + case providerordertokenscorehistory.FieldCreatedAt: + return m.CreatedAt() + case providerordertokenscorehistory.FieldUpdatedAt: + return m.UpdatedAt() + case providerordertokenscorehistory.FieldEventType: + return m.EventType() + case providerordertokenscorehistory.FieldDelta: + return m.Delta() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *ProviderOrderTokenScoreHistoryMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case providerordertokenscorehistory.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case providerordertokenscorehistory.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case providerordertokenscorehistory.FieldEventType: + return m.OldEventType(ctx) + case providerordertokenscorehistory.FieldDelta: + return m.OldDelta(ctx) + } + return nil, fmt.Errorf("unknown ProviderOrderTokenScoreHistory field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ProviderOrderTokenScoreHistoryMutation) SetField(name string, value ent.Value) error { + switch name { + case providerordertokenscorehistory.FieldCreatedAt: + v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetRateSlippage(v) + m.SetCreatedAt(v) return nil - case providerordertoken.FieldSettlementAddress: - v, ok := value.(string) + case providerordertokenscorehistory.FieldUpdatedAt: + v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetSettlementAddress(v) + m.SetUpdatedAt(v) return nil - case providerordertoken.FieldPayoutAddress: + case providerordertokenscorehistory.FieldEventType: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetPayoutAddress(v) + m.SetEventType(v) return nil - case providerordertoken.FieldNetwork: - v, ok := value.(string) + case providerordertokenscorehistory.FieldDelta: + v, ok := value.(decimal.Decimal) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetNetwork(v) + m.SetDelta(v) return nil } - return fmt.Errorf("unknown ProviderOrderToken field %s", name) + return fmt.Errorf("unknown ProviderOrderTokenScoreHistory field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *ProviderOrderTokenMutation) AddedFields() []string { +func (m *ProviderOrderTokenScoreHistoryMutation) AddedFields() []string { var fields []string - if m.addfixed_buy_rate != nil { - fields = append(fields, providerordertoken.FieldFixedBuyRate) - } - if m.addfixed_sell_rate != nil { - fields = append(fields, providerordertoken.FieldFixedSellRate) - } - if m.addfloating_buy_delta != nil { - fields = append(fields, providerordertoken.FieldFloatingBuyDelta) - } - if m.addfloating_sell_delta != nil { - fields = append(fields, providerordertoken.FieldFloatingSellDelta) - } - if m.addmax_order_amount != nil { - fields = append(fields, providerordertoken.FieldMaxOrderAmount) - } - if m.addmin_order_amount != nil { - fields = append(fields, providerordertoken.FieldMinOrderAmount) - } - if m.addmax_order_amount_otc != nil { - fields = append(fields, providerordertoken.FieldMaxOrderAmountOtc) - } - if m.addmin_order_amount_otc != nil { - fields = append(fields, providerordertoken.FieldMinOrderAmountOtc) - } - if m.addrate_slippage != nil { - fields = append(fields, providerordertoken.FieldRateSlippage) + if m.adddelta != nil { + fields = append(fields, providerordertokenscorehistory.FieldDelta) } return fields } @@ -14284,26 +16762,10 @@ func (m *ProviderOrderTokenMutation) AddedFields() []string { // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *ProviderOrderTokenMutation) AddedField(name string) (ent.Value, bool) { +func (m *ProviderOrderTokenScoreHistoryMutation) AddedField(name string) (ent.Value, bool) { switch name { - case providerordertoken.FieldFixedBuyRate: - return m.AddedFixedBuyRate() - case providerordertoken.FieldFixedSellRate: - return m.AddedFixedSellRate() - case providerordertoken.FieldFloatingBuyDelta: - return m.AddedFloatingBuyDelta() - case providerordertoken.FieldFloatingSellDelta: - return m.AddedFloatingSellDelta() - case providerordertoken.FieldMaxOrderAmount: - return m.AddedMaxOrderAmount() - case providerordertoken.FieldMinOrderAmount: - return m.AddedMinOrderAmount() - case providerordertoken.FieldMaxOrderAmountOtc: - return m.AddedMaxOrderAmountOtc() - case providerordertoken.FieldMinOrderAmountOtc: - return m.AddedMinOrderAmountOtc() - case providerordertoken.FieldRateSlippage: - return m.AddedRateSlippage() + case providerordertokenscorehistory.FieldDelta: + return m.AddedDelta() } return nil, false } @@ -14311,212 +16773,80 @@ func (m *ProviderOrderTokenMutation) AddedField(name string) (ent.Value, bool) { // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *ProviderOrderTokenMutation) AddField(name string, value ent.Value) error { +func (m *ProviderOrderTokenScoreHistoryMutation) AddField(name string, value ent.Value) error { switch name { - case providerordertoken.FieldFixedBuyRate: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddFixedBuyRate(v) - return nil - case providerordertoken.FieldFixedSellRate: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddFixedSellRate(v) - return nil - case providerordertoken.FieldFloatingBuyDelta: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddFloatingBuyDelta(v) - return nil - case providerordertoken.FieldFloatingSellDelta: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddFloatingSellDelta(v) - return nil - case providerordertoken.FieldMaxOrderAmount: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddMaxOrderAmount(v) - return nil - case providerordertoken.FieldMinOrderAmount: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddMinOrderAmount(v) - return nil - case providerordertoken.FieldMaxOrderAmountOtc: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddMaxOrderAmountOtc(v) - return nil - case providerordertoken.FieldMinOrderAmountOtc: - v, ok := value.(decimal.Decimal) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddMinOrderAmountOtc(v) - return nil - case providerordertoken.FieldRateSlippage: + case providerordertokenscorehistory.FieldDelta: v, ok := value.(decimal.Decimal) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.AddRateSlippage(v) + m.AddDelta(v) return nil } - return fmt.Errorf("unknown ProviderOrderToken numeric field %s", name) + return fmt.Errorf("unknown ProviderOrderTokenScoreHistory numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *ProviderOrderTokenMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(providerordertoken.FieldFixedBuyRate) { - fields = append(fields, providerordertoken.FieldFixedBuyRate) - } - if m.FieldCleared(providerordertoken.FieldFixedSellRate) { - fields = append(fields, providerordertoken.FieldFixedSellRate) - } - if m.FieldCleared(providerordertoken.FieldFloatingBuyDelta) { - fields = append(fields, providerordertoken.FieldFloatingBuyDelta) - } - if m.FieldCleared(providerordertoken.FieldFloatingSellDelta) { - fields = append(fields, providerordertoken.FieldFloatingSellDelta) - } - if m.FieldCleared(providerordertoken.FieldSettlementAddress) { - fields = append(fields, providerordertoken.FieldSettlementAddress) - } - if m.FieldCleared(providerordertoken.FieldPayoutAddress) { - fields = append(fields, providerordertoken.FieldPayoutAddress) - } - return fields +func (m *ProviderOrderTokenScoreHistoryMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *ProviderOrderTokenMutation) FieldCleared(name string) bool { +func (m *ProviderOrderTokenScoreHistoryMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. -func (m *ProviderOrderTokenMutation) ClearField(name string) error { - switch name { - case providerordertoken.FieldFixedBuyRate: - m.ClearFixedBuyRate() - return nil - case providerordertoken.FieldFixedSellRate: - m.ClearFixedSellRate() - return nil - case providerordertoken.FieldFloatingBuyDelta: - m.ClearFloatingBuyDelta() - return nil - case providerordertoken.FieldFloatingSellDelta: - m.ClearFloatingSellDelta() - return nil - case providerordertoken.FieldSettlementAddress: - m.ClearSettlementAddress() - return nil - case providerordertoken.FieldPayoutAddress: - m.ClearPayoutAddress() - return nil - } - return fmt.Errorf("unknown ProviderOrderToken nullable field %s", name) +func (m *ProviderOrderTokenScoreHistoryMutation) ClearField(name string) error { + return fmt.Errorf("unknown ProviderOrderTokenScoreHistory nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *ProviderOrderTokenMutation) ResetField(name string) error { +func (m *ProviderOrderTokenScoreHistoryMutation) ResetField(name string) error { switch name { - case providerordertoken.FieldCreatedAt: + case providerordertokenscorehistory.FieldCreatedAt: m.ResetCreatedAt() return nil - case providerordertoken.FieldUpdatedAt: + case providerordertokenscorehistory.FieldUpdatedAt: m.ResetUpdatedAt() return nil - case providerordertoken.FieldFixedBuyRate: - m.ResetFixedBuyRate() - return nil - case providerordertoken.FieldFixedSellRate: - m.ResetFixedSellRate() - return nil - case providerordertoken.FieldFloatingBuyDelta: - m.ResetFloatingBuyDelta() - return nil - case providerordertoken.FieldFloatingSellDelta: - m.ResetFloatingSellDelta() - return nil - case providerordertoken.FieldMaxOrderAmount: - m.ResetMaxOrderAmount() - return nil - case providerordertoken.FieldMinOrderAmount: - m.ResetMinOrderAmount() - return nil - case providerordertoken.FieldMaxOrderAmountOtc: - m.ResetMaxOrderAmountOtc() - return nil - case providerordertoken.FieldMinOrderAmountOtc: - m.ResetMinOrderAmountOtc() - return nil - case providerordertoken.FieldRateSlippage: - m.ResetRateSlippage() - return nil - case providerordertoken.FieldSettlementAddress: - m.ResetSettlementAddress() - return nil - case providerordertoken.FieldPayoutAddress: - m.ResetPayoutAddress() + case providerordertokenscorehistory.FieldEventType: + m.ResetEventType() return nil - case providerordertoken.FieldNetwork: - m.ResetNetwork() + case providerordertokenscorehistory.FieldDelta: + m.ResetDelta() return nil } - return fmt.Errorf("unknown ProviderOrderToken field %s", name) + return fmt.Errorf("unknown ProviderOrderTokenScoreHistory field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *ProviderOrderTokenMutation) AddedEdges() []string { - edges := make([]string, 0, 3) - if m.provider != nil { - edges = append(edges, providerordertoken.EdgeProvider) - } - if m.token != nil { - edges = append(edges, providerordertoken.EdgeToken) +func (m *ProviderOrderTokenScoreHistoryMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.payment_order != nil { + edges = append(edges, providerordertokenscorehistory.EdgePaymentOrder) } - if m.currency != nil { - edges = append(edges, providerordertoken.EdgeCurrency) + if m.provider_order_token != nil { + edges = append(edges, providerordertokenscorehistory.EdgeProviderOrderToken) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *ProviderOrderTokenMutation) AddedIDs(name string) []ent.Value { +func (m *ProviderOrderTokenScoreHistoryMutation) AddedIDs(name string) []ent.Value { switch name { - case providerordertoken.EdgeProvider: - if id := m.provider; id != nil { - return []ent.Value{*id} - } - case providerordertoken.EdgeToken: - if id := m.token; id != nil { + case providerordertokenscorehistory.EdgePaymentOrder: + if id := m.payment_order; id != nil { return []ent.Value{*id} } - case providerordertoken.EdgeCurrency: - if id := m.currency; id != nil { + case providerordertokenscorehistory.EdgeProviderOrderToken: + if id := m.provider_order_token; id != nil { return []ent.Value{*id} } } @@ -14524,78 +16854,67 @@ func (m *ProviderOrderTokenMutation) AddedIDs(name string) []ent.Value { } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *ProviderOrderTokenMutation) RemovedEdges() []string { - edges := make([]string, 0, 3) +func (m *ProviderOrderTokenScoreHistoryMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *ProviderOrderTokenMutation) RemovedIDs(name string) []ent.Value { +func (m *ProviderOrderTokenScoreHistoryMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *ProviderOrderTokenMutation) ClearedEdges() []string { - edges := make([]string, 0, 3) - if m.clearedprovider { - edges = append(edges, providerordertoken.EdgeProvider) - } - if m.clearedtoken { - edges = append(edges, providerordertoken.EdgeToken) +func (m *ProviderOrderTokenScoreHistoryMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedpayment_order { + edges = append(edges, providerordertokenscorehistory.EdgePaymentOrder) } - if m.clearedcurrency { - edges = append(edges, providerordertoken.EdgeCurrency) + if m.clearedprovider_order_token { + edges = append(edges, providerordertokenscorehistory.EdgeProviderOrderToken) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *ProviderOrderTokenMutation) EdgeCleared(name string) bool { +func (m *ProviderOrderTokenScoreHistoryMutation) EdgeCleared(name string) bool { switch name { - case providerordertoken.EdgeProvider: - return m.clearedprovider - case providerordertoken.EdgeToken: - return m.clearedtoken - case providerordertoken.EdgeCurrency: - return m.clearedcurrency + case providerordertokenscorehistory.EdgePaymentOrder: + return m.clearedpayment_order + case providerordertokenscorehistory.EdgeProviderOrderToken: + return m.clearedprovider_order_token } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *ProviderOrderTokenMutation) ClearEdge(name string) error { +func (m *ProviderOrderTokenScoreHistoryMutation) ClearEdge(name string) error { switch name { - case providerordertoken.EdgeProvider: - m.ClearProvider() - return nil - case providerordertoken.EdgeToken: - m.ClearToken() + case providerordertokenscorehistory.EdgePaymentOrder: + m.ClearPaymentOrder() return nil - case providerordertoken.EdgeCurrency: - m.ClearCurrency() + case providerordertokenscorehistory.EdgeProviderOrderToken: + m.ClearProviderOrderToken() return nil } - return fmt.Errorf("unknown ProviderOrderToken unique edge %s", name) + return fmt.Errorf("unknown ProviderOrderTokenScoreHistory unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *ProviderOrderTokenMutation) ResetEdge(name string) error { +func (m *ProviderOrderTokenScoreHistoryMutation) ResetEdge(name string) error { switch name { - case providerordertoken.EdgeProvider: - m.ResetProvider() - return nil - case providerordertoken.EdgeToken: - m.ResetToken() + case providerordertokenscorehistory.EdgePaymentOrder: + m.ResetPaymentOrder() return nil - case providerordertoken.EdgeCurrency: - m.ResetCurrency() + case providerordertokenscorehistory.EdgeProviderOrderToken: + m.ResetProviderOrderToken() return nil } - return fmt.Errorf("unknown ProviderOrderToken edge %s", name) + return fmt.Errorf("unknown ProviderOrderTokenScoreHistory edge %s", name) } // ProviderProfileMutation represents an operation that mutates the ProviderProfile nodes in the graph. @@ -14618,9 +16937,6 @@ type ProviderProfileMutation struct { provider_balances map[uuid.UUID]struct{} removedprovider_balances map[uuid.UUID]struct{} clearedprovider_balances bool - provision_buckets map[int]struct{} - removedprovision_buckets map[int]struct{} - clearedprovision_buckets bool order_tokens map[int]struct{} removedorder_tokens map[int]struct{} clearedorder_tokens bool @@ -15115,60 +17431,6 @@ func (m *ProviderProfileMutation) ResetProviderBalances() { m.removedprovider_balances = nil } -// AddProvisionBucketIDs adds the "provision_buckets" edge to the ProvisionBucket entity by ids. -func (m *ProviderProfileMutation) AddProvisionBucketIDs(ids ...int) { - if m.provision_buckets == nil { - m.provision_buckets = make(map[int]struct{}) - } - for i := range ids { - m.provision_buckets[ids[i]] = struct{}{} - } -} - -// ClearProvisionBuckets clears the "provision_buckets" edge to the ProvisionBucket entity. -func (m *ProviderProfileMutation) ClearProvisionBuckets() { - m.clearedprovision_buckets = true -} - -// ProvisionBucketsCleared reports if the "provision_buckets" edge to the ProvisionBucket entity was cleared. -func (m *ProviderProfileMutation) ProvisionBucketsCleared() bool { - return m.clearedprovision_buckets -} - -// RemoveProvisionBucketIDs removes the "provision_buckets" edge to the ProvisionBucket entity by IDs. -func (m *ProviderProfileMutation) RemoveProvisionBucketIDs(ids ...int) { - if m.removedprovision_buckets == nil { - m.removedprovision_buckets = make(map[int]struct{}) - } - for i := range ids { - delete(m.provision_buckets, ids[i]) - m.removedprovision_buckets[ids[i]] = struct{}{} - } -} - -// RemovedProvisionBuckets returns the removed IDs of the "provision_buckets" edge to the ProvisionBucket entity. -func (m *ProviderProfileMutation) RemovedProvisionBucketsIDs() (ids []int) { - for id := range m.removedprovision_buckets { - ids = append(ids, id) - } - return -} - -// ProvisionBucketsIDs returns the "provision_buckets" edge IDs in the mutation. -func (m *ProviderProfileMutation) ProvisionBucketsIDs() (ids []int) { - for id := range m.provision_buckets { - ids = append(ids, id) - } - return -} - -// ResetProvisionBuckets resets all changes to the "provision_buckets" edge. -func (m *ProviderProfileMutation) ResetProvisionBuckets() { - m.provision_buckets = nil - m.clearedprovision_buckets = false - m.removedprovision_buckets = nil -} - // AddOrderTokenIDs adds the "order_tokens" edge to the ProviderOrderToken entity by ids. func (m *ProviderProfileMutation) AddOrderTokenIDs(ids ...int) { if m.order_tokens == nil { @@ -15603,7 +17865,7 @@ func (m *ProviderProfileMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *ProviderProfileMutation) AddedEdges() []string { - edges := make([]string, 0, 8) + edges := make([]string, 0, 7) if m.user != nil { edges = append(edges, providerprofile.EdgeUser) } @@ -15613,9 +17875,6 @@ func (m *ProviderProfileMutation) AddedEdges() []string { if m.provider_balances != nil { edges = append(edges, providerprofile.EdgeProviderBalances) } - if m.provision_buckets != nil { - edges = append(edges, providerprofile.EdgeProvisionBuckets) - } if m.order_tokens != nil { edges = append(edges, providerprofile.EdgeOrderTokens) } @@ -15649,12 +17908,6 @@ func (m *ProviderProfileMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids - case providerprofile.EdgeProvisionBuckets: - ids := make([]ent.Value, 0, len(m.provision_buckets)) - for id := range m.provision_buckets { - ids = append(ids, id) - } - return ids case providerprofile.EdgeOrderTokens: ids := make([]ent.Value, 0, len(m.order_tokens)) for id := range m.order_tokens { @@ -15683,13 +17936,10 @@ func (m *ProviderProfileMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *ProviderProfileMutation) RemovedEdges() []string { - edges := make([]string, 0, 8) + edges := make([]string, 0, 7) if m.removedprovider_balances != nil { edges = append(edges, providerprofile.EdgeProviderBalances) } - if m.removedprovision_buckets != nil { - edges = append(edges, providerprofile.EdgeProvisionBuckets) - } if m.removedorder_tokens != nil { edges = append(edges, providerprofile.EdgeOrderTokens) } @@ -15712,12 +17962,6 @@ func (m *ProviderProfileMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids - case providerprofile.EdgeProvisionBuckets: - ids := make([]ent.Value, 0, len(m.removedprovision_buckets)) - for id := range m.removedprovision_buckets { - ids = append(ids, id) - } - return ids case providerprofile.EdgeOrderTokens: ids := make([]ent.Value, 0, len(m.removedorder_tokens)) for id := range m.removedorder_tokens { @@ -15742,7 +17986,7 @@ func (m *ProviderProfileMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *ProviderProfileMutation) ClearedEdges() []string { - edges := make([]string, 0, 8) + edges := make([]string, 0, 7) if m.cleareduser { edges = append(edges, providerprofile.EdgeUser) } @@ -15752,9 +17996,6 @@ func (m *ProviderProfileMutation) ClearedEdges() []string { if m.clearedprovider_balances { edges = append(edges, providerprofile.EdgeProviderBalances) } - if m.clearedprovision_buckets { - edges = append(edges, providerprofile.EdgeProvisionBuckets) - } if m.clearedorder_tokens { edges = append(edges, providerprofile.EdgeOrderTokens) } @@ -15780,8 +18021,6 @@ func (m *ProviderProfileMutation) EdgeCleared(name string) bool { return m.clearedapi_key case providerprofile.EdgeProviderBalances: return m.clearedprovider_balances - case providerprofile.EdgeProvisionBuckets: - return m.clearedprovision_buckets case providerprofile.EdgeOrderTokens: return m.clearedorder_tokens case providerprofile.EdgeProviderRating: @@ -15824,9 +18063,6 @@ func (m *ProviderProfileMutation) ResetEdge(name string) error { case providerprofile.EdgeProviderBalances: m.ResetProviderBalances() return nil - case providerprofile.EdgeProvisionBuckets: - m.ResetProvisionBuckets() - return nil case providerprofile.EdgeOrderTokens: m.ResetOrderTokens() return nil @@ -16383,26 +18619,19 @@ func (m *ProviderRatingMutation) ResetEdge(name string) error { // ProvisionBucketMutation represents an operation that mutates the ProvisionBucket nodes in the graph. type ProvisionBucketMutation struct { config - op Op - typ string - id *int - min_amount *decimal.Decimal - addmin_amount *decimal.Decimal - max_amount *decimal.Decimal - addmax_amount *decimal.Decimal - created_at *time.Time - clearedFields map[string]struct{} - currency *uuid.UUID - clearedcurrency bool - payment_orders map[uuid.UUID]struct{} - removedpayment_orders map[uuid.UUID]struct{} - clearedpayment_orders bool - provider_profiles map[string]struct{} - removedprovider_profiles map[string]struct{} - clearedprovider_profiles bool - done bool - oldValue func(context.Context) (*ProvisionBucket, error) - predicates []predicate.ProvisionBucket + op Op + typ string + id *int + min_amount *decimal.Decimal + addmin_amount *decimal.Decimal + max_amount *decimal.Decimal + addmax_amount *decimal.Decimal + created_at *time.Time + fiat_currency_id *uuid.UUID + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*ProvisionBucket, error) + predicates []predicate.ProvisionBucket } var _ ent.Mutation = (*ProvisionBucketMutation)(nil) @@ -16651,151 +18880,53 @@ func (m *ProvisionBucketMutation) ResetCreatedAt() { m.created_at = nil } -// SetCurrencyID sets the "currency" edge to the FiatCurrency entity by id. -func (m *ProvisionBucketMutation) SetCurrencyID(id uuid.UUID) { - m.currency = &id -} - -// ClearCurrency clears the "currency" edge to the FiatCurrency entity. -func (m *ProvisionBucketMutation) ClearCurrency() { - m.clearedcurrency = true -} - -// CurrencyCleared reports if the "currency" edge to the FiatCurrency entity was cleared. -func (m *ProvisionBucketMutation) CurrencyCleared() bool { - return m.clearedcurrency -} - -// CurrencyID returns the "currency" edge ID in the mutation. -func (m *ProvisionBucketMutation) CurrencyID() (id uuid.UUID, exists bool) { - if m.currency != nil { - return *m.currency, true - } - return -} - -// CurrencyIDs returns the "currency" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// CurrencyID instead. It exists only for internal usage by the builders. -func (m *ProvisionBucketMutation) CurrencyIDs() (ids []uuid.UUID) { - if id := m.currency; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetCurrency resets all changes to the "currency" edge. -func (m *ProvisionBucketMutation) ResetCurrency() { - m.currency = nil - m.clearedcurrency = false -} - -// AddPaymentOrderIDs adds the "payment_orders" edge to the PaymentOrder entity by ids. -func (m *ProvisionBucketMutation) AddPaymentOrderIDs(ids ...uuid.UUID) { - if m.payment_orders == nil { - m.payment_orders = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.payment_orders[ids[i]] = struct{}{} - } -} - -// ClearPaymentOrders clears the "payment_orders" edge to the PaymentOrder entity. -func (m *ProvisionBucketMutation) ClearPaymentOrders() { - m.clearedpayment_orders = true -} - -// PaymentOrdersCleared reports if the "payment_orders" edge to the PaymentOrder entity was cleared. -func (m *ProvisionBucketMutation) PaymentOrdersCleared() bool { - return m.clearedpayment_orders -} - -// RemovePaymentOrderIDs removes the "payment_orders" edge to the PaymentOrder entity by IDs. -func (m *ProvisionBucketMutation) RemovePaymentOrderIDs(ids ...uuid.UUID) { - if m.removedpayment_orders == nil { - m.removedpayment_orders = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.payment_orders, ids[i]) - m.removedpayment_orders[ids[i]] = struct{}{} - } -} - -// RemovedPaymentOrders returns the removed IDs of the "payment_orders" edge to the PaymentOrder entity. -func (m *ProvisionBucketMutation) RemovedPaymentOrdersIDs() (ids []uuid.UUID) { - for id := range m.removedpayment_orders { - ids = append(ids, id) - } - return +// SetFiatCurrencyID sets the "fiat_currency_id" field. +func (m *ProvisionBucketMutation) SetFiatCurrencyID(u uuid.UUID) { + m.fiat_currency_id = &u } -// PaymentOrdersIDs returns the "payment_orders" edge IDs in the mutation. -func (m *ProvisionBucketMutation) PaymentOrdersIDs() (ids []uuid.UUID) { - for id := range m.payment_orders { - ids = append(ids, id) +// FiatCurrencyID returns the value of the "fiat_currency_id" field in the mutation. +func (m *ProvisionBucketMutation) FiatCurrencyID() (r uuid.UUID, exists bool) { + v := m.fiat_currency_id + if v == nil { + return } - return -} - -// ResetPaymentOrders resets all changes to the "payment_orders" edge. -func (m *ProvisionBucketMutation) ResetPaymentOrders() { - m.payment_orders = nil - m.clearedpayment_orders = false - m.removedpayment_orders = nil + return *v, true } -// AddProviderProfileIDs adds the "provider_profiles" edge to the ProviderProfile entity by ids. -func (m *ProvisionBucketMutation) AddProviderProfileIDs(ids ...string) { - if m.provider_profiles == nil { - m.provider_profiles = make(map[string]struct{}) - } - for i := range ids { - m.provider_profiles[ids[i]] = struct{}{} +// OldFiatCurrencyID returns the old "fiat_currency_id" field's value of the ProvisionBucket entity. +// If the ProvisionBucket object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ProvisionBucketMutation) OldFiatCurrencyID(ctx context.Context) (v *uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFiatCurrencyID is only allowed on UpdateOne operations") } -} - -// ClearProviderProfiles clears the "provider_profiles" edge to the ProviderProfile entity. -func (m *ProvisionBucketMutation) ClearProviderProfiles() { - m.clearedprovider_profiles = true -} - -// ProviderProfilesCleared reports if the "provider_profiles" edge to the ProviderProfile entity was cleared. -func (m *ProvisionBucketMutation) ProviderProfilesCleared() bool { - return m.clearedprovider_profiles -} - -// RemoveProviderProfileIDs removes the "provider_profiles" edge to the ProviderProfile entity by IDs. -func (m *ProvisionBucketMutation) RemoveProviderProfileIDs(ids ...string) { - if m.removedprovider_profiles == nil { - m.removedprovider_profiles = make(map[string]struct{}) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFiatCurrencyID requires an ID field in the mutation") } - for i := range ids { - delete(m.provider_profiles, ids[i]) - m.removedprovider_profiles[ids[i]] = struct{}{} + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFiatCurrencyID: %w", err) } + return oldValue.FiatCurrencyID, nil } -// RemovedProviderProfiles returns the removed IDs of the "provider_profiles" edge to the ProviderProfile entity. -func (m *ProvisionBucketMutation) RemovedProviderProfilesIDs() (ids []string) { - for id := range m.removedprovider_profiles { - ids = append(ids, id) - } - return +// ClearFiatCurrencyID clears the value of the "fiat_currency_id" field. +func (m *ProvisionBucketMutation) ClearFiatCurrencyID() { + m.fiat_currency_id = nil + m.clearedFields[provisionbucket.FieldFiatCurrencyID] = struct{}{} } -// ProviderProfilesIDs returns the "provider_profiles" edge IDs in the mutation. -func (m *ProvisionBucketMutation) ProviderProfilesIDs() (ids []string) { - for id := range m.provider_profiles { - ids = append(ids, id) - } - return +// FiatCurrencyIDCleared returns if the "fiat_currency_id" field was cleared in this mutation. +func (m *ProvisionBucketMutation) FiatCurrencyIDCleared() bool { + _, ok := m.clearedFields[provisionbucket.FieldFiatCurrencyID] + return ok } -// ResetProviderProfiles resets all changes to the "provider_profiles" edge. -func (m *ProvisionBucketMutation) ResetProviderProfiles() { - m.provider_profiles = nil - m.clearedprovider_profiles = false - m.removedprovider_profiles = nil +// ResetFiatCurrencyID resets all changes to the "fiat_currency_id" field. +func (m *ProvisionBucketMutation) ResetFiatCurrencyID() { + m.fiat_currency_id = nil + delete(m.clearedFields, provisionbucket.FieldFiatCurrencyID) } // Where appends a list predicates to the ProvisionBucketMutation builder. @@ -16832,7 +18963,7 @@ func (m *ProvisionBucketMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *ProvisionBucketMutation) Fields() []string { - fields := make([]string, 0, 3) + fields := make([]string, 0, 4) if m.min_amount != nil { fields = append(fields, provisionbucket.FieldMinAmount) } @@ -16842,6 +18973,9 @@ func (m *ProvisionBucketMutation) Fields() []string { if m.created_at != nil { fields = append(fields, provisionbucket.FieldCreatedAt) } + if m.fiat_currency_id != nil { + fields = append(fields, provisionbucket.FieldFiatCurrencyID) + } return fields } @@ -16856,6 +18990,8 @@ func (m *ProvisionBucketMutation) Field(name string) (ent.Value, bool) { return m.MaxAmount() case provisionbucket.FieldCreatedAt: return m.CreatedAt() + case provisionbucket.FieldFiatCurrencyID: + return m.FiatCurrencyID() } return nil, false } @@ -16871,6 +19007,8 @@ func (m *ProvisionBucketMutation) OldField(ctx context.Context, name string) (en return m.OldMaxAmount(ctx) case provisionbucket.FieldCreatedAt: return m.OldCreatedAt(ctx) + case provisionbucket.FieldFiatCurrencyID: + return m.OldFiatCurrencyID(ctx) } return nil, fmt.Errorf("unknown ProvisionBucket field %s", name) } @@ -16901,6 +19039,13 @@ func (m *ProvisionBucketMutation) SetField(name string, value ent.Value) error { } m.SetCreatedAt(v) return nil + case provisionbucket.FieldFiatCurrencyID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFiatCurrencyID(v) + return nil } return fmt.Errorf("unknown ProvisionBucket field %s", name) } @@ -16957,7 +19102,11 @@ func (m *ProvisionBucketMutation) AddField(name string, value ent.Value) error { // ClearedFields returns all nullable fields that were cleared during this // mutation. func (m *ProvisionBucketMutation) ClearedFields() []string { - return nil + var fields []string + if m.FieldCleared(provisionbucket.FieldFiatCurrencyID) { + fields = append(fields, provisionbucket.FieldFiatCurrencyID) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was @@ -16970,6 +19119,11 @@ func (m *ProvisionBucketMutation) FieldCleared(name string) bool { // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *ProvisionBucketMutation) ClearField(name string) error { + switch name { + case provisionbucket.FieldFiatCurrencyID: + m.ClearFiatCurrencyID() + return nil + } return fmt.Errorf("unknown ProvisionBucket nullable field %s", name) } @@ -16986,135 +19140,58 @@ func (m *ProvisionBucketMutation) ResetField(name string) error { case provisionbucket.FieldCreatedAt: m.ResetCreatedAt() return nil + case provisionbucket.FieldFiatCurrencyID: + m.ResetFiatCurrencyID() + return nil } return fmt.Errorf("unknown ProvisionBucket field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. func (m *ProvisionBucketMutation) AddedEdges() []string { - edges := make([]string, 0, 3) - if m.currency != nil { - edges = append(edges, provisionbucket.EdgeCurrency) - } - if m.payment_orders != nil { - edges = append(edges, provisionbucket.EdgePaymentOrders) - } - if m.provider_profiles != nil { - edges = append(edges, provisionbucket.EdgeProviderProfiles) - } + edges := make([]string, 0, 0) return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. func (m *ProvisionBucketMutation) AddedIDs(name string) []ent.Value { - switch name { - case provisionbucket.EdgeCurrency: - if id := m.currency; id != nil { - return []ent.Value{*id} - } - case provisionbucket.EdgePaymentOrders: - ids := make([]ent.Value, 0, len(m.payment_orders)) - for id := range m.payment_orders { - ids = append(ids, id) - } - return ids - case provisionbucket.EdgeProviderProfiles: - ids := make([]ent.Value, 0, len(m.provider_profiles)) - for id := range m.provider_profiles { - ids = append(ids, id) - } - return ids - } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *ProvisionBucketMutation) RemovedEdges() []string { - edges := make([]string, 0, 3) - if m.removedpayment_orders != nil { - edges = append(edges, provisionbucket.EdgePaymentOrders) - } - if m.removedprovider_profiles != nil { - edges = append(edges, provisionbucket.EdgeProviderProfiles) - } + edges := make([]string, 0, 0) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. func (m *ProvisionBucketMutation) RemovedIDs(name string) []ent.Value { - switch name { - case provisionbucket.EdgePaymentOrders: - ids := make([]ent.Value, 0, len(m.removedpayment_orders)) - for id := range m.removedpayment_orders { - ids = append(ids, id) - } - return ids - case provisionbucket.EdgeProviderProfiles: - ids := make([]ent.Value, 0, len(m.removedprovider_profiles)) - for id := range m.removedprovider_profiles { - ids = append(ids, id) - } - return ids - } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *ProvisionBucketMutation) ClearedEdges() []string { - edges := make([]string, 0, 3) - if m.clearedcurrency { - edges = append(edges, provisionbucket.EdgeCurrency) - } - if m.clearedpayment_orders { - edges = append(edges, provisionbucket.EdgePaymentOrders) - } - if m.clearedprovider_profiles { - edges = append(edges, provisionbucket.EdgeProviderProfiles) - } + edges := make([]string, 0, 0) return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. func (m *ProvisionBucketMutation) EdgeCleared(name string) bool { - switch name { - case provisionbucket.EdgeCurrency: - return m.clearedcurrency - case provisionbucket.EdgePaymentOrders: - return m.clearedpayment_orders - case provisionbucket.EdgeProviderProfiles: - return m.clearedprovider_profiles - } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. func (m *ProvisionBucketMutation) ClearEdge(name string) error { - switch name { - case provisionbucket.EdgeCurrency: - m.ClearCurrency() - return nil - } return fmt.Errorf("unknown ProvisionBucket unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. func (m *ProvisionBucketMutation) ResetEdge(name string) error { - switch name { - case provisionbucket.EdgeCurrency: - m.ResetCurrency() - return nil - case provisionbucket.EdgePaymentOrders: - m.ResetPaymentOrders() - return nil - case provisionbucket.EdgeProviderProfiles: - m.ResetProviderProfiles() - return nil - } return fmt.Errorf("unknown ProvisionBucket edge %s", name) } diff --git a/ent/paymentorder.go b/ent/paymentorder.go index f70648902..8756ad94a 100644 --- a/ent/paymentorder.go +++ b/ent/paymentorder.go @@ -14,7 +14,6 @@ import ( "github.com/paycrest/aggregator/ent/paymentorder" "github.com/paycrest/aggregator/ent/paymentwebhook" "github.com/paycrest/aggregator/ent/providerprofile" - "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/paycrest/aggregator/ent/senderprofile" "github.com/paycrest/aggregator/ent/token" "github.com/shopspring/decimal" @@ -99,12 +98,17 @@ type PaymentOrder struct { OrderType paymentorder.OrderType `json:"order_type,omitempty"` // FallbackTriedAt holds the value of the "fallback_tried_at" field. FallbackTriedAt time.Time `json:"fallback_tried_at,omitempty"` + // AssignmentMarketBuyRate holds the value of the "assignment_market_buy_rate" field. + AssignmentMarketBuyRate *decimal.Decimal `json:"assignment_market_buy_rate,omitempty"` + // AssignmentMarketSellRate holds the value of the "assignment_market_sell_rate" field. + AssignmentMarketSellRate *decimal.Decimal `json:"assignment_market_sell_rate,omitempty"` + // LegacyProvisionBucketID holds the value of the "legacy_provision_bucket_id" field. + LegacyProvisionBucketID *int `json:"legacy_provision_bucket_id,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the PaymentOrderQuery when eager-loading is set. Edges PaymentOrderEdges `json:"edges"` api_key_payment_orders *uuid.UUID provider_profile_assigned_orders *string - provision_bucket_payment_orders *int sender_profile_payment_orders *uuid.UUID token_payment_orders *int selectValues sql.SelectValues @@ -120,15 +124,17 @@ type PaymentOrderEdges struct { PaymentWebhook *PaymentWebhook `json:"payment_webhook,omitempty"` // Provider holds the value of the provider edge. Provider *ProviderProfile `json:"provider,omitempty"` - // ProvisionBucket holds the value of the provision_bucket edge. - ProvisionBucket *ProvisionBucket `json:"provision_bucket,omitempty"` // Fulfillments holds the value of the fulfillments edge. Fulfillments []*PaymentOrderFulfillment `json:"fulfillments,omitempty"` // Transactions holds the value of the transactions edge. Transactions []*TransactionLog `json:"transactions,omitempty"` + // ProviderAssignmentRuns holds the value of the provider_assignment_runs edge. + ProviderAssignmentRuns []*ProviderAssignmentRun `json:"provider_assignment_runs,omitempty"` + // ProviderOrderTokenScoreHistories holds the value of the provider_order_token_score_histories edge. + ProviderOrderTokenScoreHistories []*ProviderOrderTokenScoreHistory `json:"provider_order_token_score_histories,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [7]bool + loadedTypes [8]bool } // TokenOrErr returns the Token value or an error if the edge @@ -175,21 +181,10 @@ func (e PaymentOrderEdges) ProviderOrErr() (*ProviderProfile, error) { return nil, &NotLoadedError{edge: "provider"} } -// ProvisionBucketOrErr returns the ProvisionBucket value or an error if the edge -// was not loaded in eager-loading, or loaded but was not found. -func (e PaymentOrderEdges) ProvisionBucketOrErr() (*ProvisionBucket, error) { - if e.ProvisionBucket != nil { - return e.ProvisionBucket, nil - } else if e.loadedTypes[4] { - return nil, &NotFoundError{label: provisionbucket.Label} - } - return nil, &NotLoadedError{edge: "provision_bucket"} -} - // FulfillmentsOrErr returns the Fulfillments value or an error if the edge // was not loaded in eager-loading. func (e PaymentOrderEdges) FulfillmentsOrErr() ([]*PaymentOrderFulfillment, error) { - if e.loadedTypes[5] { + if e.loadedTypes[4] { return e.Fulfillments, nil } return nil, &NotLoadedError{edge: "fulfillments"} @@ -198,22 +193,42 @@ func (e PaymentOrderEdges) FulfillmentsOrErr() ([]*PaymentOrderFulfillment, erro // TransactionsOrErr returns the Transactions value or an error if the edge // was not loaded in eager-loading. func (e PaymentOrderEdges) TransactionsOrErr() ([]*TransactionLog, error) { - if e.loadedTypes[6] { + if e.loadedTypes[5] { return e.Transactions, nil } return nil, &NotLoadedError{edge: "transactions"} } +// ProviderAssignmentRunsOrErr returns the ProviderAssignmentRuns value or an error if the edge +// was not loaded in eager-loading. +func (e PaymentOrderEdges) ProviderAssignmentRunsOrErr() ([]*ProviderAssignmentRun, error) { + if e.loadedTypes[6] { + return e.ProviderAssignmentRuns, nil + } + return nil, &NotLoadedError{edge: "provider_assignment_runs"} +} + +// ProviderOrderTokenScoreHistoriesOrErr returns the ProviderOrderTokenScoreHistories value or an error if the edge +// was not loaded in eager-loading. +func (e PaymentOrderEdges) ProviderOrderTokenScoreHistoriesOrErr() ([]*ProviderOrderTokenScoreHistory, error) { + if e.loadedTypes[7] { + return e.ProviderOrderTokenScoreHistories, nil + } + return nil, &NotLoadedError{edge: "provider_order_token_score_histories"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*PaymentOrder) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { + case paymentorder.FieldAssignmentMarketBuyRate, paymentorder.FieldAssignmentMarketSellRate: + values[i] = &sql.NullScanner{S: new(decimal.Decimal)} case paymentorder.FieldReceiveAddressSalt, paymentorder.FieldMetadata, paymentorder.FieldCancellationReasons: values[i] = new([]byte) case paymentorder.FieldAmount, paymentorder.FieldRate, paymentorder.FieldAmountInUsd, paymentorder.FieldAmountPaid, paymentorder.FieldAmountReturned, paymentorder.FieldPercentSettled, paymentorder.FieldSenderFee, paymentorder.FieldNetworkFee, paymentorder.FieldProtocolFee, paymentorder.FieldOrderPercent, paymentorder.FieldFeePercent: values[i] = new(decimal.Decimal) - case paymentorder.FieldBlockNumber, paymentorder.FieldCancellationCount: + case paymentorder.FieldBlockNumber, paymentorder.FieldCancellationCount, paymentorder.FieldLegacyProvisionBucketID: values[i] = new(sql.NullInt64) case paymentorder.FieldTxHash, paymentorder.FieldMessageHash, paymentorder.FieldGatewayID, paymentorder.FieldFromAddress, paymentorder.FieldRefundOrRecipientAddress, paymentorder.FieldReceiveAddress, paymentorder.FieldFeeAddress, paymentorder.FieldInstitution, paymentorder.FieldAccountIdentifier, paymentorder.FieldAccountName, paymentorder.FieldSender, paymentorder.FieldReference, paymentorder.FieldMemo, paymentorder.FieldStatus, paymentorder.FieldDirection, paymentorder.FieldOrderType: values[i] = new(sql.NullString) @@ -225,11 +240,9 @@ func (*PaymentOrder) scanValues(columns []string) ([]any, error) { values[i] = &sql.NullScanner{S: new(uuid.UUID)} case paymentorder.ForeignKeys[1]: // provider_profile_assigned_orders values[i] = new(sql.NullString) - case paymentorder.ForeignKeys[2]: // provision_bucket_payment_orders - values[i] = new(sql.NullInt64) - case paymentorder.ForeignKeys[3]: // sender_profile_payment_orders + case paymentorder.ForeignKeys[2]: // sender_profile_payment_orders values[i] = &sql.NullScanner{S: new(uuid.UUID)} - case paymentorder.ForeignKeys[4]: // token_payment_orders + case paymentorder.ForeignKeys[3]: // token_payment_orders values[i] = new(sql.NullInt64) default: values[i] = new(sql.UnknownType) @@ -478,6 +491,27 @@ func (_m *PaymentOrder) assignValues(columns []string, values []any) error { } else if value.Valid { _m.FallbackTriedAt = value.Time } + case paymentorder.FieldAssignmentMarketBuyRate: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field assignment_market_buy_rate", values[i]) + } else if value.Valid { + _m.AssignmentMarketBuyRate = new(decimal.Decimal) + *_m.AssignmentMarketBuyRate = *value.S.(*decimal.Decimal) + } + case paymentorder.FieldAssignmentMarketSellRate: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field assignment_market_sell_rate", values[i]) + } else if value.Valid { + _m.AssignmentMarketSellRate = new(decimal.Decimal) + *_m.AssignmentMarketSellRate = *value.S.(*decimal.Decimal) + } + case paymentorder.FieldLegacyProvisionBucketID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field legacy_provision_bucket_id", values[i]) + } else if value.Valid { + _m.LegacyProvisionBucketID = new(int) + *_m.LegacyProvisionBucketID = int(value.Int64) + } case paymentorder.ForeignKeys[0]: if value, ok := values[i].(*sql.NullScanner); !ok { return fmt.Errorf("unexpected type %T for field api_key_payment_orders", values[i]) @@ -493,20 +527,13 @@ func (_m *PaymentOrder) assignValues(columns []string, values []any) error { *_m.provider_profile_assigned_orders = value.String } case paymentorder.ForeignKeys[2]: - if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for edge-field provision_bucket_payment_orders", value) - } else if value.Valid { - _m.provision_bucket_payment_orders = new(int) - *_m.provision_bucket_payment_orders = int(value.Int64) - } - case paymentorder.ForeignKeys[3]: if value, ok := values[i].(*sql.NullScanner); !ok { return fmt.Errorf("unexpected type %T for field sender_profile_payment_orders", values[i]) } else if value.Valid { _m.sender_profile_payment_orders = new(uuid.UUID) *_m.sender_profile_payment_orders = *value.S.(*uuid.UUID) } - case paymentorder.ForeignKeys[4]: + case paymentorder.ForeignKeys[3]: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for edge-field token_payment_orders", value) } else if value.Valid { @@ -546,11 +573,6 @@ func (_m *PaymentOrder) QueryProvider() *ProviderProfileQuery { return NewPaymentOrderClient(_m.config).QueryProvider(_m) } -// QueryProvisionBucket queries the "provision_bucket" edge of the PaymentOrder entity. -func (_m *PaymentOrder) QueryProvisionBucket() *ProvisionBucketQuery { - return NewPaymentOrderClient(_m.config).QueryProvisionBucket(_m) -} - // QueryFulfillments queries the "fulfillments" edge of the PaymentOrder entity. func (_m *PaymentOrder) QueryFulfillments() *PaymentOrderFulfillmentQuery { return NewPaymentOrderClient(_m.config).QueryFulfillments(_m) @@ -561,6 +583,16 @@ func (_m *PaymentOrder) QueryTransactions() *TransactionLogQuery { return NewPaymentOrderClient(_m.config).QueryTransactions(_m) } +// QueryProviderAssignmentRuns queries the "provider_assignment_runs" edge of the PaymentOrder entity. +func (_m *PaymentOrder) QueryProviderAssignmentRuns() *ProviderAssignmentRunQuery { + return NewPaymentOrderClient(_m.config).QueryProviderAssignmentRuns(_m) +} + +// QueryProviderOrderTokenScoreHistories queries the "provider_order_token_score_histories" edge of the PaymentOrder entity. +func (_m *PaymentOrder) QueryProviderOrderTokenScoreHistories() *ProviderOrderTokenScoreHistoryQuery { + return NewPaymentOrderClient(_m.config).QueryProviderOrderTokenScoreHistories(_m) +} + // Update returns a builder for updating this PaymentOrder. // Note that you need to call PaymentOrder.Unwrap() before calling this method if this PaymentOrder // was returned from a transaction, and the transaction was committed or rolled back. @@ -694,6 +726,21 @@ func (_m *PaymentOrder) String() string { builder.WriteString(", ") builder.WriteString("fallback_tried_at=") builder.WriteString(_m.FallbackTriedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.AssignmentMarketBuyRate; v != nil { + builder.WriteString("assignment_market_buy_rate=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.AssignmentMarketSellRate; v != nil { + builder.WriteString("assignment_market_sell_rate=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.LegacyProvisionBucketID; v != nil { + builder.WriteString("legacy_provision_bucket_id=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } builder.WriteByte(')') return builder.String() } diff --git a/ent/paymentorder/paymentorder.go b/ent/paymentorder/paymentorder.go index da5523318..43c96e26b 100644 --- a/ent/paymentorder/paymentorder.go +++ b/ent/paymentorder/paymentorder.go @@ -91,6 +91,12 @@ const ( FieldOrderType = "order_type" // FieldFallbackTriedAt holds the string denoting the fallback_tried_at field in the database. FieldFallbackTriedAt = "fallback_tried_at" + // FieldAssignmentMarketBuyRate holds the string denoting the assignment_market_buy_rate field in the database. + FieldAssignmentMarketBuyRate = "assignment_market_buy_rate" + // FieldAssignmentMarketSellRate holds the string denoting the assignment_market_sell_rate field in the database. + FieldAssignmentMarketSellRate = "assignment_market_sell_rate" + // FieldLegacyProvisionBucketID holds the string denoting the legacy_provision_bucket_id field in the database. + FieldLegacyProvisionBucketID = "provision_bucket_payment_orders" // EdgeToken holds the string denoting the token edge name in mutations. EdgeToken = "token" // EdgeSenderProfile holds the string denoting the sender_profile edge name in mutations. @@ -99,12 +105,14 @@ const ( EdgePaymentWebhook = "payment_webhook" // EdgeProvider holds the string denoting the provider edge name in mutations. EdgeProvider = "provider" - // EdgeProvisionBucket holds the string denoting the provision_bucket edge name in mutations. - EdgeProvisionBucket = "provision_bucket" // EdgeFulfillments holds the string denoting the fulfillments edge name in mutations. EdgeFulfillments = "fulfillments" // EdgeTransactions holds the string denoting the transactions edge name in mutations. EdgeTransactions = "transactions" + // EdgeProviderAssignmentRuns holds the string denoting the provider_assignment_runs edge name in mutations. + EdgeProviderAssignmentRuns = "provider_assignment_runs" + // EdgeProviderOrderTokenScoreHistories holds the string denoting the provider_order_token_score_histories edge name in mutations. + EdgeProviderOrderTokenScoreHistories = "provider_order_token_score_histories" // Table holds the table name of the paymentorder in the database. Table = "payment_orders" // TokenTable is the table that holds the token relation/edge. @@ -135,13 +143,6 @@ const ( ProviderInverseTable = "provider_profiles" // ProviderColumn is the table column denoting the provider relation/edge. ProviderColumn = "provider_profile_assigned_orders" - // ProvisionBucketTable is the table that holds the provision_bucket relation/edge. - ProvisionBucketTable = "payment_orders" - // ProvisionBucketInverseTable is the table name for the ProvisionBucket entity. - // It exists in this package in order to avoid circular dependency with the "provisionbucket" package. - ProvisionBucketInverseTable = "provision_buckets" - // ProvisionBucketColumn is the table column denoting the provision_bucket relation/edge. - ProvisionBucketColumn = "provision_bucket_payment_orders" // FulfillmentsTable is the table that holds the fulfillments relation/edge. FulfillmentsTable = "payment_order_fulfillments" // FulfillmentsInverseTable is the table name for the PaymentOrderFulfillment entity. @@ -156,6 +157,20 @@ const ( TransactionsInverseTable = "transaction_logs" // TransactionsColumn is the table column denoting the transactions relation/edge. TransactionsColumn = "payment_order_transactions" + // ProviderAssignmentRunsTable is the table that holds the provider_assignment_runs relation/edge. + ProviderAssignmentRunsTable = "provider_assignment_runs" + // ProviderAssignmentRunsInverseTable is the table name for the ProviderAssignmentRun entity. + // It exists in this package in order to avoid circular dependency with the "providerassignmentrun" package. + ProviderAssignmentRunsInverseTable = "provider_assignment_runs" + // ProviderAssignmentRunsColumn is the table column denoting the provider_assignment_runs relation/edge. + ProviderAssignmentRunsColumn = "payment_order_provider_assignment_runs" + // ProviderOrderTokenScoreHistoriesTable is the table that holds the provider_order_token_score_histories relation/edge. + ProviderOrderTokenScoreHistoriesTable = "provider_order_token_score_histories" + // ProviderOrderTokenScoreHistoriesInverseTable is the table name for the ProviderOrderTokenScoreHistory entity. + // It exists in this package in order to avoid circular dependency with the "providerordertokenscorehistory" package. + ProviderOrderTokenScoreHistoriesInverseTable = "provider_order_token_score_histories" + // ProviderOrderTokenScoreHistoriesColumn is the table column denoting the provider_order_token_score_histories relation/edge. + ProviderOrderTokenScoreHistoriesColumn = "payment_order_provider_order_token_score_histories" ) // Columns holds all SQL columns for paymentorder fields. @@ -198,6 +213,9 @@ var Columns = []string{ FieldDirection, FieldOrderType, FieldFallbackTriedAt, + FieldAssignmentMarketBuyRate, + FieldAssignmentMarketSellRate, + FieldLegacyProvisionBucketID, } // ForeignKeys holds the SQL foreign-keys that are owned by the "payment_orders" @@ -205,7 +223,6 @@ var Columns = []string{ var ForeignKeys = []string{ "api_key_payment_orders", "provider_profile_assigned_orders", - "provision_bucket_payment_orders", "sender_profile_payment_orders", "token_payment_orders", } @@ -548,6 +565,21 @@ func ByFallbackTriedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldFallbackTriedAt, opts...).ToFunc() } +// ByAssignmentMarketBuyRate orders the results by the assignment_market_buy_rate field. +func ByAssignmentMarketBuyRate(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAssignmentMarketBuyRate, opts...).ToFunc() +} + +// ByAssignmentMarketSellRate orders the results by the assignment_market_sell_rate field. +func ByAssignmentMarketSellRate(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAssignmentMarketSellRate, opts...).ToFunc() +} + +// ByLegacyProvisionBucketID orders the results by the legacy_provision_bucket_id field. +func ByLegacyProvisionBucketID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLegacyProvisionBucketID, opts...).ToFunc() +} + // ByTokenField orders the results by token field. func ByTokenField(field string, opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -576,13 +608,6 @@ func ByProviderField(field string, opts ...sql.OrderTermOption) OrderOption { } } -// ByProvisionBucketField orders the results by provision_bucket field. -func ByProvisionBucketField(field string, opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newProvisionBucketStep(), sql.OrderByField(field, opts...)) - } -} - // ByFulfillmentsCount orders the results by fulfillments count. func ByFulfillmentsCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -610,6 +635,34 @@ func ByTransactions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { sqlgraph.OrderByNeighborTerms(s, newTransactionsStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// ByProviderAssignmentRunsCount orders the results by provider_assignment_runs count. +func ByProviderAssignmentRunsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newProviderAssignmentRunsStep(), opts...) + } +} + +// ByProviderAssignmentRuns orders the results by provider_assignment_runs terms. +func ByProviderAssignmentRuns(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newProviderAssignmentRunsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByProviderOrderTokenScoreHistoriesCount orders the results by provider_order_token_score_histories count. +func ByProviderOrderTokenScoreHistoriesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newProviderOrderTokenScoreHistoriesStep(), opts...) + } +} + +// ByProviderOrderTokenScoreHistories orders the results by provider_order_token_score_histories terms. +func ByProviderOrderTokenScoreHistories(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newProviderOrderTokenScoreHistoriesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newTokenStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -638,13 +691,6 @@ func newProviderStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.M2O, true, ProviderTable, ProviderColumn), ) } -func newProvisionBucketStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(ProvisionBucketInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, ProvisionBucketTable, ProvisionBucketColumn), - ) -} func newFulfillmentsStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -659,3 +705,17 @@ func newTransactionsStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, TransactionsTable, TransactionsColumn), ) } +func newProviderAssignmentRunsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ProviderAssignmentRunsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ProviderAssignmentRunsTable, ProviderAssignmentRunsColumn), + ) +} +func newProviderOrderTokenScoreHistoriesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ProviderOrderTokenScoreHistoriesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ProviderOrderTokenScoreHistoriesTable, ProviderOrderTokenScoreHistoriesColumn), + ) +} diff --git a/ent/paymentorder/where.go b/ent/paymentorder/where.go index e5f10449c..1f947cb60 100644 --- a/ent/paymentorder/where.go +++ b/ent/paymentorder/where.go @@ -217,6 +217,21 @@ func FallbackTriedAt(v time.Time) predicate.PaymentOrder { return predicate.PaymentOrder(sql.FieldEQ(FieldFallbackTriedAt, v)) } +// AssignmentMarketBuyRate applies equality check predicate on the "assignment_market_buy_rate" field. It's identical to AssignmentMarketBuyRateEQ. +func AssignmentMarketBuyRate(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldEQ(FieldAssignmentMarketBuyRate, v)) +} + +// AssignmentMarketSellRate applies equality check predicate on the "assignment_market_sell_rate" field. It's identical to AssignmentMarketSellRateEQ. +func AssignmentMarketSellRate(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldEQ(FieldAssignmentMarketSellRate, v)) +} + +// LegacyProvisionBucketID applies equality check predicate on the "legacy_provision_bucket_id" field. It's identical to LegacyProvisionBucketIDEQ. +func LegacyProvisionBucketID(v int) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldEQ(FieldLegacyProvisionBucketID, v)) +} + // CreatedAtEQ applies the EQ predicate on the "created_at" field. func CreatedAtEQ(v time.Time) predicate.PaymentOrder { return predicate.PaymentOrder(sql.FieldEQ(FieldCreatedAt, v)) @@ -2052,6 +2067,156 @@ func FallbackTriedAtNotNil() predicate.PaymentOrder { return predicate.PaymentOrder(sql.FieldNotNull(FieldFallbackTriedAt)) } +// AssignmentMarketBuyRateEQ applies the EQ predicate on the "assignment_market_buy_rate" field. +func AssignmentMarketBuyRateEQ(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldEQ(FieldAssignmentMarketBuyRate, v)) +} + +// AssignmentMarketBuyRateNEQ applies the NEQ predicate on the "assignment_market_buy_rate" field. +func AssignmentMarketBuyRateNEQ(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldNEQ(FieldAssignmentMarketBuyRate, v)) +} + +// AssignmentMarketBuyRateIn applies the In predicate on the "assignment_market_buy_rate" field. +func AssignmentMarketBuyRateIn(vs ...decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldIn(FieldAssignmentMarketBuyRate, vs...)) +} + +// AssignmentMarketBuyRateNotIn applies the NotIn predicate on the "assignment_market_buy_rate" field. +func AssignmentMarketBuyRateNotIn(vs ...decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldNotIn(FieldAssignmentMarketBuyRate, vs...)) +} + +// AssignmentMarketBuyRateGT applies the GT predicate on the "assignment_market_buy_rate" field. +func AssignmentMarketBuyRateGT(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldGT(FieldAssignmentMarketBuyRate, v)) +} + +// AssignmentMarketBuyRateGTE applies the GTE predicate on the "assignment_market_buy_rate" field. +func AssignmentMarketBuyRateGTE(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldGTE(FieldAssignmentMarketBuyRate, v)) +} + +// AssignmentMarketBuyRateLT applies the LT predicate on the "assignment_market_buy_rate" field. +func AssignmentMarketBuyRateLT(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldLT(FieldAssignmentMarketBuyRate, v)) +} + +// AssignmentMarketBuyRateLTE applies the LTE predicate on the "assignment_market_buy_rate" field. +func AssignmentMarketBuyRateLTE(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldLTE(FieldAssignmentMarketBuyRate, v)) +} + +// AssignmentMarketBuyRateIsNil applies the IsNil predicate on the "assignment_market_buy_rate" field. +func AssignmentMarketBuyRateIsNil() predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldIsNull(FieldAssignmentMarketBuyRate)) +} + +// AssignmentMarketBuyRateNotNil applies the NotNil predicate on the "assignment_market_buy_rate" field. +func AssignmentMarketBuyRateNotNil() predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldNotNull(FieldAssignmentMarketBuyRate)) +} + +// AssignmentMarketSellRateEQ applies the EQ predicate on the "assignment_market_sell_rate" field. +func AssignmentMarketSellRateEQ(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldEQ(FieldAssignmentMarketSellRate, v)) +} + +// AssignmentMarketSellRateNEQ applies the NEQ predicate on the "assignment_market_sell_rate" field. +func AssignmentMarketSellRateNEQ(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldNEQ(FieldAssignmentMarketSellRate, v)) +} + +// AssignmentMarketSellRateIn applies the In predicate on the "assignment_market_sell_rate" field. +func AssignmentMarketSellRateIn(vs ...decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldIn(FieldAssignmentMarketSellRate, vs...)) +} + +// AssignmentMarketSellRateNotIn applies the NotIn predicate on the "assignment_market_sell_rate" field. +func AssignmentMarketSellRateNotIn(vs ...decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldNotIn(FieldAssignmentMarketSellRate, vs...)) +} + +// AssignmentMarketSellRateGT applies the GT predicate on the "assignment_market_sell_rate" field. +func AssignmentMarketSellRateGT(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldGT(FieldAssignmentMarketSellRate, v)) +} + +// AssignmentMarketSellRateGTE applies the GTE predicate on the "assignment_market_sell_rate" field. +func AssignmentMarketSellRateGTE(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldGTE(FieldAssignmentMarketSellRate, v)) +} + +// AssignmentMarketSellRateLT applies the LT predicate on the "assignment_market_sell_rate" field. +func AssignmentMarketSellRateLT(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldLT(FieldAssignmentMarketSellRate, v)) +} + +// AssignmentMarketSellRateLTE applies the LTE predicate on the "assignment_market_sell_rate" field. +func AssignmentMarketSellRateLTE(v decimal.Decimal) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldLTE(FieldAssignmentMarketSellRate, v)) +} + +// AssignmentMarketSellRateIsNil applies the IsNil predicate on the "assignment_market_sell_rate" field. +func AssignmentMarketSellRateIsNil() predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldIsNull(FieldAssignmentMarketSellRate)) +} + +// AssignmentMarketSellRateNotNil applies the NotNil predicate on the "assignment_market_sell_rate" field. +func AssignmentMarketSellRateNotNil() predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldNotNull(FieldAssignmentMarketSellRate)) +} + +// LegacyProvisionBucketIDEQ applies the EQ predicate on the "legacy_provision_bucket_id" field. +func LegacyProvisionBucketIDEQ(v int) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldEQ(FieldLegacyProvisionBucketID, v)) +} + +// LegacyProvisionBucketIDNEQ applies the NEQ predicate on the "legacy_provision_bucket_id" field. +func LegacyProvisionBucketIDNEQ(v int) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldNEQ(FieldLegacyProvisionBucketID, v)) +} + +// LegacyProvisionBucketIDIn applies the In predicate on the "legacy_provision_bucket_id" field. +func LegacyProvisionBucketIDIn(vs ...int) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldIn(FieldLegacyProvisionBucketID, vs...)) +} + +// LegacyProvisionBucketIDNotIn applies the NotIn predicate on the "legacy_provision_bucket_id" field. +func LegacyProvisionBucketIDNotIn(vs ...int) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldNotIn(FieldLegacyProvisionBucketID, vs...)) +} + +// LegacyProvisionBucketIDGT applies the GT predicate on the "legacy_provision_bucket_id" field. +func LegacyProvisionBucketIDGT(v int) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldGT(FieldLegacyProvisionBucketID, v)) +} + +// LegacyProvisionBucketIDGTE applies the GTE predicate on the "legacy_provision_bucket_id" field. +func LegacyProvisionBucketIDGTE(v int) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldGTE(FieldLegacyProvisionBucketID, v)) +} + +// LegacyProvisionBucketIDLT applies the LT predicate on the "legacy_provision_bucket_id" field. +func LegacyProvisionBucketIDLT(v int) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldLT(FieldLegacyProvisionBucketID, v)) +} + +// LegacyProvisionBucketIDLTE applies the LTE predicate on the "legacy_provision_bucket_id" field. +func LegacyProvisionBucketIDLTE(v int) predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldLTE(FieldLegacyProvisionBucketID, v)) +} + +// LegacyProvisionBucketIDIsNil applies the IsNil predicate on the "legacy_provision_bucket_id" field. +func LegacyProvisionBucketIDIsNil() predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldIsNull(FieldLegacyProvisionBucketID)) +} + +// LegacyProvisionBucketIDNotNil applies the NotNil predicate on the "legacy_provision_bucket_id" field. +func LegacyProvisionBucketIDNotNil() predicate.PaymentOrder { + return predicate.PaymentOrder(sql.FieldNotNull(FieldLegacyProvisionBucketID)) +} + // HasToken applies the HasEdge predicate on the "token" edge. func HasToken() predicate.PaymentOrder { return predicate.PaymentOrder(func(s *sql.Selector) { @@ -2144,21 +2309,21 @@ func HasProviderWith(preds ...predicate.ProviderProfile) predicate.PaymentOrder }) } -// HasProvisionBucket applies the HasEdge predicate on the "provision_bucket" edge. -func HasProvisionBucket() predicate.PaymentOrder { +// HasFulfillments applies the HasEdge predicate on the "fulfillments" edge. +func HasFulfillments() predicate.PaymentOrder { return predicate.PaymentOrder(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, ProvisionBucketTable, ProvisionBucketColumn), + sqlgraph.Edge(sqlgraph.O2M, false, FulfillmentsTable, FulfillmentsColumn), ) sqlgraph.HasNeighbors(s, step) }) } -// HasProvisionBucketWith applies the HasEdge predicate on the "provision_bucket" edge with a given conditions (other predicates). -func HasProvisionBucketWith(preds ...predicate.ProvisionBucket) predicate.PaymentOrder { +// HasFulfillmentsWith applies the HasEdge predicate on the "fulfillments" edge with a given conditions (other predicates). +func HasFulfillmentsWith(preds ...predicate.PaymentOrderFulfillment) predicate.PaymentOrder { return predicate.PaymentOrder(func(s *sql.Selector) { - step := newProvisionBucketStep() + step := newFulfillmentsStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -2167,21 +2332,21 @@ func HasProvisionBucketWith(preds ...predicate.ProvisionBucket) predicate.Paymen }) } -// HasFulfillments applies the HasEdge predicate on the "fulfillments" edge. -func HasFulfillments() predicate.PaymentOrder { +// HasTransactions applies the HasEdge predicate on the "transactions" edge. +func HasTransactions() predicate.PaymentOrder { return predicate.PaymentOrder(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, FulfillmentsTable, FulfillmentsColumn), + sqlgraph.Edge(sqlgraph.O2M, false, TransactionsTable, TransactionsColumn), ) sqlgraph.HasNeighbors(s, step) }) } -// HasFulfillmentsWith applies the HasEdge predicate on the "fulfillments" edge with a given conditions (other predicates). -func HasFulfillmentsWith(preds ...predicate.PaymentOrderFulfillment) predicate.PaymentOrder { +// HasTransactionsWith applies the HasEdge predicate on the "transactions" edge with a given conditions (other predicates). +func HasTransactionsWith(preds ...predicate.TransactionLog) predicate.PaymentOrder { return predicate.PaymentOrder(func(s *sql.Selector) { - step := newFulfillmentsStep() + step := newTransactionsStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -2190,21 +2355,44 @@ func HasFulfillmentsWith(preds ...predicate.PaymentOrderFulfillment) predicate.P }) } -// HasTransactions applies the HasEdge predicate on the "transactions" edge. -func HasTransactions() predicate.PaymentOrder { +// HasProviderAssignmentRuns applies the HasEdge predicate on the "provider_assignment_runs" edge. +func HasProviderAssignmentRuns() predicate.PaymentOrder { return predicate.PaymentOrder(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, TransactionsTable, TransactionsColumn), + sqlgraph.Edge(sqlgraph.O2M, false, ProviderAssignmentRunsTable, ProviderAssignmentRunsColumn), ) sqlgraph.HasNeighbors(s, step) }) } -// HasTransactionsWith applies the HasEdge predicate on the "transactions" edge with a given conditions (other predicates). -func HasTransactionsWith(preds ...predicate.TransactionLog) predicate.PaymentOrder { +// HasProviderAssignmentRunsWith applies the HasEdge predicate on the "provider_assignment_runs" edge with a given conditions (other predicates). +func HasProviderAssignmentRunsWith(preds ...predicate.ProviderAssignmentRun) predicate.PaymentOrder { return predicate.PaymentOrder(func(s *sql.Selector) { - step := newTransactionsStep() + step := newProviderAssignmentRunsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasProviderOrderTokenScoreHistories applies the HasEdge predicate on the "provider_order_token_score_histories" edge. +func HasProviderOrderTokenScoreHistories() predicate.PaymentOrder { + return predicate.PaymentOrder(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ProviderOrderTokenScoreHistoriesTable, ProviderOrderTokenScoreHistoriesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasProviderOrderTokenScoreHistoriesWith applies the HasEdge predicate on the "provider_order_token_score_histories" edge with a given conditions (other predicates). +func HasProviderOrderTokenScoreHistoriesWith(preds ...predicate.ProviderOrderTokenScoreHistory) predicate.PaymentOrder { + return predicate.PaymentOrder(func(s *sql.Selector) { + step := newProviderOrderTokenScoreHistoriesStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) diff --git a/ent/paymentorder_create.go b/ent/paymentorder_create.go index f4f5b3f2a..1c509efb0 100644 --- a/ent/paymentorder_create.go +++ b/ent/paymentorder_create.go @@ -16,8 +16,9 @@ import ( "github.com/paycrest/aggregator/ent/paymentorder" "github.com/paycrest/aggregator/ent/paymentorderfulfillment" "github.com/paycrest/aggregator/ent/paymentwebhook" + "github.com/paycrest/aggregator/ent/providerassignmentrun" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" "github.com/paycrest/aggregator/ent/providerprofile" - "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/paycrest/aggregator/ent/senderprofile" "github.com/paycrest/aggregator/ent/token" "github.com/paycrest/aggregator/ent/transactionlog" @@ -478,6 +479,48 @@ func (_c *PaymentOrderCreate) SetNillableFallbackTriedAt(v *time.Time) *PaymentO return _c } +// SetAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field. +func (_c *PaymentOrderCreate) SetAssignmentMarketBuyRate(v decimal.Decimal) *PaymentOrderCreate { + _c.mutation.SetAssignmentMarketBuyRate(v) + return _c +} + +// SetNillableAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field if the given value is not nil. +func (_c *PaymentOrderCreate) SetNillableAssignmentMarketBuyRate(v *decimal.Decimal) *PaymentOrderCreate { + if v != nil { + _c.SetAssignmentMarketBuyRate(*v) + } + return _c +} + +// SetAssignmentMarketSellRate sets the "assignment_market_sell_rate" field. +func (_c *PaymentOrderCreate) SetAssignmentMarketSellRate(v decimal.Decimal) *PaymentOrderCreate { + _c.mutation.SetAssignmentMarketSellRate(v) + return _c +} + +// SetNillableAssignmentMarketSellRate sets the "assignment_market_sell_rate" field if the given value is not nil. +func (_c *PaymentOrderCreate) SetNillableAssignmentMarketSellRate(v *decimal.Decimal) *PaymentOrderCreate { + if v != nil { + _c.SetAssignmentMarketSellRate(*v) + } + return _c +} + +// SetLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field. +func (_c *PaymentOrderCreate) SetLegacyProvisionBucketID(v int) *PaymentOrderCreate { + _c.mutation.SetLegacyProvisionBucketID(v) + return _c +} + +// SetNillableLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field if the given value is not nil. +func (_c *PaymentOrderCreate) SetNillableLegacyProvisionBucketID(v *int) *PaymentOrderCreate { + if v != nil { + _c.SetLegacyProvisionBucketID(*v) + } + return _c +} + // SetID sets the "id" field. func (_c *PaymentOrderCreate) SetID(v uuid.UUID) *PaymentOrderCreate { _c.mutation.SetID(v) @@ -560,25 +603,6 @@ func (_c *PaymentOrderCreate) SetProvider(v *ProviderProfile) *PaymentOrderCreat return _c.SetProviderID(v.ID) } -// SetProvisionBucketID sets the "provision_bucket" edge to the ProvisionBucket entity by ID. -func (_c *PaymentOrderCreate) SetProvisionBucketID(id int) *PaymentOrderCreate { - _c.mutation.SetProvisionBucketID(id) - return _c -} - -// SetNillableProvisionBucketID sets the "provision_bucket" edge to the ProvisionBucket entity by ID if the given value is not nil. -func (_c *PaymentOrderCreate) SetNillableProvisionBucketID(id *int) *PaymentOrderCreate { - if id != nil { - _c = _c.SetProvisionBucketID(*id) - } - return _c -} - -// SetProvisionBucket sets the "provision_bucket" edge to the ProvisionBucket entity. -func (_c *PaymentOrderCreate) SetProvisionBucket(v *ProvisionBucket) *PaymentOrderCreate { - return _c.SetProvisionBucketID(v.ID) -} - // AddFulfillmentIDs adds the "fulfillments" edge to the PaymentOrderFulfillment entity by IDs. func (_c *PaymentOrderCreate) AddFulfillmentIDs(ids ...uuid.UUID) *PaymentOrderCreate { _c.mutation.AddFulfillmentIDs(ids...) @@ -609,6 +633,36 @@ func (_c *PaymentOrderCreate) AddTransactions(v ...*TransactionLog) *PaymentOrde return _c.AddTransactionIDs(ids...) } +// AddProviderAssignmentRunIDs adds the "provider_assignment_runs" edge to the ProviderAssignmentRun entity by IDs. +func (_c *PaymentOrderCreate) AddProviderAssignmentRunIDs(ids ...uuid.UUID) *PaymentOrderCreate { + _c.mutation.AddProviderAssignmentRunIDs(ids...) + return _c +} + +// AddProviderAssignmentRuns adds the "provider_assignment_runs" edges to the ProviderAssignmentRun entity. +func (_c *PaymentOrderCreate) AddProviderAssignmentRuns(v ...*ProviderAssignmentRun) *PaymentOrderCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddProviderAssignmentRunIDs(ids...) +} + +// AddProviderOrderTokenScoreHistoryIDs adds the "provider_order_token_score_histories" edge to the ProviderOrderTokenScoreHistory entity by IDs. +func (_c *PaymentOrderCreate) AddProviderOrderTokenScoreHistoryIDs(ids ...uuid.UUID) *PaymentOrderCreate { + _c.mutation.AddProviderOrderTokenScoreHistoryIDs(ids...) + return _c +} + +// AddProviderOrderTokenScoreHistories adds the "provider_order_token_score_histories" edges to the ProviderOrderTokenScoreHistory entity. +func (_c *PaymentOrderCreate) AddProviderOrderTokenScoreHistories(v ...*ProviderOrderTokenScoreHistory) *PaymentOrderCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddProviderOrderTokenScoreHistoryIDs(ids...) +} + // Mutation returns the PaymentOrderMutation object of the builder. func (_c *PaymentOrderCreate) Mutation() *PaymentOrderMutation { return _c.mutation @@ -1038,6 +1092,18 @@ func (_c *PaymentOrderCreate) createSpec() (*PaymentOrder, *sqlgraph.CreateSpec) _spec.SetField(paymentorder.FieldFallbackTriedAt, field.TypeTime, value) _node.FallbackTriedAt = value } + if value, ok := _c.mutation.AssignmentMarketBuyRate(); ok { + _spec.SetField(paymentorder.FieldAssignmentMarketBuyRate, field.TypeFloat64, value) + _node.AssignmentMarketBuyRate = &value + } + if value, ok := _c.mutation.AssignmentMarketSellRate(); ok { + _spec.SetField(paymentorder.FieldAssignmentMarketSellRate, field.TypeFloat64, value) + _node.AssignmentMarketSellRate = &value + } + if value, ok := _c.mutation.LegacyProvisionBucketID(); ok { + _spec.SetField(paymentorder.FieldLegacyProvisionBucketID, field.TypeInt, value) + _node.LegacyProvisionBucketID = &value + } if nodes := _c.mutation.TokenIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -1105,32 +1171,31 @@ func (_c *PaymentOrderCreate) createSpec() (*PaymentOrder, *sqlgraph.CreateSpec) _node.provider_profile_assigned_orders = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } - if nodes := _c.mutation.ProvisionBucketIDs(); len(nodes) > 0 { + if nodes := _c.mutation.FulfillmentsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: paymentorder.ProvisionBucketTable, - Columns: []string{paymentorder.ProvisionBucketColumn}, + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.FulfillmentsTable, + Columns: []string{paymentorder.FulfillmentsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), + IDSpec: sqlgraph.NewFieldSpec(paymentorderfulfillment.FieldID, field.TypeUUID), }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } - _node.provision_bucket_payment_orders = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } - if nodes := _c.mutation.FulfillmentsIDs(); len(nodes) > 0 { + if nodes := _c.mutation.TransactionsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: paymentorder.FulfillmentsTable, - Columns: []string{paymentorder.FulfillmentsColumn}, + Table: paymentorder.TransactionsTable, + Columns: []string{paymentorder.TransactionsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(paymentorderfulfillment.FieldID, field.TypeUUID), + IDSpec: sqlgraph.NewFieldSpec(transactionlog.FieldID, field.TypeUUID), }, } for _, k := range nodes { @@ -1138,15 +1203,31 @@ func (_c *PaymentOrderCreate) createSpec() (*PaymentOrder, *sqlgraph.CreateSpec) } _spec.Edges = append(_spec.Edges, edge) } - if nodes := _c.mutation.TransactionsIDs(); len(nodes) > 0 { + if nodes := _c.mutation.ProviderAssignmentRunsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: paymentorder.TransactionsTable, - Columns: []string{paymentorder.TransactionsColumn}, + Table: paymentorder.ProviderAssignmentRunsTable, + Columns: []string{paymentorder.ProviderAssignmentRunsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(transactionlog.FieldID, field.TypeUUID), + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ProviderOrderTokenScoreHistoriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderOrderTokenScoreHistoriesTable, + Columns: []string{paymentorder.ProviderOrderTokenScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), }, } for _, k := range nodes { @@ -1818,6 +1899,78 @@ func (u *PaymentOrderUpsert) ClearFallbackTriedAt() *PaymentOrderUpsert { return u } +// SetAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field. +func (u *PaymentOrderUpsert) SetAssignmentMarketBuyRate(v decimal.Decimal) *PaymentOrderUpsert { + u.Set(paymentorder.FieldAssignmentMarketBuyRate, v) + return u +} + +// UpdateAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field to the value that was provided on create. +func (u *PaymentOrderUpsert) UpdateAssignmentMarketBuyRate() *PaymentOrderUpsert { + u.SetExcluded(paymentorder.FieldAssignmentMarketBuyRate) + return u +} + +// AddAssignmentMarketBuyRate adds v to the "assignment_market_buy_rate" field. +func (u *PaymentOrderUpsert) AddAssignmentMarketBuyRate(v decimal.Decimal) *PaymentOrderUpsert { + u.Add(paymentorder.FieldAssignmentMarketBuyRate, v) + return u +} + +// ClearAssignmentMarketBuyRate clears the value of the "assignment_market_buy_rate" field. +func (u *PaymentOrderUpsert) ClearAssignmentMarketBuyRate() *PaymentOrderUpsert { + u.SetNull(paymentorder.FieldAssignmentMarketBuyRate) + return u +} + +// SetAssignmentMarketSellRate sets the "assignment_market_sell_rate" field. +func (u *PaymentOrderUpsert) SetAssignmentMarketSellRate(v decimal.Decimal) *PaymentOrderUpsert { + u.Set(paymentorder.FieldAssignmentMarketSellRate, v) + return u +} + +// UpdateAssignmentMarketSellRate sets the "assignment_market_sell_rate" field to the value that was provided on create. +func (u *PaymentOrderUpsert) UpdateAssignmentMarketSellRate() *PaymentOrderUpsert { + u.SetExcluded(paymentorder.FieldAssignmentMarketSellRate) + return u +} + +// AddAssignmentMarketSellRate adds v to the "assignment_market_sell_rate" field. +func (u *PaymentOrderUpsert) AddAssignmentMarketSellRate(v decimal.Decimal) *PaymentOrderUpsert { + u.Add(paymentorder.FieldAssignmentMarketSellRate, v) + return u +} + +// ClearAssignmentMarketSellRate clears the value of the "assignment_market_sell_rate" field. +func (u *PaymentOrderUpsert) ClearAssignmentMarketSellRate() *PaymentOrderUpsert { + u.SetNull(paymentorder.FieldAssignmentMarketSellRate) + return u +} + +// SetLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field. +func (u *PaymentOrderUpsert) SetLegacyProvisionBucketID(v int) *PaymentOrderUpsert { + u.Set(paymentorder.FieldLegacyProvisionBucketID, v) + return u +} + +// UpdateLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field to the value that was provided on create. +func (u *PaymentOrderUpsert) UpdateLegacyProvisionBucketID() *PaymentOrderUpsert { + u.SetExcluded(paymentorder.FieldLegacyProvisionBucketID) + return u +} + +// AddLegacyProvisionBucketID adds v to the "legacy_provision_bucket_id" field. +func (u *PaymentOrderUpsert) AddLegacyProvisionBucketID(v int) *PaymentOrderUpsert { + u.Add(paymentorder.FieldLegacyProvisionBucketID, v) + return u +} + +// ClearLegacyProvisionBucketID clears the value of the "legacy_provision_bucket_id" field. +func (u *PaymentOrderUpsert) ClearLegacyProvisionBucketID() *PaymentOrderUpsert { + u.SetNull(paymentorder.FieldLegacyProvisionBucketID) + return u +} + // UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. // Using this option is equivalent to using: // @@ -2583,6 +2736,90 @@ func (u *PaymentOrderUpsertOne) ClearFallbackTriedAt() *PaymentOrderUpsertOne { }) } +// SetAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field. +func (u *PaymentOrderUpsertOne) SetAssignmentMarketBuyRate(v decimal.Decimal) *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.SetAssignmentMarketBuyRate(v) + }) +} + +// AddAssignmentMarketBuyRate adds v to the "assignment_market_buy_rate" field. +func (u *PaymentOrderUpsertOne) AddAssignmentMarketBuyRate(v decimal.Decimal) *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.AddAssignmentMarketBuyRate(v) + }) +} + +// UpdateAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field to the value that was provided on create. +func (u *PaymentOrderUpsertOne) UpdateAssignmentMarketBuyRate() *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.UpdateAssignmentMarketBuyRate() + }) +} + +// ClearAssignmentMarketBuyRate clears the value of the "assignment_market_buy_rate" field. +func (u *PaymentOrderUpsertOne) ClearAssignmentMarketBuyRate() *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.ClearAssignmentMarketBuyRate() + }) +} + +// SetAssignmentMarketSellRate sets the "assignment_market_sell_rate" field. +func (u *PaymentOrderUpsertOne) SetAssignmentMarketSellRate(v decimal.Decimal) *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.SetAssignmentMarketSellRate(v) + }) +} + +// AddAssignmentMarketSellRate adds v to the "assignment_market_sell_rate" field. +func (u *PaymentOrderUpsertOne) AddAssignmentMarketSellRate(v decimal.Decimal) *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.AddAssignmentMarketSellRate(v) + }) +} + +// UpdateAssignmentMarketSellRate sets the "assignment_market_sell_rate" field to the value that was provided on create. +func (u *PaymentOrderUpsertOne) UpdateAssignmentMarketSellRate() *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.UpdateAssignmentMarketSellRate() + }) +} + +// ClearAssignmentMarketSellRate clears the value of the "assignment_market_sell_rate" field. +func (u *PaymentOrderUpsertOne) ClearAssignmentMarketSellRate() *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.ClearAssignmentMarketSellRate() + }) +} + +// SetLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field. +func (u *PaymentOrderUpsertOne) SetLegacyProvisionBucketID(v int) *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.SetLegacyProvisionBucketID(v) + }) +} + +// AddLegacyProvisionBucketID adds v to the "legacy_provision_bucket_id" field. +func (u *PaymentOrderUpsertOne) AddLegacyProvisionBucketID(v int) *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.AddLegacyProvisionBucketID(v) + }) +} + +// UpdateLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field to the value that was provided on create. +func (u *PaymentOrderUpsertOne) UpdateLegacyProvisionBucketID() *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.UpdateLegacyProvisionBucketID() + }) +} + +// ClearLegacyProvisionBucketID clears the value of the "legacy_provision_bucket_id" field. +func (u *PaymentOrderUpsertOne) ClearLegacyProvisionBucketID() *PaymentOrderUpsertOne { + return u.Update(func(s *PaymentOrderUpsert) { + s.ClearLegacyProvisionBucketID() + }) +} + // Exec executes the query. func (u *PaymentOrderUpsertOne) Exec(ctx context.Context) error { if len(u.create.conflict) == 0 { @@ -3515,6 +3752,90 @@ func (u *PaymentOrderUpsertBulk) ClearFallbackTriedAt() *PaymentOrderUpsertBulk }) } +// SetAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field. +func (u *PaymentOrderUpsertBulk) SetAssignmentMarketBuyRate(v decimal.Decimal) *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.SetAssignmentMarketBuyRate(v) + }) +} + +// AddAssignmentMarketBuyRate adds v to the "assignment_market_buy_rate" field. +func (u *PaymentOrderUpsertBulk) AddAssignmentMarketBuyRate(v decimal.Decimal) *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.AddAssignmentMarketBuyRate(v) + }) +} + +// UpdateAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field to the value that was provided on create. +func (u *PaymentOrderUpsertBulk) UpdateAssignmentMarketBuyRate() *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.UpdateAssignmentMarketBuyRate() + }) +} + +// ClearAssignmentMarketBuyRate clears the value of the "assignment_market_buy_rate" field. +func (u *PaymentOrderUpsertBulk) ClearAssignmentMarketBuyRate() *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.ClearAssignmentMarketBuyRate() + }) +} + +// SetAssignmentMarketSellRate sets the "assignment_market_sell_rate" field. +func (u *PaymentOrderUpsertBulk) SetAssignmentMarketSellRate(v decimal.Decimal) *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.SetAssignmentMarketSellRate(v) + }) +} + +// AddAssignmentMarketSellRate adds v to the "assignment_market_sell_rate" field. +func (u *PaymentOrderUpsertBulk) AddAssignmentMarketSellRate(v decimal.Decimal) *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.AddAssignmentMarketSellRate(v) + }) +} + +// UpdateAssignmentMarketSellRate sets the "assignment_market_sell_rate" field to the value that was provided on create. +func (u *PaymentOrderUpsertBulk) UpdateAssignmentMarketSellRate() *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.UpdateAssignmentMarketSellRate() + }) +} + +// ClearAssignmentMarketSellRate clears the value of the "assignment_market_sell_rate" field. +func (u *PaymentOrderUpsertBulk) ClearAssignmentMarketSellRate() *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.ClearAssignmentMarketSellRate() + }) +} + +// SetLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field. +func (u *PaymentOrderUpsertBulk) SetLegacyProvisionBucketID(v int) *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.SetLegacyProvisionBucketID(v) + }) +} + +// AddLegacyProvisionBucketID adds v to the "legacy_provision_bucket_id" field. +func (u *PaymentOrderUpsertBulk) AddLegacyProvisionBucketID(v int) *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.AddLegacyProvisionBucketID(v) + }) +} + +// UpdateLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field to the value that was provided on create. +func (u *PaymentOrderUpsertBulk) UpdateLegacyProvisionBucketID() *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.UpdateLegacyProvisionBucketID() + }) +} + +// ClearLegacyProvisionBucketID clears the value of the "legacy_provision_bucket_id" field. +func (u *PaymentOrderUpsertBulk) ClearLegacyProvisionBucketID() *PaymentOrderUpsertBulk { + return u.Update(func(s *PaymentOrderUpsert) { + s.ClearLegacyProvisionBucketID() + }) +} + // Exec executes the query. func (u *PaymentOrderUpsertBulk) Exec(ctx context.Context) error { if u.create.err != nil { diff --git a/ent/paymentorder_query.go b/ent/paymentorder_query.go index ccb5ec12f..f41f88959 100644 --- a/ent/paymentorder_query.go +++ b/ent/paymentorder_query.go @@ -17,8 +17,9 @@ import ( "github.com/paycrest/aggregator/ent/paymentorderfulfillment" "github.com/paycrest/aggregator/ent/paymentwebhook" "github.com/paycrest/aggregator/ent/predicate" + "github.com/paycrest/aggregator/ent/providerassignmentrun" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" "github.com/paycrest/aggregator/ent/providerprofile" - "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/paycrest/aggregator/ent/senderprofile" "github.com/paycrest/aggregator/ent/token" "github.com/paycrest/aggregator/ent/transactionlog" @@ -27,18 +28,19 @@ import ( // PaymentOrderQuery is the builder for querying PaymentOrder entities. type PaymentOrderQuery struct { config - ctx *QueryContext - order []paymentorder.OrderOption - inters []Interceptor - predicates []predicate.PaymentOrder - withToken *TokenQuery - withSenderProfile *SenderProfileQuery - withPaymentWebhook *PaymentWebhookQuery - withProvider *ProviderProfileQuery - withProvisionBucket *ProvisionBucketQuery - withFulfillments *PaymentOrderFulfillmentQuery - withTransactions *TransactionLogQuery - withFKs bool + ctx *QueryContext + order []paymentorder.OrderOption + inters []Interceptor + predicates []predicate.PaymentOrder + withToken *TokenQuery + withSenderProfile *SenderProfileQuery + withPaymentWebhook *PaymentWebhookQuery + withProvider *ProviderProfileQuery + withFulfillments *PaymentOrderFulfillmentQuery + withTransactions *TransactionLogQuery + withProviderAssignmentRuns *ProviderAssignmentRunQuery + withProviderOrderTokenScoreHistories *ProviderOrderTokenScoreHistoryQuery + withFKs bool // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -163,9 +165,9 @@ func (_q *PaymentOrderQuery) QueryProvider() *ProviderProfileQuery { return query } -// QueryProvisionBucket chains the current query on the "provision_bucket" edge. -func (_q *PaymentOrderQuery) QueryProvisionBucket() *ProvisionBucketQuery { - query := (&ProvisionBucketClient{config: _q.config}).Query() +// QueryFulfillments chains the current query on the "fulfillments" edge. +func (_q *PaymentOrderQuery) QueryFulfillments() *PaymentOrderFulfillmentQuery { + query := (&PaymentOrderFulfillmentClient{config: _q.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := _q.prepareQuery(ctx); err != nil { return nil, err @@ -176,8 +178,8 @@ func (_q *PaymentOrderQuery) QueryProvisionBucket() *ProvisionBucketQuery { } step := sqlgraph.NewStep( sqlgraph.From(paymentorder.Table, paymentorder.FieldID, selector), - sqlgraph.To(provisionbucket.Table, provisionbucket.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, paymentorder.ProvisionBucketTable, paymentorder.ProvisionBucketColumn), + sqlgraph.To(paymentorderfulfillment.Table, paymentorderfulfillment.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.FulfillmentsTable, paymentorder.FulfillmentsColumn), ) fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) return fromU, nil @@ -185,9 +187,9 @@ func (_q *PaymentOrderQuery) QueryProvisionBucket() *ProvisionBucketQuery { return query } -// QueryFulfillments chains the current query on the "fulfillments" edge. -func (_q *PaymentOrderQuery) QueryFulfillments() *PaymentOrderFulfillmentQuery { - query := (&PaymentOrderFulfillmentClient{config: _q.config}).Query() +// QueryTransactions chains the current query on the "transactions" edge. +func (_q *PaymentOrderQuery) QueryTransactions() *TransactionLogQuery { + query := (&TransactionLogClient{config: _q.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := _q.prepareQuery(ctx); err != nil { return nil, err @@ -198,8 +200,8 @@ func (_q *PaymentOrderQuery) QueryFulfillments() *PaymentOrderFulfillmentQuery { } step := sqlgraph.NewStep( sqlgraph.From(paymentorder.Table, paymentorder.FieldID, selector), - sqlgraph.To(paymentorderfulfillment.Table, paymentorderfulfillment.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.FulfillmentsTable, paymentorder.FulfillmentsColumn), + sqlgraph.To(transactionlog.Table, transactionlog.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.TransactionsTable, paymentorder.TransactionsColumn), ) fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) return fromU, nil @@ -207,9 +209,9 @@ func (_q *PaymentOrderQuery) QueryFulfillments() *PaymentOrderFulfillmentQuery { return query } -// QueryTransactions chains the current query on the "transactions" edge. -func (_q *PaymentOrderQuery) QueryTransactions() *TransactionLogQuery { - query := (&TransactionLogClient{config: _q.config}).Query() +// QueryProviderAssignmentRuns chains the current query on the "provider_assignment_runs" edge. +func (_q *PaymentOrderQuery) QueryProviderAssignmentRuns() *ProviderAssignmentRunQuery { + query := (&ProviderAssignmentRunClient{config: _q.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := _q.prepareQuery(ctx); err != nil { return nil, err @@ -220,8 +222,30 @@ func (_q *PaymentOrderQuery) QueryTransactions() *TransactionLogQuery { } step := sqlgraph.NewStep( sqlgraph.From(paymentorder.Table, paymentorder.FieldID, selector), - sqlgraph.To(transactionlog.Table, transactionlog.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.TransactionsTable, paymentorder.TransactionsColumn), + sqlgraph.To(providerassignmentrun.Table, providerassignmentrun.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.ProviderAssignmentRunsTable, paymentorder.ProviderAssignmentRunsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryProviderOrderTokenScoreHistories chains the current query on the "provider_order_token_score_histories" edge. +func (_q *PaymentOrderQuery) QueryProviderOrderTokenScoreHistories() *ProviderOrderTokenScoreHistoryQuery { + query := (&ProviderOrderTokenScoreHistoryClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(paymentorder.Table, paymentorder.FieldID, selector), + sqlgraph.To(providerordertokenscorehistory.Table, providerordertokenscorehistory.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, paymentorder.ProviderOrderTokenScoreHistoriesTable, paymentorder.ProviderOrderTokenScoreHistoriesColumn), ) fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) return fromU, nil @@ -416,18 +440,19 @@ func (_q *PaymentOrderQuery) Clone() *PaymentOrderQuery { return nil } return &PaymentOrderQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]paymentorder.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.PaymentOrder{}, _q.predicates...), - withToken: _q.withToken.Clone(), - withSenderProfile: _q.withSenderProfile.Clone(), - withPaymentWebhook: _q.withPaymentWebhook.Clone(), - withProvider: _q.withProvider.Clone(), - withProvisionBucket: _q.withProvisionBucket.Clone(), - withFulfillments: _q.withFulfillments.Clone(), - withTransactions: _q.withTransactions.Clone(), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]paymentorder.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.PaymentOrder{}, _q.predicates...), + withToken: _q.withToken.Clone(), + withSenderProfile: _q.withSenderProfile.Clone(), + withPaymentWebhook: _q.withPaymentWebhook.Clone(), + withProvider: _q.withProvider.Clone(), + withFulfillments: _q.withFulfillments.Clone(), + withTransactions: _q.withTransactions.Clone(), + withProviderAssignmentRuns: _q.withProviderAssignmentRuns.Clone(), + withProviderOrderTokenScoreHistories: _q.withProviderOrderTokenScoreHistories.Clone(), // clone intermediate query. sql: _q.sql.Clone(), path: _q.path, @@ -478,17 +503,6 @@ func (_q *PaymentOrderQuery) WithProvider(opts ...func(*ProviderProfileQuery)) * return _q } -// WithProvisionBucket tells the query-builder to eager-load the nodes that are connected to -// the "provision_bucket" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *PaymentOrderQuery) WithProvisionBucket(opts ...func(*ProvisionBucketQuery)) *PaymentOrderQuery { - query := (&ProvisionBucketClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withProvisionBucket = query - return _q -} - // WithFulfillments tells the query-builder to eager-load the nodes that are connected to // the "fulfillments" edge. The optional arguments are used to configure the query builder of the edge. func (_q *PaymentOrderQuery) WithFulfillments(opts ...func(*PaymentOrderFulfillmentQuery)) *PaymentOrderQuery { @@ -511,6 +525,28 @@ func (_q *PaymentOrderQuery) WithTransactions(opts ...func(*TransactionLogQuery) return _q } +// WithProviderAssignmentRuns tells the query-builder to eager-load the nodes that are connected to +// the "provider_assignment_runs" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *PaymentOrderQuery) WithProviderAssignmentRuns(opts ...func(*ProviderAssignmentRunQuery)) *PaymentOrderQuery { + query := (&ProviderAssignmentRunClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withProviderAssignmentRuns = query + return _q +} + +// WithProviderOrderTokenScoreHistories tells the query-builder to eager-load the nodes that are connected to +// the "provider_order_token_score_histories" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *PaymentOrderQuery) WithProviderOrderTokenScoreHistories(opts ...func(*ProviderOrderTokenScoreHistoryQuery)) *PaymentOrderQuery { + query := (&ProviderOrderTokenScoreHistoryClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withProviderOrderTokenScoreHistories = query + return _q +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -590,17 +626,18 @@ func (_q *PaymentOrderQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([] nodes = []*PaymentOrder{} withFKs = _q.withFKs _spec = _q.querySpec() - loadedTypes = [7]bool{ + loadedTypes = [8]bool{ _q.withToken != nil, _q.withSenderProfile != nil, _q.withPaymentWebhook != nil, _q.withProvider != nil, - _q.withProvisionBucket != nil, _q.withFulfillments != nil, _q.withTransactions != nil, + _q.withProviderAssignmentRuns != nil, + _q.withProviderOrderTokenScoreHistories != nil, } ) - if _q.withToken != nil || _q.withSenderProfile != nil || _q.withProvider != nil || _q.withProvisionBucket != nil { + if _q.withToken != nil || _q.withSenderProfile != nil || _q.withProvider != nil { withFKs = true } if withFKs { @@ -648,12 +685,6 @@ func (_q *PaymentOrderQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([] return nil, err } } - if query := _q.withProvisionBucket; query != nil { - if err := _q.loadProvisionBucket(ctx, query, nodes, nil, - func(n *PaymentOrder, e *ProvisionBucket) { n.Edges.ProvisionBucket = e }); err != nil { - return nil, err - } - } if query := _q.withFulfillments; query != nil { if err := _q.loadFulfillments(ctx, query, nodes, func(n *PaymentOrder) { n.Edges.Fulfillments = []*PaymentOrderFulfillment{} }, @@ -670,6 +701,24 @@ func (_q *PaymentOrderQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([] return nil, err } } + if query := _q.withProviderAssignmentRuns; query != nil { + if err := _q.loadProviderAssignmentRuns(ctx, query, nodes, + func(n *PaymentOrder) { n.Edges.ProviderAssignmentRuns = []*ProviderAssignmentRun{} }, + func(n *PaymentOrder, e *ProviderAssignmentRun) { + n.Edges.ProviderAssignmentRuns = append(n.Edges.ProviderAssignmentRuns, e) + }); err != nil { + return nil, err + } + } + if query := _q.withProviderOrderTokenScoreHistories; query != nil { + if err := _q.loadProviderOrderTokenScoreHistories(ctx, query, nodes, + func(n *PaymentOrder) { n.Edges.ProviderOrderTokenScoreHistories = []*ProviderOrderTokenScoreHistory{} }, + func(n *PaymentOrder, e *ProviderOrderTokenScoreHistory) { + n.Edges.ProviderOrderTokenScoreHistories = append(n.Edges.ProviderOrderTokenScoreHistories, e) + }); err != nil { + return nil, err + } + } return nodes, nil } @@ -797,39 +846,69 @@ func (_q *PaymentOrderQuery) loadProvider(ctx context.Context, query *ProviderPr } return nil } -func (_q *PaymentOrderQuery) loadProvisionBucket(ctx context.Context, query *ProvisionBucketQuery, nodes []*PaymentOrder, init func(*PaymentOrder), assign func(*PaymentOrder, *ProvisionBucket)) error { - ids := make([]int, 0, len(nodes)) - nodeids := make(map[int][]*PaymentOrder) +func (_q *PaymentOrderQuery) loadFulfillments(ctx context.Context, query *PaymentOrderFulfillmentQuery, nodes []*PaymentOrder, init func(*PaymentOrder), assign func(*PaymentOrder, *PaymentOrderFulfillment)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*PaymentOrder) for i := range nodes { - if nodes[i].provision_bucket_payment_orders == nil { - continue + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) } - fk := *nodes[i].provision_bucket_payment_orders - if _, ok := nodeids[fk]; !ok { - ids = append(ids, fk) + } + query.withFKs = true + query.Where(predicate.PaymentOrderFulfillment(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(paymentorder.FulfillmentsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.payment_order_fulfillments + if fk == nil { + return fmt.Errorf(`foreign-key "payment_order_fulfillments" is nil for node %v`, n.ID) } - nodeids[fk] = append(nodeids[fk], nodes[i]) + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "payment_order_fulfillments" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) } - if len(ids) == 0 { - return nil + return nil +} +func (_q *PaymentOrderQuery) loadTransactions(ctx context.Context, query *TransactionLogQuery, nodes []*PaymentOrder, init func(*PaymentOrder), assign func(*PaymentOrder, *TransactionLog)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*PaymentOrder) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } } - query.Where(provisionbucket.IDIn(ids...)) + query.withFKs = true + query.Where(predicate.TransactionLog(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(paymentorder.TransactionsColumn), fks...)) + })) neighbors, err := query.All(ctx) if err != nil { return err } for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return fmt.Errorf(`unexpected foreign-key "provision_bucket_payment_orders" returned %v`, n.ID) + fk := n.payment_order_transactions + if fk == nil { + return fmt.Errorf(`foreign-key "payment_order_transactions" is nil for node %v`, n.ID) } - for i := range nodes { - assign(nodes[i], n) + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "payment_order_transactions" returned %v for node %v`, *fk, n.ID) } + assign(node, n) } return nil } -func (_q *PaymentOrderQuery) loadFulfillments(ctx context.Context, query *PaymentOrderFulfillmentQuery, nodes []*PaymentOrder, init func(*PaymentOrder), assign func(*PaymentOrder, *PaymentOrderFulfillment)) error { +func (_q *PaymentOrderQuery) loadProviderAssignmentRuns(ctx context.Context, query *ProviderAssignmentRunQuery, nodes []*PaymentOrder, init func(*PaymentOrder), assign func(*PaymentOrder, *ProviderAssignmentRun)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[uuid.UUID]*PaymentOrder) for i := range nodes { @@ -840,27 +919,27 @@ func (_q *PaymentOrderQuery) loadFulfillments(ctx context.Context, query *Paymen } } query.withFKs = true - query.Where(predicate.PaymentOrderFulfillment(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(paymentorder.FulfillmentsColumn), fks...)) + query.Where(predicate.ProviderAssignmentRun(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(paymentorder.ProviderAssignmentRunsColumn), fks...)) })) neighbors, err := query.All(ctx) if err != nil { return err } for _, n := range neighbors { - fk := n.payment_order_fulfillments + fk := n.payment_order_provider_assignment_runs if fk == nil { - return fmt.Errorf(`foreign-key "payment_order_fulfillments" is nil for node %v`, n.ID) + return fmt.Errorf(`foreign-key "payment_order_provider_assignment_runs" is nil for node %v`, n.ID) } node, ok := nodeids[*fk] if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "payment_order_fulfillments" returned %v for node %v`, *fk, n.ID) + return fmt.Errorf(`unexpected referenced foreign-key "payment_order_provider_assignment_runs" returned %v for node %v`, *fk, n.ID) } assign(node, n) } return nil } -func (_q *PaymentOrderQuery) loadTransactions(ctx context.Context, query *TransactionLogQuery, nodes []*PaymentOrder, init func(*PaymentOrder), assign func(*PaymentOrder, *TransactionLog)) error { +func (_q *PaymentOrderQuery) loadProviderOrderTokenScoreHistories(ctx context.Context, query *ProviderOrderTokenScoreHistoryQuery, nodes []*PaymentOrder, init func(*PaymentOrder), assign func(*PaymentOrder, *ProviderOrderTokenScoreHistory)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[uuid.UUID]*PaymentOrder) for i := range nodes { @@ -871,21 +950,21 @@ func (_q *PaymentOrderQuery) loadTransactions(ctx context.Context, query *Transa } } query.withFKs = true - query.Where(predicate.TransactionLog(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(paymentorder.TransactionsColumn), fks...)) + query.Where(predicate.ProviderOrderTokenScoreHistory(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(paymentorder.ProviderOrderTokenScoreHistoriesColumn), fks...)) })) neighbors, err := query.All(ctx) if err != nil { return err } for _, n := range neighbors { - fk := n.payment_order_transactions + fk := n.payment_order_provider_order_token_score_histories if fk == nil { - return fmt.Errorf(`foreign-key "payment_order_transactions" is nil for node %v`, n.ID) + return fmt.Errorf(`foreign-key "payment_order_provider_order_token_score_histories" is nil for node %v`, n.ID) } node, ok := nodeids[*fk] if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "payment_order_transactions" returned %v for node %v`, *fk, n.ID) + return fmt.Errorf(`unexpected referenced foreign-key "payment_order_provider_order_token_score_histories" returned %v for node %v`, *fk, n.ID) } assign(node, n) } diff --git a/ent/paymentorder_update.go b/ent/paymentorder_update.go index bceecbecf..a13da7751 100644 --- a/ent/paymentorder_update.go +++ b/ent/paymentorder_update.go @@ -17,8 +17,9 @@ import ( "github.com/paycrest/aggregator/ent/paymentorderfulfillment" "github.com/paycrest/aggregator/ent/paymentwebhook" "github.com/paycrest/aggregator/ent/predicate" + "github.com/paycrest/aggregator/ent/providerassignmentrun" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" "github.com/paycrest/aggregator/ent/providerprofile" - "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/paycrest/aggregator/ent/senderprofile" "github.com/paycrest/aggregator/ent/token" "github.com/paycrest/aggregator/ent/transactionlog" @@ -709,6 +710,87 @@ func (_u *PaymentOrderUpdate) ClearFallbackTriedAt() *PaymentOrderUpdate { return _u } +// SetAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field. +func (_u *PaymentOrderUpdate) SetAssignmentMarketBuyRate(v decimal.Decimal) *PaymentOrderUpdate { + _u.mutation.ResetAssignmentMarketBuyRate() + _u.mutation.SetAssignmentMarketBuyRate(v) + return _u +} + +// SetNillableAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field if the given value is not nil. +func (_u *PaymentOrderUpdate) SetNillableAssignmentMarketBuyRate(v *decimal.Decimal) *PaymentOrderUpdate { + if v != nil { + _u.SetAssignmentMarketBuyRate(*v) + } + return _u +} + +// AddAssignmentMarketBuyRate adds value to the "assignment_market_buy_rate" field. +func (_u *PaymentOrderUpdate) AddAssignmentMarketBuyRate(v decimal.Decimal) *PaymentOrderUpdate { + _u.mutation.AddAssignmentMarketBuyRate(v) + return _u +} + +// ClearAssignmentMarketBuyRate clears the value of the "assignment_market_buy_rate" field. +func (_u *PaymentOrderUpdate) ClearAssignmentMarketBuyRate() *PaymentOrderUpdate { + _u.mutation.ClearAssignmentMarketBuyRate() + return _u +} + +// SetAssignmentMarketSellRate sets the "assignment_market_sell_rate" field. +func (_u *PaymentOrderUpdate) SetAssignmentMarketSellRate(v decimal.Decimal) *PaymentOrderUpdate { + _u.mutation.ResetAssignmentMarketSellRate() + _u.mutation.SetAssignmentMarketSellRate(v) + return _u +} + +// SetNillableAssignmentMarketSellRate sets the "assignment_market_sell_rate" field if the given value is not nil. +func (_u *PaymentOrderUpdate) SetNillableAssignmentMarketSellRate(v *decimal.Decimal) *PaymentOrderUpdate { + if v != nil { + _u.SetAssignmentMarketSellRate(*v) + } + return _u +} + +// AddAssignmentMarketSellRate adds value to the "assignment_market_sell_rate" field. +func (_u *PaymentOrderUpdate) AddAssignmentMarketSellRate(v decimal.Decimal) *PaymentOrderUpdate { + _u.mutation.AddAssignmentMarketSellRate(v) + return _u +} + +// ClearAssignmentMarketSellRate clears the value of the "assignment_market_sell_rate" field. +func (_u *PaymentOrderUpdate) ClearAssignmentMarketSellRate() *PaymentOrderUpdate { + _u.mutation.ClearAssignmentMarketSellRate() + return _u +} + +// SetLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field. +func (_u *PaymentOrderUpdate) SetLegacyProvisionBucketID(v int) *PaymentOrderUpdate { + _u.mutation.ResetLegacyProvisionBucketID() + _u.mutation.SetLegacyProvisionBucketID(v) + return _u +} + +// SetNillableLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field if the given value is not nil. +func (_u *PaymentOrderUpdate) SetNillableLegacyProvisionBucketID(v *int) *PaymentOrderUpdate { + if v != nil { + _u.SetLegacyProvisionBucketID(*v) + } + return _u +} + +// AddLegacyProvisionBucketID adds value to the "legacy_provision_bucket_id" field. +func (_u *PaymentOrderUpdate) AddLegacyProvisionBucketID(v int) *PaymentOrderUpdate { + _u.mutation.AddLegacyProvisionBucketID(v) + return _u +} + +// ClearLegacyProvisionBucketID clears the value of the "legacy_provision_bucket_id" field. +func (_u *PaymentOrderUpdate) ClearLegacyProvisionBucketID() *PaymentOrderUpdate { + _u.mutation.ClearLegacyProvisionBucketID() + return _u +} + // SetTokenID sets the "token" edge to the Token entity by ID. func (_u *PaymentOrderUpdate) SetTokenID(id int) *PaymentOrderUpdate { _u.mutation.SetTokenID(id) @@ -777,25 +859,6 @@ func (_u *PaymentOrderUpdate) SetProvider(v *ProviderProfile) *PaymentOrderUpdat return _u.SetProviderID(v.ID) } -// SetProvisionBucketID sets the "provision_bucket" edge to the ProvisionBucket entity by ID. -func (_u *PaymentOrderUpdate) SetProvisionBucketID(id int) *PaymentOrderUpdate { - _u.mutation.SetProvisionBucketID(id) - return _u -} - -// SetNillableProvisionBucketID sets the "provision_bucket" edge to the ProvisionBucket entity by ID if the given value is not nil. -func (_u *PaymentOrderUpdate) SetNillableProvisionBucketID(id *int) *PaymentOrderUpdate { - if id != nil { - _u = _u.SetProvisionBucketID(*id) - } - return _u -} - -// SetProvisionBucket sets the "provision_bucket" edge to the ProvisionBucket entity. -func (_u *PaymentOrderUpdate) SetProvisionBucket(v *ProvisionBucket) *PaymentOrderUpdate { - return _u.SetProvisionBucketID(v.ID) -} - // AddFulfillmentIDs adds the "fulfillments" edge to the PaymentOrderFulfillment entity by IDs. func (_u *PaymentOrderUpdate) AddFulfillmentIDs(ids ...uuid.UUID) *PaymentOrderUpdate { _u.mutation.AddFulfillmentIDs(ids...) @@ -826,6 +889,36 @@ func (_u *PaymentOrderUpdate) AddTransactions(v ...*TransactionLog) *PaymentOrde return _u.AddTransactionIDs(ids...) } +// AddProviderAssignmentRunIDs adds the "provider_assignment_runs" edge to the ProviderAssignmentRun entity by IDs. +func (_u *PaymentOrderUpdate) AddProviderAssignmentRunIDs(ids ...uuid.UUID) *PaymentOrderUpdate { + _u.mutation.AddProviderAssignmentRunIDs(ids...) + return _u +} + +// AddProviderAssignmentRuns adds the "provider_assignment_runs" edges to the ProviderAssignmentRun entity. +func (_u *PaymentOrderUpdate) AddProviderAssignmentRuns(v ...*ProviderAssignmentRun) *PaymentOrderUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddProviderAssignmentRunIDs(ids...) +} + +// AddProviderOrderTokenScoreHistoryIDs adds the "provider_order_token_score_histories" edge to the ProviderOrderTokenScoreHistory entity by IDs. +func (_u *PaymentOrderUpdate) AddProviderOrderTokenScoreHistoryIDs(ids ...uuid.UUID) *PaymentOrderUpdate { + _u.mutation.AddProviderOrderTokenScoreHistoryIDs(ids...) + return _u +} + +// AddProviderOrderTokenScoreHistories adds the "provider_order_token_score_histories" edges to the ProviderOrderTokenScoreHistory entity. +func (_u *PaymentOrderUpdate) AddProviderOrderTokenScoreHistories(v ...*ProviderOrderTokenScoreHistory) *PaymentOrderUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddProviderOrderTokenScoreHistoryIDs(ids...) +} + // Mutation returns the PaymentOrderMutation object of the builder. func (_u *PaymentOrderUpdate) Mutation() *PaymentOrderMutation { return _u.mutation @@ -855,12 +948,6 @@ func (_u *PaymentOrderUpdate) ClearProvider() *PaymentOrderUpdate { return _u } -// ClearProvisionBucket clears the "provision_bucket" edge to the ProvisionBucket entity. -func (_u *PaymentOrderUpdate) ClearProvisionBucket() *PaymentOrderUpdate { - _u.mutation.ClearProvisionBucket() - return _u -} - // ClearFulfillments clears all "fulfillments" edges to the PaymentOrderFulfillment entity. func (_u *PaymentOrderUpdate) ClearFulfillments() *PaymentOrderUpdate { _u.mutation.ClearFulfillments() @@ -903,6 +990,48 @@ func (_u *PaymentOrderUpdate) RemoveTransactions(v ...*TransactionLog) *PaymentO return _u.RemoveTransactionIDs(ids...) } +// ClearProviderAssignmentRuns clears all "provider_assignment_runs" edges to the ProviderAssignmentRun entity. +func (_u *PaymentOrderUpdate) ClearProviderAssignmentRuns() *PaymentOrderUpdate { + _u.mutation.ClearProviderAssignmentRuns() + return _u +} + +// RemoveProviderAssignmentRunIDs removes the "provider_assignment_runs" edge to ProviderAssignmentRun entities by IDs. +func (_u *PaymentOrderUpdate) RemoveProviderAssignmentRunIDs(ids ...uuid.UUID) *PaymentOrderUpdate { + _u.mutation.RemoveProviderAssignmentRunIDs(ids...) + return _u +} + +// RemoveProviderAssignmentRuns removes "provider_assignment_runs" edges to ProviderAssignmentRun entities. +func (_u *PaymentOrderUpdate) RemoveProviderAssignmentRuns(v ...*ProviderAssignmentRun) *PaymentOrderUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveProviderAssignmentRunIDs(ids...) +} + +// ClearProviderOrderTokenScoreHistories clears all "provider_order_token_score_histories" edges to the ProviderOrderTokenScoreHistory entity. +func (_u *PaymentOrderUpdate) ClearProviderOrderTokenScoreHistories() *PaymentOrderUpdate { + _u.mutation.ClearProviderOrderTokenScoreHistories() + return _u +} + +// RemoveProviderOrderTokenScoreHistoryIDs removes the "provider_order_token_score_histories" edge to ProviderOrderTokenScoreHistory entities by IDs. +func (_u *PaymentOrderUpdate) RemoveProviderOrderTokenScoreHistoryIDs(ids ...uuid.UUID) *PaymentOrderUpdate { + _u.mutation.RemoveProviderOrderTokenScoreHistoryIDs(ids...) + return _u +} + +// RemoveProviderOrderTokenScoreHistories removes "provider_order_token_score_histories" edges to ProviderOrderTokenScoreHistory entities. +func (_u *PaymentOrderUpdate) RemoveProviderOrderTokenScoreHistories(v ...*ProviderOrderTokenScoreHistory) *PaymentOrderUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveProviderOrderTokenScoreHistoryIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (_u *PaymentOrderUpdate) Save(ctx context.Context) (int, error) { _u.defaults() @@ -1237,6 +1366,33 @@ func (_u *PaymentOrderUpdate) sqlSave(ctx context.Context) (_node int, err error if _u.mutation.FallbackTriedAtCleared() { _spec.ClearField(paymentorder.FieldFallbackTriedAt, field.TypeTime) } + if value, ok := _u.mutation.AssignmentMarketBuyRate(); ok { + _spec.SetField(paymentorder.FieldAssignmentMarketBuyRate, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedAssignmentMarketBuyRate(); ok { + _spec.AddField(paymentorder.FieldAssignmentMarketBuyRate, field.TypeFloat64, value) + } + if _u.mutation.AssignmentMarketBuyRateCleared() { + _spec.ClearField(paymentorder.FieldAssignmentMarketBuyRate, field.TypeFloat64) + } + if value, ok := _u.mutation.AssignmentMarketSellRate(); ok { + _spec.SetField(paymentorder.FieldAssignmentMarketSellRate, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedAssignmentMarketSellRate(); ok { + _spec.AddField(paymentorder.FieldAssignmentMarketSellRate, field.TypeFloat64, value) + } + if _u.mutation.AssignmentMarketSellRateCleared() { + _spec.ClearField(paymentorder.FieldAssignmentMarketSellRate, field.TypeFloat64) + } + if value, ok := _u.mutation.LegacyProvisionBucketID(); ok { + _spec.SetField(paymentorder.FieldLegacyProvisionBucketID, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedLegacyProvisionBucketID(); ok { + _spec.AddField(paymentorder.FieldLegacyProvisionBucketID, field.TypeInt, value) + } + if _u.mutation.LegacyProvisionBucketIDCleared() { + _spec.ClearField(paymentorder.FieldLegacyProvisionBucketID, field.TypeInt) + } if _u.mutation.TokenCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -1353,35 +1509,6 @@ func (_u *PaymentOrderUpdate) sqlSave(ctx context.Context) (_node int, err error } _spec.Edges.Add = append(_spec.Edges.Add, edge) } - if _u.mutation.ProvisionBucketCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: paymentorder.ProvisionBucketTable, - Columns: []string{paymentorder.ProvisionBucketColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.ProvisionBucketIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: paymentorder.ProvisionBucketTable, - Columns: []string{paymentorder.ProvisionBucketColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } if _u.mutation.FulfillmentsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -1472,6 +1599,96 @@ func (_u *PaymentOrderUpdate) sqlSave(ctx context.Context) (_node int, err error } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.ProviderAssignmentRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderAssignmentRunsTable, + Columns: []string{paymentorder.ProviderAssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedProviderAssignmentRunsIDs(); len(nodes) > 0 && !_u.mutation.ProviderAssignmentRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderAssignmentRunsTable, + Columns: []string{paymentorder.ProviderAssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ProviderAssignmentRunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderAssignmentRunsTable, + Columns: []string{paymentorder.ProviderAssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ProviderOrderTokenScoreHistoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderOrderTokenScoreHistoriesTable, + Columns: []string{paymentorder.ProviderOrderTokenScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedProviderOrderTokenScoreHistoriesIDs(); len(nodes) > 0 && !_u.mutation.ProviderOrderTokenScoreHistoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderOrderTokenScoreHistoriesTable, + Columns: []string{paymentorder.ProviderOrderTokenScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ProviderOrderTokenScoreHistoriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderOrderTokenScoreHistoriesTable, + Columns: []string{paymentorder.ProviderOrderTokenScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{paymentorder.Label} @@ -2163,6 +2380,87 @@ func (_u *PaymentOrderUpdateOne) ClearFallbackTriedAt() *PaymentOrderUpdateOne { return _u } +// SetAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field. +func (_u *PaymentOrderUpdateOne) SetAssignmentMarketBuyRate(v decimal.Decimal) *PaymentOrderUpdateOne { + _u.mutation.ResetAssignmentMarketBuyRate() + _u.mutation.SetAssignmentMarketBuyRate(v) + return _u +} + +// SetNillableAssignmentMarketBuyRate sets the "assignment_market_buy_rate" field if the given value is not nil. +func (_u *PaymentOrderUpdateOne) SetNillableAssignmentMarketBuyRate(v *decimal.Decimal) *PaymentOrderUpdateOne { + if v != nil { + _u.SetAssignmentMarketBuyRate(*v) + } + return _u +} + +// AddAssignmentMarketBuyRate adds value to the "assignment_market_buy_rate" field. +func (_u *PaymentOrderUpdateOne) AddAssignmentMarketBuyRate(v decimal.Decimal) *PaymentOrderUpdateOne { + _u.mutation.AddAssignmentMarketBuyRate(v) + return _u +} + +// ClearAssignmentMarketBuyRate clears the value of the "assignment_market_buy_rate" field. +func (_u *PaymentOrderUpdateOne) ClearAssignmentMarketBuyRate() *PaymentOrderUpdateOne { + _u.mutation.ClearAssignmentMarketBuyRate() + return _u +} + +// SetAssignmentMarketSellRate sets the "assignment_market_sell_rate" field. +func (_u *PaymentOrderUpdateOne) SetAssignmentMarketSellRate(v decimal.Decimal) *PaymentOrderUpdateOne { + _u.mutation.ResetAssignmentMarketSellRate() + _u.mutation.SetAssignmentMarketSellRate(v) + return _u +} + +// SetNillableAssignmentMarketSellRate sets the "assignment_market_sell_rate" field if the given value is not nil. +func (_u *PaymentOrderUpdateOne) SetNillableAssignmentMarketSellRate(v *decimal.Decimal) *PaymentOrderUpdateOne { + if v != nil { + _u.SetAssignmentMarketSellRate(*v) + } + return _u +} + +// AddAssignmentMarketSellRate adds value to the "assignment_market_sell_rate" field. +func (_u *PaymentOrderUpdateOne) AddAssignmentMarketSellRate(v decimal.Decimal) *PaymentOrderUpdateOne { + _u.mutation.AddAssignmentMarketSellRate(v) + return _u +} + +// ClearAssignmentMarketSellRate clears the value of the "assignment_market_sell_rate" field. +func (_u *PaymentOrderUpdateOne) ClearAssignmentMarketSellRate() *PaymentOrderUpdateOne { + _u.mutation.ClearAssignmentMarketSellRate() + return _u +} + +// SetLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field. +func (_u *PaymentOrderUpdateOne) SetLegacyProvisionBucketID(v int) *PaymentOrderUpdateOne { + _u.mutation.ResetLegacyProvisionBucketID() + _u.mutation.SetLegacyProvisionBucketID(v) + return _u +} + +// SetNillableLegacyProvisionBucketID sets the "legacy_provision_bucket_id" field if the given value is not nil. +func (_u *PaymentOrderUpdateOne) SetNillableLegacyProvisionBucketID(v *int) *PaymentOrderUpdateOne { + if v != nil { + _u.SetLegacyProvisionBucketID(*v) + } + return _u +} + +// AddLegacyProvisionBucketID adds value to the "legacy_provision_bucket_id" field. +func (_u *PaymentOrderUpdateOne) AddLegacyProvisionBucketID(v int) *PaymentOrderUpdateOne { + _u.mutation.AddLegacyProvisionBucketID(v) + return _u +} + +// ClearLegacyProvisionBucketID clears the value of the "legacy_provision_bucket_id" field. +func (_u *PaymentOrderUpdateOne) ClearLegacyProvisionBucketID() *PaymentOrderUpdateOne { + _u.mutation.ClearLegacyProvisionBucketID() + return _u +} + // SetTokenID sets the "token" edge to the Token entity by ID. func (_u *PaymentOrderUpdateOne) SetTokenID(id int) *PaymentOrderUpdateOne { _u.mutation.SetTokenID(id) @@ -2231,25 +2529,6 @@ func (_u *PaymentOrderUpdateOne) SetProvider(v *ProviderProfile) *PaymentOrderUp return _u.SetProviderID(v.ID) } -// SetProvisionBucketID sets the "provision_bucket" edge to the ProvisionBucket entity by ID. -func (_u *PaymentOrderUpdateOne) SetProvisionBucketID(id int) *PaymentOrderUpdateOne { - _u.mutation.SetProvisionBucketID(id) - return _u -} - -// SetNillableProvisionBucketID sets the "provision_bucket" edge to the ProvisionBucket entity by ID if the given value is not nil. -func (_u *PaymentOrderUpdateOne) SetNillableProvisionBucketID(id *int) *PaymentOrderUpdateOne { - if id != nil { - _u = _u.SetProvisionBucketID(*id) - } - return _u -} - -// SetProvisionBucket sets the "provision_bucket" edge to the ProvisionBucket entity. -func (_u *PaymentOrderUpdateOne) SetProvisionBucket(v *ProvisionBucket) *PaymentOrderUpdateOne { - return _u.SetProvisionBucketID(v.ID) -} - // AddFulfillmentIDs adds the "fulfillments" edge to the PaymentOrderFulfillment entity by IDs. func (_u *PaymentOrderUpdateOne) AddFulfillmentIDs(ids ...uuid.UUID) *PaymentOrderUpdateOne { _u.mutation.AddFulfillmentIDs(ids...) @@ -2280,6 +2559,36 @@ func (_u *PaymentOrderUpdateOne) AddTransactions(v ...*TransactionLog) *PaymentO return _u.AddTransactionIDs(ids...) } +// AddProviderAssignmentRunIDs adds the "provider_assignment_runs" edge to the ProviderAssignmentRun entity by IDs. +func (_u *PaymentOrderUpdateOne) AddProviderAssignmentRunIDs(ids ...uuid.UUID) *PaymentOrderUpdateOne { + _u.mutation.AddProviderAssignmentRunIDs(ids...) + return _u +} + +// AddProviderAssignmentRuns adds the "provider_assignment_runs" edges to the ProviderAssignmentRun entity. +func (_u *PaymentOrderUpdateOne) AddProviderAssignmentRuns(v ...*ProviderAssignmentRun) *PaymentOrderUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddProviderAssignmentRunIDs(ids...) +} + +// AddProviderOrderTokenScoreHistoryIDs adds the "provider_order_token_score_histories" edge to the ProviderOrderTokenScoreHistory entity by IDs. +func (_u *PaymentOrderUpdateOne) AddProviderOrderTokenScoreHistoryIDs(ids ...uuid.UUID) *PaymentOrderUpdateOne { + _u.mutation.AddProviderOrderTokenScoreHistoryIDs(ids...) + return _u +} + +// AddProviderOrderTokenScoreHistories adds the "provider_order_token_score_histories" edges to the ProviderOrderTokenScoreHistory entity. +func (_u *PaymentOrderUpdateOne) AddProviderOrderTokenScoreHistories(v ...*ProviderOrderTokenScoreHistory) *PaymentOrderUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddProviderOrderTokenScoreHistoryIDs(ids...) +} + // Mutation returns the PaymentOrderMutation object of the builder. func (_u *PaymentOrderUpdateOne) Mutation() *PaymentOrderMutation { return _u.mutation @@ -2309,12 +2618,6 @@ func (_u *PaymentOrderUpdateOne) ClearProvider() *PaymentOrderUpdateOne { return _u } -// ClearProvisionBucket clears the "provision_bucket" edge to the ProvisionBucket entity. -func (_u *PaymentOrderUpdateOne) ClearProvisionBucket() *PaymentOrderUpdateOne { - _u.mutation.ClearProvisionBucket() - return _u -} - // ClearFulfillments clears all "fulfillments" edges to the PaymentOrderFulfillment entity. func (_u *PaymentOrderUpdateOne) ClearFulfillments() *PaymentOrderUpdateOne { _u.mutation.ClearFulfillments() @@ -2357,6 +2660,48 @@ func (_u *PaymentOrderUpdateOne) RemoveTransactions(v ...*TransactionLog) *Payme return _u.RemoveTransactionIDs(ids...) } +// ClearProviderAssignmentRuns clears all "provider_assignment_runs" edges to the ProviderAssignmentRun entity. +func (_u *PaymentOrderUpdateOne) ClearProviderAssignmentRuns() *PaymentOrderUpdateOne { + _u.mutation.ClearProviderAssignmentRuns() + return _u +} + +// RemoveProviderAssignmentRunIDs removes the "provider_assignment_runs" edge to ProviderAssignmentRun entities by IDs. +func (_u *PaymentOrderUpdateOne) RemoveProviderAssignmentRunIDs(ids ...uuid.UUID) *PaymentOrderUpdateOne { + _u.mutation.RemoveProviderAssignmentRunIDs(ids...) + return _u +} + +// RemoveProviderAssignmentRuns removes "provider_assignment_runs" edges to ProviderAssignmentRun entities. +func (_u *PaymentOrderUpdateOne) RemoveProviderAssignmentRuns(v ...*ProviderAssignmentRun) *PaymentOrderUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveProviderAssignmentRunIDs(ids...) +} + +// ClearProviderOrderTokenScoreHistories clears all "provider_order_token_score_histories" edges to the ProviderOrderTokenScoreHistory entity. +func (_u *PaymentOrderUpdateOne) ClearProviderOrderTokenScoreHistories() *PaymentOrderUpdateOne { + _u.mutation.ClearProviderOrderTokenScoreHistories() + return _u +} + +// RemoveProviderOrderTokenScoreHistoryIDs removes the "provider_order_token_score_histories" edge to ProviderOrderTokenScoreHistory entities by IDs. +func (_u *PaymentOrderUpdateOne) RemoveProviderOrderTokenScoreHistoryIDs(ids ...uuid.UUID) *PaymentOrderUpdateOne { + _u.mutation.RemoveProviderOrderTokenScoreHistoryIDs(ids...) + return _u +} + +// RemoveProviderOrderTokenScoreHistories removes "provider_order_token_score_histories" edges to ProviderOrderTokenScoreHistory entities. +func (_u *PaymentOrderUpdateOne) RemoveProviderOrderTokenScoreHistories(v ...*ProviderOrderTokenScoreHistory) *PaymentOrderUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveProviderOrderTokenScoreHistoryIDs(ids...) +} + // Where appends a list predicates to the PaymentOrderUpdate builder. func (_u *PaymentOrderUpdateOne) Where(ps ...predicate.PaymentOrder) *PaymentOrderUpdateOne { _u.mutation.Where(ps...) @@ -2721,6 +3066,33 @@ func (_u *PaymentOrderUpdateOne) sqlSave(ctx context.Context) (_node *PaymentOrd if _u.mutation.FallbackTriedAtCleared() { _spec.ClearField(paymentorder.FieldFallbackTriedAt, field.TypeTime) } + if value, ok := _u.mutation.AssignmentMarketBuyRate(); ok { + _spec.SetField(paymentorder.FieldAssignmentMarketBuyRate, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedAssignmentMarketBuyRate(); ok { + _spec.AddField(paymentorder.FieldAssignmentMarketBuyRate, field.TypeFloat64, value) + } + if _u.mutation.AssignmentMarketBuyRateCleared() { + _spec.ClearField(paymentorder.FieldAssignmentMarketBuyRate, field.TypeFloat64) + } + if value, ok := _u.mutation.AssignmentMarketSellRate(); ok { + _spec.SetField(paymentorder.FieldAssignmentMarketSellRate, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedAssignmentMarketSellRate(); ok { + _spec.AddField(paymentorder.FieldAssignmentMarketSellRate, field.TypeFloat64, value) + } + if _u.mutation.AssignmentMarketSellRateCleared() { + _spec.ClearField(paymentorder.FieldAssignmentMarketSellRate, field.TypeFloat64) + } + if value, ok := _u.mutation.LegacyProvisionBucketID(); ok { + _spec.SetField(paymentorder.FieldLegacyProvisionBucketID, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedLegacyProvisionBucketID(); ok { + _spec.AddField(paymentorder.FieldLegacyProvisionBucketID, field.TypeInt, value) + } + if _u.mutation.LegacyProvisionBucketIDCleared() { + _spec.ClearField(paymentorder.FieldLegacyProvisionBucketID, field.TypeInt) + } if _u.mutation.TokenCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -2837,35 +3209,6 @@ func (_u *PaymentOrderUpdateOne) sqlSave(ctx context.Context) (_node *PaymentOrd } _spec.Edges.Add = append(_spec.Edges.Add, edge) } - if _u.mutation.ProvisionBucketCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: paymentorder.ProvisionBucketTable, - Columns: []string{paymentorder.ProvisionBucketColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.ProvisionBucketIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: paymentorder.ProvisionBucketTable, - Columns: []string{paymentorder.ProvisionBucketColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } if _u.mutation.FulfillmentsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -2956,6 +3299,96 @@ func (_u *PaymentOrderUpdateOne) sqlSave(ctx context.Context) (_node *PaymentOrd } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.ProviderAssignmentRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderAssignmentRunsTable, + Columns: []string{paymentorder.ProviderAssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedProviderAssignmentRunsIDs(); len(nodes) > 0 && !_u.mutation.ProviderAssignmentRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderAssignmentRunsTable, + Columns: []string{paymentorder.ProviderAssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ProviderAssignmentRunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderAssignmentRunsTable, + Columns: []string{paymentorder.ProviderAssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ProviderOrderTokenScoreHistoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderOrderTokenScoreHistoriesTable, + Columns: []string{paymentorder.ProviderOrderTokenScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedProviderOrderTokenScoreHistoriesIDs(); len(nodes) > 0 && !_u.mutation.ProviderOrderTokenScoreHistoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderOrderTokenScoreHistoriesTable, + Columns: []string{paymentorder.ProviderOrderTokenScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ProviderOrderTokenScoreHistoriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: paymentorder.ProviderOrderTokenScoreHistoriesTable, + Columns: []string{paymentorder.ProviderOrderTokenScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &PaymentOrder{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go index 70a960e1d..5e600c485 100644 --- a/ent/predicate/predicate.go +++ b/ent/predicate/predicate.go @@ -36,6 +36,9 @@ type PaymentOrderFulfillment func(*sql.Selector) // PaymentWebhook is the predicate function for paymentwebhook builders. type PaymentWebhook func(*sql.Selector) +// ProviderAssignmentRun is the predicate function for providerassignmentrun builders. +type ProviderAssignmentRun func(*sql.Selector) + // ProviderBalances is the predicate function for providerbalances builders. type ProviderBalances func(*sql.Selector) @@ -45,6 +48,9 @@ type ProviderFiatAccount func(*sql.Selector) // ProviderOrderToken is the predicate function for providerordertoken builders. type ProviderOrderToken func(*sql.Selector) +// ProviderOrderTokenScoreHistory is the predicate function for providerordertokenscorehistory builders. +type ProviderOrderTokenScoreHistory func(*sql.Selector) + // ProviderProfile is the predicate function for providerprofile builders. type ProviderProfile func(*sql.Selector) diff --git a/ent/providerassignmentrun.go b/ent/providerassignmentrun.go new file mode 100644 index 000000000..1bfe4e8c1 --- /dev/null +++ b/ent/providerassignmentrun.go @@ -0,0 +1,269 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/providerassignmentrun" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/shopspring/decimal" +) + +// ProviderAssignmentRun is the model entity for the ProviderAssignmentRun schema. +type ProviderAssignmentRun struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // AssignedProviderID holds the value of the "assigned_provider_id" field. + AssignedProviderID *string `json:"assigned_provider_id,omitempty"` + // AttemptedAt holds the value of the "attempted_at" field. + AttemptedAt time.Time `json:"attempted_at,omitempty"` + // Trigger holds the value of the "trigger" field. + Trigger string `json:"trigger,omitempty"` + // Result holds the value of the "result" field. + Result string `json:"result,omitempty"` + // UsedFallback holds the value of the "used_fallback" field. + UsedFallback bool `json:"used_fallback,omitempty"` + // MarketBuyRateSnapshot holds the value of the "market_buy_rate_snapshot" field. + MarketBuyRateSnapshot *decimal.Decimal `json:"market_buy_rate_snapshot,omitempty"` + // MarketSellRateSnapshot holds the value of the "market_sell_rate_snapshot" field. + MarketSellRateSnapshot *decimal.Decimal `json:"market_sell_rate_snapshot,omitempty"` + // ErrorMessage holds the value of the "error_message" field. + ErrorMessage *string `json:"error_message,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ProviderAssignmentRunQuery when eager-loading is set. + Edges ProviderAssignmentRunEdges `json:"edges"` + payment_order_provider_assignment_runs *uuid.UUID + provider_order_token_assignment_runs *int + selectValues sql.SelectValues +} + +// ProviderAssignmentRunEdges holds the relations/edges for other nodes in the graph. +type ProviderAssignmentRunEdges struct { + // PaymentOrder holds the value of the payment_order edge. + PaymentOrder *PaymentOrder `json:"payment_order,omitempty"` + // ProviderOrderToken holds the value of the provider_order_token edge. + ProviderOrderToken *ProviderOrderToken `json:"provider_order_token,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// PaymentOrderOrErr returns the PaymentOrder value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ProviderAssignmentRunEdges) PaymentOrderOrErr() (*PaymentOrder, error) { + if e.PaymentOrder != nil { + return e.PaymentOrder, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: paymentorder.Label} + } + return nil, &NotLoadedError{edge: "payment_order"} +} + +// ProviderOrderTokenOrErr returns the ProviderOrderToken value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ProviderAssignmentRunEdges) ProviderOrderTokenOrErr() (*ProviderOrderToken, error) { + if e.ProviderOrderToken != nil { + return e.ProviderOrderToken, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: providerordertoken.Label} + } + return nil, &NotLoadedError{edge: "provider_order_token"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ProviderAssignmentRun) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case providerassignmentrun.FieldMarketBuyRateSnapshot, providerassignmentrun.FieldMarketSellRateSnapshot: + values[i] = &sql.NullScanner{S: new(decimal.Decimal)} + case providerassignmentrun.FieldUsedFallback: + values[i] = new(sql.NullBool) + case providerassignmentrun.FieldAssignedProviderID, providerassignmentrun.FieldTrigger, providerassignmentrun.FieldResult, providerassignmentrun.FieldErrorMessage: + values[i] = new(sql.NullString) + case providerassignmentrun.FieldAttemptedAt: + values[i] = new(sql.NullTime) + case providerassignmentrun.FieldID: + values[i] = new(uuid.UUID) + case providerassignmentrun.ForeignKeys[0]: // payment_order_provider_assignment_runs + values[i] = &sql.NullScanner{S: new(uuid.UUID)} + case providerassignmentrun.ForeignKeys[1]: // provider_order_token_assignment_runs + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ProviderAssignmentRun fields. +func (_m *ProviderAssignmentRun) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case providerassignmentrun.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case providerassignmentrun.FieldAssignedProviderID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field assigned_provider_id", values[i]) + } else if value.Valid { + _m.AssignedProviderID = new(string) + *_m.AssignedProviderID = value.String + } + case providerassignmentrun.FieldAttemptedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field attempted_at", values[i]) + } else if value.Valid { + _m.AttemptedAt = value.Time + } + case providerassignmentrun.FieldTrigger: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field trigger", values[i]) + } else if value.Valid { + _m.Trigger = value.String + } + case providerassignmentrun.FieldResult: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field result", values[i]) + } else if value.Valid { + _m.Result = value.String + } + case providerassignmentrun.FieldUsedFallback: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field used_fallback", values[i]) + } else if value.Valid { + _m.UsedFallback = value.Bool + } + case providerassignmentrun.FieldMarketBuyRateSnapshot: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field market_buy_rate_snapshot", values[i]) + } else if value.Valid { + _m.MarketBuyRateSnapshot = new(decimal.Decimal) + *_m.MarketBuyRateSnapshot = *value.S.(*decimal.Decimal) + } + case providerassignmentrun.FieldMarketSellRateSnapshot: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field market_sell_rate_snapshot", values[i]) + } else if value.Valid { + _m.MarketSellRateSnapshot = new(decimal.Decimal) + *_m.MarketSellRateSnapshot = *value.S.(*decimal.Decimal) + } + case providerassignmentrun.FieldErrorMessage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field error_message", values[i]) + } else if value.Valid { + _m.ErrorMessage = new(string) + *_m.ErrorMessage = value.String + } + case providerassignmentrun.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field payment_order_provider_assignment_runs", values[i]) + } else if value.Valid { + _m.payment_order_provider_assignment_runs = new(uuid.UUID) + *_m.payment_order_provider_assignment_runs = *value.S.(*uuid.UUID) + } + case providerassignmentrun.ForeignKeys[1]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field provider_order_token_assignment_runs", value) + } else if value.Valid { + _m.provider_order_token_assignment_runs = new(int) + *_m.provider_order_token_assignment_runs = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ProviderAssignmentRun. +// This includes values selected through modifiers, order, etc. +func (_m *ProviderAssignmentRun) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryPaymentOrder queries the "payment_order" edge of the ProviderAssignmentRun entity. +func (_m *ProviderAssignmentRun) QueryPaymentOrder() *PaymentOrderQuery { + return NewProviderAssignmentRunClient(_m.config).QueryPaymentOrder(_m) +} + +// QueryProviderOrderToken queries the "provider_order_token" edge of the ProviderAssignmentRun entity. +func (_m *ProviderAssignmentRun) QueryProviderOrderToken() *ProviderOrderTokenQuery { + return NewProviderAssignmentRunClient(_m.config).QueryProviderOrderToken(_m) +} + +// Update returns a builder for updating this ProviderAssignmentRun. +// Note that you need to call ProviderAssignmentRun.Unwrap() before calling this method if this ProviderAssignmentRun +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ProviderAssignmentRun) Update() *ProviderAssignmentRunUpdateOne { + return NewProviderAssignmentRunClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ProviderAssignmentRun entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *ProviderAssignmentRun) Unwrap() *ProviderAssignmentRun { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: ProviderAssignmentRun is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ProviderAssignmentRun) String() string { + var builder strings.Builder + builder.WriteString("ProviderAssignmentRun(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + if v := _m.AssignedProviderID; v != nil { + builder.WriteString("assigned_provider_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("attempted_at=") + builder.WriteString(_m.AttemptedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("trigger=") + builder.WriteString(_m.Trigger) + builder.WriteString(", ") + builder.WriteString("result=") + builder.WriteString(_m.Result) + builder.WriteString(", ") + builder.WriteString("used_fallback=") + builder.WriteString(fmt.Sprintf("%v", _m.UsedFallback)) + builder.WriteString(", ") + if v := _m.MarketBuyRateSnapshot; v != nil { + builder.WriteString("market_buy_rate_snapshot=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.MarketSellRateSnapshot; v != nil { + builder.WriteString("market_sell_rate_snapshot=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.ErrorMessage; v != nil { + builder.WriteString("error_message=") + builder.WriteString(*v) + } + builder.WriteByte(')') + return builder.String() +} + +// ProviderAssignmentRuns is a parsable slice of ProviderAssignmentRun. +type ProviderAssignmentRuns []*ProviderAssignmentRun diff --git a/ent/providerassignmentrun/providerassignmentrun.go b/ent/providerassignmentrun/providerassignmentrun.go new file mode 100644 index 000000000..199fbc3f5 --- /dev/null +++ b/ent/providerassignmentrun/providerassignmentrun.go @@ -0,0 +1,180 @@ +// Code generated by ent, DO NOT EDIT. + +package providerassignmentrun + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the providerassignmentrun type in the database. + Label = "provider_assignment_run" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldAssignedProviderID holds the string denoting the assigned_provider_id field in the database. + FieldAssignedProviderID = "assigned_provider_id" + // FieldAttemptedAt holds the string denoting the attempted_at field in the database. + FieldAttemptedAt = "attempted_at" + // FieldTrigger holds the string denoting the trigger field in the database. + FieldTrigger = "trigger" + // FieldResult holds the string denoting the result field in the database. + FieldResult = "result" + // FieldUsedFallback holds the string denoting the used_fallback field in the database. + FieldUsedFallback = "used_fallback" + // FieldMarketBuyRateSnapshot holds the string denoting the market_buy_rate_snapshot field in the database. + FieldMarketBuyRateSnapshot = "market_buy_rate_snapshot" + // FieldMarketSellRateSnapshot holds the string denoting the market_sell_rate_snapshot field in the database. + FieldMarketSellRateSnapshot = "market_sell_rate_snapshot" + // FieldErrorMessage holds the string denoting the error_message field in the database. + FieldErrorMessage = "error_message" + // EdgePaymentOrder holds the string denoting the payment_order edge name in mutations. + EdgePaymentOrder = "payment_order" + // EdgeProviderOrderToken holds the string denoting the provider_order_token edge name in mutations. + EdgeProviderOrderToken = "provider_order_token" + // Table holds the table name of the providerassignmentrun in the database. + Table = "provider_assignment_runs" + // PaymentOrderTable is the table that holds the payment_order relation/edge. + PaymentOrderTable = "provider_assignment_runs" + // PaymentOrderInverseTable is the table name for the PaymentOrder entity. + // It exists in this package in order to avoid circular dependency with the "paymentorder" package. + PaymentOrderInverseTable = "payment_orders" + // PaymentOrderColumn is the table column denoting the payment_order relation/edge. + PaymentOrderColumn = "payment_order_provider_assignment_runs" + // ProviderOrderTokenTable is the table that holds the provider_order_token relation/edge. + ProviderOrderTokenTable = "provider_assignment_runs" + // ProviderOrderTokenInverseTable is the table name for the ProviderOrderToken entity. + // It exists in this package in order to avoid circular dependency with the "providerordertoken" package. + ProviderOrderTokenInverseTable = "provider_order_tokens" + // ProviderOrderTokenColumn is the table column denoting the provider_order_token relation/edge. + ProviderOrderTokenColumn = "provider_order_token_assignment_runs" +) + +// Columns holds all SQL columns for providerassignmentrun fields. +var Columns = []string{ + FieldID, + FieldAssignedProviderID, + FieldAttemptedAt, + FieldTrigger, + FieldResult, + FieldUsedFallback, + FieldMarketBuyRateSnapshot, + FieldMarketSellRateSnapshot, + FieldErrorMessage, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "provider_assignment_runs" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "payment_order_provider_assignment_runs", + "provider_order_token_assignment_runs", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} + +var ( + // AssignedProviderIDValidator is a validator for the "assigned_provider_id" field. It is called by the builders before save. + AssignedProviderIDValidator func(string) error + // DefaultAttemptedAt holds the default value on creation for the "attempted_at" field. + DefaultAttemptedAt func() time.Time + // TriggerValidator is a validator for the "trigger" field. It is called by the builders before save. + TriggerValidator func(string) error + // ResultValidator is a validator for the "result" field. It is called by the builders before save. + ResultValidator func(string) error + // DefaultUsedFallback holds the default value on creation for the "used_fallback" field. + DefaultUsedFallback bool + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// OrderOption defines the ordering options for the ProviderAssignmentRun queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByAssignedProviderID orders the results by the assigned_provider_id field. +func ByAssignedProviderID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAssignedProviderID, opts...).ToFunc() +} + +// ByAttemptedAt orders the results by the attempted_at field. +func ByAttemptedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAttemptedAt, opts...).ToFunc() +} + +// ByTrigger orders the results by the trigger field. +func ByTrigger(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTrigger, opts...).ToFunc() +} + +// ByResult orders the results by the result field. +func ByResult(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldResult, opts...).ToFunc() +} + +// ByUsedFallback orders the results by the used_fallback field. +func ByUsedFallback(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUsedFallback, opts...).ToFunc() +} + +// ByMarketBuyRateSnapshot orders the results by the market_buy_rate_snapshot field. +func ByMarketBuyRateSnapshot(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMarketBuyRateSnapshot, opts...).ToFunc() +} + +// ByMarketSellRateSnapshot orders the results by the market_sell_rate_snapshot field. +func ByMarketSellRateSnapshot(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMarketSellRateSnapshot, opts...).ToFunc() +} + +// ByErrorMessage orders the results by the error_message field. +func ByErrorMessage(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldErrorMessage, opts...).ToFunc() +} + +// ByPaymentOrderField orders the results by payment_order field. +func ByPaymentOrderField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newPaymentOrderStep(), sql.OrderByField(field, opts...)) + } +} + +// ByProviderOrderTokenField orders the results by provider_order_token field. +func ByProviderOrderTokenField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newProviderOrderTokenStep(), sql.OrderByField(field, opts...)) + } +} +func newPaymentOrderStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(PaymentOrderInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, PaymentOrderTable, PaymentOrderColumn), + ) +} +func newProviderOrderTokenStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ProviderOrderTokenInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ProviderOrderTokenTable, ProviderOrderTokenColumn), + ) +} diff --git a/ent/providerassignmentrun/where.go b/ent/providerassignmentrun/where.go new file mode 100644 index 000000000..40930c429 --- /dev/null +++ b/ent/providerassignmentrun/where.go @@ -0,0 +1,589 @@ +// Code generated by ent, DO NOT EDIT. + +package providerassignmentrun + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent/predicate" + "github.com/shopspring/decimal" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLTE(FieldID, id)) +} + +// AssignedProviderID applies equality check predicate on the "assigned_provider_id" field. It's identical to AssignedProviderIDEQ. +func AssignedProviderID(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldAssignedProviderID, v)) +} + +// AttemptedAt applies equality check predicate on the "attempted_at" field. It's identical to AttemptedAtEQ. +func AttemptedAt(v time.Time) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldAttemptedAt, v)) +} + +// Trigger applies equality check predicate on the "trigger" field. It's identical to TriggerEQ. +func Trigger(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldTrigger, v)) +} + +// Result applies equality check predicate on the "result" field. It's identical to ResultEQ. +func Result(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldResult, v)) +} + +// UsedFallback applies equality check predicate on the "used_fallback" field. It's identical to UsedFallbackEQ. +func UsedFallback(v bool) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldUsedFallback, v)) +} + +// MarketBuyRateSnapshot applies equality check predicate on the "market_buy_rate_snapshot" field. It's identical to MarketBuyRateSnapshotEQ. +func MarketBuyRateSnapshot(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldMarketBuyRateSnapshot, v)) +} + +// MarketSellRateSnapshot applies equality check predicate on the "market_sell_rate_snapshot" field. It's identical to MarketSellRateSnapshotEQ. +func MarketSellRateSnapshot(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldMarketSellRateSnapshot, v)) +} + +// ErrorMessage applies equality check predicate on the "error_message" field. It's identical to ErrorMessageEQ. +func ErrorMessage(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldErrorMessage, v)) +} + +// AssignedProviderIDEQ applies the EQ predicate on the "assigned_provider_id" field. +func AssignedProviderIDEQ(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldAssignedProviderID, v)) +} + +// AssignedProviderIDNEQ applies the NEQ predicate on the "assigned_provider_id" field. +func AssignedProviderIDNEQ(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNEQ(FieldAssignedProviderID, v)) +} + +// AssignedProviderIDIn applies the In predicate on the "assigned_provider_id" field. +func AssignedProviderIDIn(vs ...string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIn(FieldAssignedProviderID, vs...)) +} + +// AssignedProviderIDNotIn applies the NotIn predicate on the "assigned_provider_id" field. +func AssignedProviderIDNotIn(vs ...string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotIn(FieldAssignedProviderID, vs...)) +} + +// AssignedProviderIDGT applies the GT predicate on the "assigned_provider_id" field. +func AssignedProviderIDGT(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGT(FieldAssignedProviderID, v)) +} + +// AssignedProviderIDGTE applies the GTE predicate on the "assigned_provider_id" field. +func AssignedProviderIDGTE(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGTE(FieldAssignedProviderID, v)) +} + +// AssignedProviderIDLT applies the LT predicate on the "assigned_provider_id" field. +func AssignedProviderIDLT(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLT(FieldAssignedProviderID, v)) +} + +// AssignedProviderIDLTE applies the LTE predicate on the "assigned_provider_id" field. +func AssignedProviderIDLTE(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLTE(FieldAssignedProviderID, v)) +} + +// AssignedProviderIDContains applies the Contains predicate on the "assigned_provider_id" field. +func AssignedProviderIDContains(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldContains(FieldAssignedProviderID, v)) +} + +// AssignedProviderIDHasPrefix applies the HasPrefix predicate on the "assigned_provider_id" field. +func AssignedProviderIDHasPrefix(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldHasPrefix(FieldAssignedProviderID, v)) +} + +// AssignedProviderIDHasSuffix applies the HasSuffix predicate on the "assigned_provider_id" field. +func AssignedProviderIDHasSuffix(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldHasSuffix(FieldAssignedProviderID, v)) +} + +// AssignedProviderIDIsNil applies the IsNil predicate on the "assigned_provider_id" field. +func AssignedProviderIDIsNil() predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIsNull(FieldAssignedProviderID)) +} + +// AssignedProviderIDNotNil applies the NotNil predicate on the "assigned_provider_id" field. +func AssignedProviderIDNotNil() predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotNull(FieldAssignedProviderID)) +} + +// AssignedProviderIDEqualFold applies the EqualFold predicate on the "assigned_provider_id" field. +func AssignedProviderIDEqualFold(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEqualFold(FieldAssignedProviderID, v)) +} + +// AssignedProviderIDContainsFold applies the ContainsFold predicate on the "assigned_provider_id" field. +func AssignedProviderIDContainsFold(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldContainsFold(FieldAssignedProviderID, v)) +} + +// AttemptedAtEQ applies the EQ predicate on the "attempted_at" field. +func AttemptedAtEQ(v time.Time) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldAttemptedAt, v)) +} + +// AttemptedAtNEQ applies the NEQ predicate on the "attempted_at" field. +func AttemptedAtNEQ(v time.Time) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNEQ(FieldAttemptedAt, v)) +} + +// AttemptedAtIn applies the In predicate on the "attempted_at" field. +func AttemptedAtIn(vs ...time.Time) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIn(FieldAttemptedAt, vs...)) +} + +// AttemptedAtNotIn applies the NotIn predicate on the "attempted_at" field. +func AttemptedAtNotIn(vs ...time.Time) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotIn(FieldAttemptedAt, vs...)) +} + +// AttemptedAtGT applies the GT predicate on the "attempted_at" field. +func AttemptedAtGT(v time.Time) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGT(FieldAttemptedAt, v)) +} + +// AttemptedAtGTE applies the GTE predicate on the "attempted_at" field. +func AttemptedAtGTE(v time.Time) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGTE(FieldAttemptedAt, v)) +} + +// AttemptedAtLT applies the LT predicate on the "attempted_at" field. +func AttemptedAtLT(v time.Time) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLT(FieldAttemptedAt, v)) +} + +// AttemptedAtLTE applies the LTE predicate on the "attempted_at" field. +func AttemptedAtLTE(v time.Time) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLTE(FieldAttemptedAt, v)) +} + +// TriggerEQ applies the EQ predicate on the "trigger" field. +func TriggerEQ(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldTrigger, v)) +} + +// TriggerNEQ applies the NEQ predicate on the "trigger" field. +func TriggerNEQ(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNEQ(FieldTrigger, v)) +} + +// TriggerIn applies the In predicate on the "trigger" field. +func TriggerIn(vs ...string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIn(FieldTrigger, vs...)) +} + +// TriggerNotIn applies the NotIn predicate on the "trigger" field. +func TriggerNotIn(vs ...string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotIn(FieldTrigger, vs...)) +} + +// TriggerGT applies the GT predicate on the "trigger" field. +func TriggerGT(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGT(FieldTrigger, v)) +} + +// TriggerGTE applies the GTE predicate on the "trigger" field. +func TriggerGTE(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGTE(FieldTrigger, v)) +} + +// TriggerLT applies the LT predicate on the "trigger" field. +func TriggerLT(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLT(FieldTrigger, v)) +} + +// TriggerLTE applies the LTE predicate on the "trigger" field. +func TriggerLTE(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLTE(FieldTrigger, v)) +} + +// TriggerContains applies the Contains predicate on the "trigger" field. +func TriggerContains(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldContains(FieldTrigger, v)) +} + +// TriggerHasPrefix applies the HasPrefix predicate on the "trigger" field. +func TriggerHasPrefix(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldHasPrefix(FieldTrigger, v)) +} + +// TriggerHasSuffix applies the HasSuffix predicate on the "trigger" field. +func TriggerHasSuffix(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldHasSuffix(FieldTrigger, v)) +} + +// TriggerEqualFold applies the EqualFold predicate on the "trigger" field. +func TriggerEqualFold(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEqualFold(FieldTrigger, v)) +} + +// TriggerContainsFold applies the ContainsFold predicate on the "trigger" field. +func TriggerContainsFold(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldContainsFold(FieldTrigger, v)) +} + +// ResultEQ applies the EQ predicate on the "result" field. +func ResultEQ(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldResult, v)) +} + +// ResultNEQ applies the NEQ predicate on the "result" field. +func ResultNEQ(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNEQ(FieldResult, v)) +} + +// ResultIn applies the In predicate on the "result" field. +func ResultIn(vs ...string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIn(FieldResult, vs...)) +} + +// ResultNotIn applies the NotIn predicate on the "result" field. +func ResultNotIn(vs ...string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotIn(FieldResult, vs...)) +} + +// ResultGT applies the GT predicate on the "result" field. +func ResultGT(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGT(FieldResult, v)) +} + +// ResultGTE applies the GTE predicate on the "result" field. +func ResultGTE(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGTE(FieldResult, v)) +} + +// ResultLT applies the LT predicate on the "result" field. +func ResultLT(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLT(FieldResult, v)) +} + +// ResultLTE applies the LTE predicate on the "result" field. +func ResultLTE(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLTE(FieldResult, v)) +} + +// ResultContains applies the Contains predicate on the "result" field. +func ResultContains(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldContains(FieldResult, v)) +} + +// ResultHasPrefix applies the HasPrefix predicate on the "result" field. +func ResultHasPrefix(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldHasPrefix(FieldResult, v)) +} + +// ResultHasSuffix applies the HasSuffix predicate on the "result" field. +func ResultHasSuffix(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldHasSuffix(FieldResult, v)) +} + +// ResultEqualFold applies the EqualFold predicate on the "result" field. +func ResultEqualFold(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEqualFold(FieldResult, v)) +} + +// ResultContainsFold applies the ContainsFold predicate on the "result" field. +func ResultContainsFold(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldContainsFold(FieldResult, v)) +} + +// UsedFallbackEQ applies the EQ predicate on the "used_fallback" field. +func UsedFallbackEQ(v bool) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldUsedFallback, v)) +} + +// UsedFallbackNEQ applies the NEQ predicate on the "used_fallback" field. +func UsedFallbackNEQ(v bool) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNEQ(FieldUsedFallback, v)) +} + +// MarketBuyRateSnapshotEQ applies the EQ predicate on the "market_buy_rate_snapshot" field. +func MarketBuyRateSnapshotEQ(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldMarketBuyRateSnapshot, v)) +} + +// MarketBuyRateSnapshotNEQ applies the NEQ predicate on the "market_buy_rate_snapshot" field. +func MarketBuyRateSnapshotNEQ(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNEQ(FieldMarketBuyRateSnapshot, v)) +} + +// MarketBuyRateSnapshotIn applies the In predicate on the "market_buy_rate_snapshot" field. +func MarketBuyRateSnapshotIn(vs ...decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIn(FieldMarketBuyRateSnapshot, vs...)) +} + +// MarketBuyRateSnapshotNotIn applies the NotIn predicate on the "market_buy_rate_snapshot" field. +func MarketBuyRateSnapshotNotIn(vs ...decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotIn(FieldMarketBuyRateSnapshot, vs...)) +} + +// MarketBuyRateSnapshotGT applies the GT predicate on the "market_buy_rate_snapshot" field. +func MarketBuyRateSnapshotGT(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGT(FieldMarketBuyRateSnapshot, v)) +} + +// MarketBuyRateSnapshotGTE applies the GTE predicate on the "market_buy_rate_snapshot" field. +func MarketBuyRateSnapshotGTE(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGTE(FieldMarketBuyRateSnapshot, v)) +} + +// MarketBuyRateSnapshotLT applies the LT predicate on the "market_buy_rate_snapshot" field. +func MarketBuyRateSnapshotLT(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLT(FieldMarketBuyRateSnapshot, v)) +} + +// MarketBuyRateSnapshotLTE applies the LTE predicate on the "market_buy_rate_snapshot" field. +func MarketBuyRateSnapshotLTE(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLTE(FieldMarketBuyRateSnapshot, v)) +} + +// MarketBuyRateSnapshotIsNil applies the IsNil predicate on the "market_buy_rate_snapshot" field. +func MarketBuyRateSnapshotIsNil() predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIsNull(FieldMarketBuyRateSnapshot)) +} + +// MarketBuyRateSnapshotNotNil applies the NotNil predicate on the "market_buy_rate_snapshot" field. +func MarketBuyRateSnapshotNotNil() predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotNull(FieldMarketBuyRateSnapshot)) +} + +// MarketSellRateSnapshotEQ applies the EQ predicate on the "market_sell_rate_snapshot" field. +func MarketSellRateSnapshotEQ(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldMarketSellRateSnapshot, v)) +} + +// MarketSellRateSnapshotNEQ applies the NEQ predicate on the "market_sell_rate_snapshot" field. +func MarketSellRateSnapshotNEQ(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNEQ(FieldMarketSellRateSnapshot, v)) +} + +// MarketSellRateSnapshotIn applies the In predicate on the "market_sell_rate_snapshot" field. +func MarketSellRateSnapshotIn(vs ...decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIn(FieldMarketSellRateSnapshot, vs...)) +} + +// MarketSellRateSnapshotNotIn applies the NotIn predicate on the "market_sell_rate_snapshot" field. +func MarketSellRateSnapshotNotIn(vs ...decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotIn(FieldMarketSellRateSnapshot, vs...)) +} + +// MarketSellRateSnapshotGT applies the GT predicate on the "market_sell_rate_snapshot" field. +func MarketSellRateSnapshotGT(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGT(FieldMarketSellRateSnapshot, v)) +} + +// MarketSellRateSnapshotGTE applies the GTE predicate on the "market_sell_rate_snapshot" field. +func MarketSellRateSnapshotGTE(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGTE(FieldMarketSellRateSnapshot, v)) +} + +// MarketSellRateSnapshotLT applies the LT predicate on the "market_sell_rate_snapshot" field. +func MarketSellRateSnapshotLT(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLT(FieldMarketSellRateSnapshot, v)) +} + +// MarketSellRateSnapshotLTE applies the LTE predicate on the "market_sell_rate_snapshot" field. +func MarketSellRateSnapshotLTE(v decimal.Decimal) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLTE(FieldMarketSellRateSnapshot, v)) +} + +// MarketSellRateSnapshotIsNil applies the IsNil predicate on the "market_sell_rate_snapshot" field. +func MarketSellRateSnapshotIsNil() predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIsNull(FieldMarketSellRateSnapshot)) +} + +// MarketSellRateSnapshotNotNil applies the NotNil predicate on the "market_sell_rate_snapshot" field. +func MarketSellRateSnapshotNotNil() predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotNull(FieldMarketSellRateSnapshot)) +} + +// ErrorMessageEQ applies the EQ predicate on the "error_message" field. +func ErrorMessageEQ(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEQ(FieldErrorMessage, v)) +} + +// ErrorMessageNEQ applies the NEQ predicate on the "error_message" field. +func ErrorMessageNEQ(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNEQ(FieldErrorMessage, v)) +} + +// ErrorMessageIn applies the In predicate on the "error_message" field. +func ErrorMessageIn(vs ...string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIn(FieldErrorMessage, vs...)) +} + +// ErrorMessageNotIn applies the NotIn predicate on the "error_message" field. +func ErrorMessageNotIn(vs ...string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotIn(FieldErrorMessage, vs...)) +} + +// ErrorMessageGT applies the GT predicate on the "error_message" field. +func ErrorMessageGT(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGT(FieldErrorMessage, v)) +} + +// ErrorMessageGTE applies the GTE predicate on the "error_message" field. +func ErrorMessageGTE(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldGTE(FieldErrorMessage, v)) +} + +// ErrorMessageLT applies the LT predicate on the "error_message" field. +func ErrorMessageLT(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLT(FieldErrorMessage, v)) +} + +// ErrorMessageLTE applies the LTE predicate on the "error_message" field. +func ErrorMessageLTE(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldLTE(FieldErrorMessage, v)) +} + +// ErrorMessageContains applies the Contains predicate on the "error_message" field. +func ErrorMessageContains(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldContains(FieldErrorMessage, v)) +} + +// ErrorMessageHasPrefix applies the HasPrefix predicate on the "error_message" field. +func ErrorMessageHasPrefix(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldHasPrefix(FieldErrorMessage, v)) +} + +// ErrorMessageHasSuffix applies the HasSuffix predicate on the "error_message" field. +func ErrorMessageHasSuffix(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldHasSuffix(FieldErrorMessage, v)) +} + +// ErrorMessageIsNil applies the IsNil predicate on the "error_message" field. +func ErrorMessageIsNil() predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldIsNull(FieldErrorMessage)) +} + +// ErrorMessageNotNil applies the NotNil predicate on the "error_message" field. +func ErrorMessageNotNil() predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldNotNull(FieldErrorMessage)) +} + +// ErrorMessageEqualFold applies the EqualFold predicate on the "error_message" field. +func ErrorMessageEqualFold(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldEqualFold(FieldErrorMessage, v)) +} + +// ErrorMessageContainsFold applies the ContainsFold predicate on the "error_message" field. +func ErrorMessageContainsFold(v string) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.FieldContainsFold(FieldErrorMessage, v)) +} + +// HasPaymentOrder applies the HasEdge predicate on the "payment_order" edge. +func HasPaymentOrder() predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, PaymentOrderTable, PaymentOrderColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasPaymentOrderWith applies the HasEdge predicate on the "payment_order" edge with a given conditions (other predicates). +func HasPaymentOrderWith(preds ...predicate.PaymentOrder) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(func(s *sql.Selector) { + step := newPaymentOrderStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasProviderOrderToken applies the HasEdge predicate on the "provider_order_token" edge. +func HasProviderOrderToken() predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ProviderOrderTokenTable, ProviderOrderTokenColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasProviderOrderTokenWith applies the HasEdge predicate on the "provider_order_token" edge with a given conditions (other predicates). +func HasProviderOrderTokenWith(preds ...predicate.ProviderOrderToken) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(func(s *sql.Selector) { + step := newProviderOrderTokenStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.ProviderAssignmentRun) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ProviderAssignmentRun) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ProviderAssignmentRun) predicate.ProviderAssignmentRun { + return predicate.ProviderAssignmentRun(sql.NotPredicates(p)) +} diff --git a/ent/providerassignmentrun_create.go b/ent/providerassignmentrun_create.go new file mode 100644 index 000000000..86cd81b67 --- /dev/null +++ b/ent/providerassignmentrun_create.go @@ -0,0 +1,1129 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/providerassignmentrun" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/shopspring/decimal" +) + +// ProviderAssignmentRunCreate is the builder for creating a ProviderAssignmentRun entity. +type ProviderAssignmentRunCreate struct { + config + mutation *ProviderAssignmentRunMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetAssignedProviderID sets the "assigned_provider_id" field. +func (_c *ProviderAssignmentRunCreate) SetAssignedProviderID(v string) *ProviderAssignmentRunCreate { + _c.mutation.SetAssignedProviderID(v) + return _c +} + +// SetNillableAssignedProviderID sets the "assigned_provider_id" field if the given value is not nil. +func (_c *ProviderAssignmentRunCreate) SetNillableAssignedProviderID(v *string) *ProviderAssignmentRunCreate { + if v != nil { + _c.SetAssignedProviderID(*v) + } + return _c +} + +// SetAttemptedAt sets the "attempted_at" field. +func (_c *ProviderAssignmentRunCreate) SetAttemptedAt(v time.Time) *ProviderAssignmentRunCreate { + _c.mutation.SetAttemptedAt(v) + return _c +} + +// SetNillableAttemptedAt sets the "attempted_at" field if the given value is not nil. +func (_c *ProviderAssignmentRunCreate) SetNillableAttemptedAt(v *time.Time) *ProviderAssignmentRunCreate { + if v != nil { + _c.SetAttemptedAt(*v) + } + return _c +} + +// SetTrigger sets the "trigger" field. +func (_c *ProviderAssignmentRunCreate) SetTrigger(v string) *ProviderAssignmentRunCreate { + _c.mutation.SetTrigger(v) + return _c +} + +// SetResult sets the "result" field. +func (_c *ProviderAssignmentRunCreate) SetResult(v string) *ProviderAssignmentRunCreate { + _c.mutation.SetResult(v) + return _c +} + +// SetUsedFallback sets the "used_fallback" field. +func (_c *ProviderAssignmentRunCreate) SetUsedFallback(v bool) *ProviderAssignmentRunCreate { + _c.mutation.SetUsedFallback(v) + return _c +} + +// SetNillableUsedFallback sets the "used_fallback" field if the given value is not nil. +func (_c *ProviderAssignmentRunCreate) SetNillableUsedFallback(v *bool) *ProviderAssignmentRunCreate { + if v != nil { + _c.SetUsedFallback(*v) + } + return _c +} + +// SetMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field. +func (_c *ProviderAssignmentRunCreate) SetMarketBuyRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunCreate { + _c.mutation.SetMarketBuyRateSnapshot(v) + return _c +} + +// SetNillableMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field if the given value is not nil. +func (_c *ProviderAssignmentRunCreate) SetNillableMarketBuyRateSnapshot(v *decimal.Decimal) *ProviderAssignmentRunCreate { + if v != nil { + _c.SetMarketBuyRateSnapshot(*v) + } + return _c +} + +// SetMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field. +func (_c *ProviderAssignmentRunCreate) SetMarketSellRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunCreate { + _c.mutation.SetMarketSellRateSnapshot(v) + return _c +} + +// SetNillableMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field if the given value is not nil. +func (_c *ProviderAssignmentRunCreate) SetNillableMarketSellRateSnapshot(v *decimal.Decimal) *ProviderAssignmentRunCreate { + if v != nil { + _c.SetMarketSellRateSnapshot(*v) + } + return _c +} + +// SetErrorMessage sets the "error_message" field. +func (_c *ProviderAssignmentRunCreate) SetErrorMessage(v string) *ProviderAssignmentRunCreate { + _c.mutation.SetErrorMessage(v) + return _c +} + +// SetNillableErrorMessage sets the "error_message" field if the given value is not nil. +func (_c *ProviderAssignmentRunCreate) SetNillableErrorMessage(v *string) *ProviderAssignmentRunCreate { + if v != nil { + _c.SetErrorMessage(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *ProviderAssignmentRunCreate) SetID(v uuid.UUID) *ProviderAssignmentRunCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ProviderAssignmentRunCreate) SetNillableID(v *uuid.UUID) *ProviderAssignmentRunCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetPaymentOrderID sets the "payment_order" edge to the PaymentOrder entity by ID. +func (_c *ProviderAssignmentRunCreate) SetPaymentOrderID(id uuid.UUID) *ProviderAssignmentRunCreate { + _c.mutation.SetPaymentOrderID(id) + return _c +} + +// SetPaymentOrder sets the "payment_order" edge to the PaymentOrder entity. +func (_c *ProviderAssignmentRunCreate) SetPaymentOrder(v *PaymentOrder) *ProviderAssignmentRunCreate { + return _c.SetPaymentOrderID(v.ID) +} + +// SetProviderOrderTokenID sets the "provider_order_token" edge to the ProviderOrderToken entity by ID. +func (_c *ProviderAssignmentRunCreate) SetProviderOrderTokenID(id int) *ProviderAssignmentRunCreate { + _c.mutation.SetProviderOrderTokenID(id) + return _c +} + +// SetNillableProviderOrderTokenID sets the "provider_order_token" edge to the ProviderOrderToken entity by ID if the given value is not nil. +func (_c *ProviderAssignmentRunCreate) SetNillableProviderOrderTokenID(id *int) *ProviderAssignmentRunCreate { + if id != nil { + _c = _c.SetProviderOrderTokenID(*id) + } + return _c +} + +// SetProviderOrderToken sets the "provider_order_token" edge to the ProviderOrderToken entity. +func (_c *ProviderAssignmentRunCreate) SetProviderOrderToken(v *ProviderOrderToken) *ProviderAssignmentRunCreate { + return _c.SetProviderOrderTokenID(v.ID) +} + +// Mutation returns the ProviderAssignmentRunMutation object of the builder. +func (_c *ProviderAssignmentRunCreate) Mutation() *ProviderAssignmentRunMutation { + return _c.mutation +} + +// Save creates the ProviderAssignmentRun in the database. +func (_c *ProviderAssignmentRunCreate) Save(ctx context.Context) (*ProviderAssignmentRun, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ProviderAssignmentRunCreate) SaveX(ctx context.Context) *ProviderAssignmentRun { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ProviderAssignmentRunCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ProviderAssignmentRunCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *ProviderAssignmentRunCreate) defaults() { + if _, ok := _c.mutation.AttemptedAt(); !ok { + v := providerassignmentrun.DefaultAttemptedAt() + _c.mutation.SetAttemptedAt(v) + } + if _, ok := _c.mutation.UsedFallback(); !ok { + v := providerassignmentrun.DefaultUsedFallback + _c.mutation.SetUsedFallback(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := providerassignmentrun.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ProviderAssignmentRunCreate) check() error { + if v, ok := _c.mutation.AssignedProviderID(); ok { + if err := providerassignmentrun.AssignedProviderIDValidator(v); err != nil { + return &ValidationError{Name: "assigned_provider_id", err: fmt.Errorf(`ent: validator failed for field "ProviderAssignmentRun.assigned_provider_id": %w`, err)} + } + } + if _, ok := _c.mutation.AttemptedAt(); !ok { + return &ValidationError{Name: "attempted_at", err: errors.New(`ent: missing required field "ProviderAssignmentRun.attempted_at"`)} + } + if _, ok := _c.mutation.Trigger(); !ok { + return &ValidationError{Name: "trigger", err: errors.New(`ent: missing required field "ProviderAssignmentRun.trigger"`)} + } + if v, ok := _c.mutation.Trigger(); ok { + if err := providerassignmentrun.TriggerValidator(v); err != nil { + return &ValidationError{Name: "trigger", err: fmt.Errorf(`ent: validator failed for field "ProviderAssignmentRun.trigger": %w`, err)} + } + } + if _, ok := _c.mutation.Result(); !ok { + return &ValidationError{Name: "result", err: errors.New(`ent: missing required field "ProviderAssignmentRun.result"`)} + } + if v, ok := _c.mutation.Result(); ok { + if err := providerassignmentrun.ResultValidator(v); err != nil { + return &ValidationError{Name: "result", err: fmt.Errorf(`ent: validator failed for field "ProviderAssignmentRun.result": %w`, err)} + } + } + if _, ok := _c.mutation.UsedFallback(); !ok { + return &ValidationError{Name: "used_fallback", err: errors.New(`ent: missing required field "ProviderAssignmentRun.used_fallback"`)} + } + if len(_c.mutation.PaymentOrderIDs()) == 0 { + return &ValidationError{Name: "payment_order", err: errors.New(`ent: missing required edge "ProviderAssignmentRun.payment_order"`)} + } + return nil +} + +func (_c *ProviderAssignmentRunCreate) sqlSave(ctx context.Context) (*ProviderAssignmentRun, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(*uuid.UUID); ok { + _node.ID = *id + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ProviderAssignmentRunCreate) createSpec() (*ProviderAssignmentRun, *sqlgraph.CreateSpec) { + var ( + _node = &ProviderAssignmentRun{config: _c.config} + _spec = sqlgraph.NewCreateSpec(providerassignmentrun.Table, sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.AssignedProviderID(); ok { + _spec.SetField(providerassignmentrun.FieldAssignedProviderID, field.TypeString, value) + _node.AssignedProviderID = &value + } + if value, ok := _c.mutation.AttemptedAt(); ok { + _spec.SetField(providerassignmentrun.FieldAttemptedAt, field.TypeTime, value) + _node.AttemptedAt = value + } + if value, ok := _c.mutation.Trigger(); ok { + _spec.SetField(providerassignmentrun.FieldTrigger, field.TypeString, value) + _node.Trigger = value + } + if value, ok := _c.mutation.Result(); ok { + _spec.SetField(providerassignmentrun.FieldResult, field.TypeString, value) + _node.Result = value + } + if value, ok := _c.mutation.UsedFallback(); ok { + _spec.SetField(providerassignmentrun.FieldUsedFallback, field.TypeBool, value) + _node.UsedFallback = value + } + if value, ok := _c.mutation.MarketBuyRateSnapshot(); ok { + _spec.SetField(providerassignmentrun.FieldMarketBuyRateSnapshot, field.TypeFloat64, value) + _node.MarketBuyRateSnapshot = &value + } + if value, ok := _c.mutation.MarketSellRateSnapshot(); ok { + _spec.SetField(providerassignmentrun.FieldMarketSellRateSnapshot, field.TypeFloat64, value) + _node.MarketSellRateSnapshot = &value + } + if value, ok := _c.mutation.ErrorMessage(); ok { + _spec.SetField(providerassignmentrun.FieldErrorMessage, field.TypeString, value) + _node.ErrorMessage = &value + } + if nodes := _c.mutation.PaymentOrderIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerassignmentrun.PaymentOrderTable, + Columns: []string{providerassignmentrun.PaymentOrderColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.payment_order_provider_assignment_runs = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ProviderOrderTokenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerassignmentrun.ProviderOrderTokenTable, + Columns: []string{providerassignmentrun.ProviderOrderTokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertoken.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.provider_order_token_assignment_runs = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ProviderAssignmentRun.Create(). +// SetAssignedProviderID(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ProviderAssignmentRunUpsert) { +// SetAssignedProviderID(v+v). +// }). +// Exec(ctx) +func (_c *ProviderAssignmentRunCreate) OnConflict(opts ...sql.ConflictOption) *ProviderAssignmentRunUpsertOne { + _c.conflict = opts + return &ProviderAssignmentRunUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ProviderAssignmentRun.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ProviderAssignmentRunCreate) OnConflictColumns(columns ...string) *ProviderAssignmentRunUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ProviderAssignmentRunUpsertOne{ + create: _c, + } +} + +type ( + // ProviderAssignmentRunUpsertOne is the builder for "upsert"-ing + // one ProviderAssignmentRun node. + ProviderAssignmentRunUpsertOne struct { + create *ProviderAssignmentRunCreate + } + + // ProviderAssignmentRunUpsert is the "OnConflict" setter. + ProviderAssignmentRunUpsert struct { + *sql.UpdateSet + } +) + +// SetAssignedProviderID sets the "assigned_provider_id" field. +func (u *ProviderAssignmentRunUpsert) SetAssignedProviderID(v string) *ProviderAssignmentRunUpsert { + u.Set(providerassignmentrun.FieldAssignedProviderID, v) + return u +} + +// UpdateAssignedProviderID sets the "assigned_provider_id" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsert) UpdateAssignedProviderID() *ProviderAssignmentRunUpsert { + u.SetExcluded(providerassignmentrun.FieldAssignedProviderID) + return u +} + +// ClearAssignedProviderID clears the value of the "assigned_provider_id" field. +func (u *ProviderAssignmentRunUpsert) ClearAssignedProviderID() *ProviderAssignmentRunUpsert { + u.SetNull(providerassignmentrun.FieldAssignedProviderID) + return u +} + +// SetAttemptedAt sets the "attempted_at" field. +func (u *ProviderAssignmentRunUpsert) SetAttemptedAt(v time.Time) *ProviderAssignmentRunUpsert { + u.Set(providerassignmentrun.FieldAttemptedAt, v) + return u +} + +// UpdateAttemptedAt sets the "attempted_at" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsert) UpdateAttemptedAt() *ProviderAssignmentRunUpsert { + u.SetExcluded(providerassignmentrun.FieldAttemptedAt) + return u +} + +// SetTrigger sets the "trigger" field. +func (u *ProviderAssignmentRunUpsert) SetTrigger(v string) *ProviderAssignmentRunUpsert { + u.Set(providerassignmentrun.FieldTrigger, v) + return u +} + +// UpdateTrigger sets the "trigger" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsert) UpdateTrigger() *ProviderAssignmentRunUpsert { + u.SetExcluded(providerassignmentrun.FieldTrigger) + return u +} + +// SetResult sets the "result" field. +func (u *ProviderAssignmentRunUpsert) SetResult(v string) *ProviderAssignmentRunUpsert { + u.Set(providerassignmentrun.FieldResult, v) + return u +} + +// UpdateResult sets the "result" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsert) UpdateResult() *ProviderAssignmentRunUpsert { + u.SetExcluded(providerassignmentrun.FieldResult) + return u +} + +// SetUsedFallback sets the "used_fallback" field. +func (u *ProviderAssignmentRunUpsert) SetUsedFallback(v bool) *ProviderAssignmentRunUpsert { + u.Set(providerassignmentrun.FieldUsedFallback, v) + return u +} + +// UpdateUsedFallback sets the "used_fallback" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsert) UpdateUsedFallback() *ProviderAssignmentRunUpsert { + u.SetExcluded(providerassignmentrun.FieldUsedFallback) + return u +} + +// SetMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsert) SetMarketBuyRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsert { + u.Set(providerassignmentrun.FieldMarketBuyRateSnapshot, v) + return u +} + +// UpdateMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsert) UpdateMarketBuyRateSnapshot() *ProviderAssignmentRunUpsert { + u.SetExcluded(providerassignmentrun.FieldMarketBuyRateSnapshot) + return u +} + +// AddMarketBuyRateSnapshot adds v to the "market_buy_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsert) AddMarketBuyRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsert { + u.Add(providerassignmentrun.FieldMarketBuyRateSnapshot, v) + return u +} + +// ClearMarketBuyRateSnapshot clears the value of the "market_buy_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsert) ClearMarketBuyRateSnapshot() *ProviderAssignmentRunUpsert { + u.SetNull(providerassignmentrun.FieldMarketBuyRateSnapshot) + return u +} + +// SetMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsert) SetMarketSellRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsert { + u.Set(providerassignmentrun.FieldMarketSellRateSnapshot, v) + return u +} + +// UpdateMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsert) UpdateMarketSellRateSnapshot() *ProviderAssignmentRunUpsert { + u.SetExcluded(providerassignmentrun.FieldMarketSellRateSnapshot) + return u +} + +// AddMarketSellRateSnapshot adds v to the "market_sell_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsert) AddMarketSellRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsert { + u.Add(providerassignmentrun.FieldMarketSellRateSnapshot, v) + return u +} + +// ClearMarketSellRateSnapshot clears the value of the "market_sell_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsert) ClearMarketSellRateSnapshot() *ProviderAssignmentRunUpsert { + u.SetNull(providerassignmentrun.FieldMarketSellRateSnapshot) + return u +} + +// SetErrorMessage sets the "error_message" field. +func (u *ProviderAssignmentRunUpsert) SetErrorMessage(v string) *ProviderAssignmentRunUpsert { + u.Set(providerassignmentrun.FieldErrorMessage, v) + return u +} + +// UpdateErrorMessage sets the "error_message" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsert) UpdateErrorMessage() *ProviderAssignmentRunUpsert { + u.SetExcluded(providerassignmentrun.FieldErrorMessage) + return u +} + +// ClearErrorMessage clears the value of the "error_message" field. +func (u *ProviderAssignmentRunUpsert) ClearErrorMessage() *ProviderAssignmentRunUpsert { + u.SetNull(providerassignmentrun.FieldErrorMessage) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.ProviderAssignmentRun.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(providerassignmentrun.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ProviderAssignmentRunUpsertOne) UpdateNewValues() *ProviderAssignmentRunUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(providerassignmentrun.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ProviderAssignmentRun.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ProviderAssignmentRunUpsertOne) Ignore() *ProviderAssignmentRunUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ProviderAssignmentRunUpsertOne) DoNothing() *ProviderAssignmentRunUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ProviderAssignmentRunCreate.OnConflict +// documentation for more info. +func (u *ProviderAssignmentRunUpsertOne) Update(set func(*ProviderAssignmentRunUpsert)) *ProviderAssignmentRunUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ProviderAssignmentRunUpsert{UpdateSet: update}) + })) + return u +} + +// SetAssignedProviderID sets the "assigned_provider_id" field. +func (u *ProviderAssignmentRunUpsertOne) SetAssignedProviderID(v string) *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetAssignedProviderID(v) + }) +} + +// UpdateAssignedProviderID sets the "assigned_provider_id" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertOne) UpdateAssignedProviderID() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateAssignedProviderID() + }) +} + +// ClearAssignedProviderID clears the value of the "assigned_provider_id" field. +func (u *ProviderAssignmentRunUpsertOne) ClearAssignedProviderID() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.ClearAssignedProviderID() + }) +} + +// SetAttemptedAt sets the "attempted_at" field. +func (u *ProviderAssignmentRunUpsertOne) SetAttemptedAt(v time.Time) *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetAttemptedAt(v) + }) +} + +// UpdateAttemptedAt sets the "attempted_at" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertOne) UpdateAttemptedAt() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateAttemptedAt() + }) +} + +// SetTrigger sets the "trigger" field. +func (u *ProviderAssignmentRunUpsertOne) SetTrigger(v string) *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetTrigger(v) + }) +} + +// UpdateTrigger sets the "trigger" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertOne) UpdateTrigger() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateTrigger() + }) +} + +// SetResult sets the "result" field. +func (u *ProviderAssignmentRunUpsertOne) SetResult(v string) *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetResult(v) + }) +} + +// UpdateResult sets the "result" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertOne) UpdateResult() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateResult() + }) +} + +// SetUsedFallback sets the "used_fallback" field. +func (u *ProviderAssignmentRunUpsertOne) SetUsedFallback(v bool) *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetUsedFallback(v) + }) +} + +// UpdateUsedFallback sets the "used_fallback" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertOne) UpdateUsedFallback() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateUsedFallback() + }) +} + +// SetMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertOne) SetMarketBuyRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetMarketBuyRateSnapshot(v) + }) +} + +// AddMarketBuyRateSnapshot adds v to the "market_buy_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertOne) AddMarketBuyRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.AddMarketBuyRateSnapshot(v) + }) +} + +// UpdateMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertOne) UpdateMarketBuyRateSnapshot() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateMarketBuyRateSnapshot() + }) +} + +// ClearMarketBuyRateSnapshot clears the value of the "market_buy_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertOne) ClearMarketBuyRateSnapshot() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.ClearMarketBuyRateSnapshot() + }) +} + +// SetMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertOne) SetMarketSellRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetMarketSellRateSnapshot(v) + }) +} + +// AddMarketSellRateSnapshot adds v to the "market_sell_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertOne) AddMarketSellRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.AddMarketSellRateSnapshot(v) + }) +} + +// UpdateMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertOne) UpdateMarketSellRateSnapshot() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateMarketSellRateSnapshot() + }) +} + +// ClearMarketSellRateSnapshot clears the value of the "market_sell_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertOne) ClearMarketSellRateSnapshot() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.ClearMarketSellRateSnapshot() + }) +} + +// SetErrorMessage sets the "error_message" field. +func (u *ProviderAssignmentRunUpsertOne) SetErrorMessage(v string) *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetErrorMessage(v) + }) +} + +// UpdateErrorMessage sets the "error_message" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertOne) UpdateErrorMessage() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateErrorMessage() + }) +} + +// ClearErrorMessage clears the value of the "error_message" field. +func (u *ProviderAssignmentRunUpsertOne) ClearErrorMessage() *ProviderAssignmentRunUpsertOne { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.ClearErrorMessage() + }) +} + +// Exec executes the query. +func (u *ProviderAssignmentRunUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ProviderAssignmentRunCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ProviderAssignmentRunUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *ProviderAssignmentRunUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("ent: ProviderAssignmentRunUpsertOne.ID is not supported by MySQL driver. Use ProviderAssignmentRunUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *ProviderAssignmentRunUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ProviderAssignmentRunCreateBulk is the builder for creating many ProviderAssignmentRun entities in bulk. +type ProviderAssignmentRunCreateBulk struct { + config + err error + builders []*ProviderAssignmentRunCreate + conflict []sql.ConflictOption +} + +// Save creates the ProviderAssignmentRun entities in the database. +func (_c *ProviderAssignmentRunCreateBulk) Save(ctx context.Context) ([]*ProviderAssignmentRun, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ProviderAssignmentRun, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ProviderAssignmentRunMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ProviderAssignmentRunCreateBulk) SaveX(ctx context.Context) []*ProviderAssignmentRun { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ProviderAssignmentRunCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ProviderAssignmentRunCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ProviderAssignmentRun.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ProviderAssignmentRunUpsert) { +// SetAssignedProviderID(v+v). +// }). +// Exec(ctx) +func (_c *ProviderAssignmentRunCreateBulk) OnConflict(opts ...sql.ConflictOption) *ProviderAssignmentRunUpsertBulk { + _c.conflict = opts + return &ProviderAssignmentRunUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ProviderAssignmentRun.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ProviderAssignmentRunCreateBulk) OnConflictColumns(columns ...string) *ProviderAssignmentRunUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ProviderAssignmentRunUpsertBulk{ + create: _c, + } +} + +// ProviderAssignmentRunUpsertBulk is the builder for "upsert"-ing +// a bulk of ProviderAssignmentRun nodes. +type ProviderAssignmentRunUpsertBulk struct { + create *ProviderAssignmentRunCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ProviderAssignmentRun.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(providerassignmentrun.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ProviderAssignmentRunUpsertBulk) UpdateNewValues() *ProviderAssignmentRunUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(providerassignmentrun.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ProviderAssignmentRun.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ProviderAssignmentRunUpsertBulk) Ignore() *ProviderAssignmentRunUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ProviderAssignmentRunUpsertBulk) DoNothing() *ProviderAssignmentRunUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ProviderAssignmentRunCreateBulk.OnConflict +// documentation for more info. +func (u *ProviderAssignmentRunUpsertBulk) Update(set func(*ProviderAssignmentRunUpsert)) *ProviderAssignmentRunUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ProviderAssignmentRunUpsert{UpdateSet: update}) + })) + return u +} + +// SetAssignedProviderID sets the "assigned_provider_id" field. +func (u *ProviderAssignmentRunUpsertBulk) SetAssignedProviderID(v string) *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetAssignedProviderID(v) + }) +} + +// UpdateAssignedProviderID sets the "assigned_provider_id" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertBulk) UpdateAssignedProviderID() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateAssignedProviderID() + }) +} + +// ClearAssignedProviderID clears the value of the "assigned_provider_id" field. +func (u *ProviderAssignmentRunUpsertBulk) ClearAssignedProviderID() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.ClearAssignedProviderID() + }) +} + +// SetAttemptedAt sets the "attempted_at" field. +func (u *ProviderAssignmentRunUpsertBulk) SetAttemptedAt(v time.Time) *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetAttemptedAt(v) + }) +} + +// UpdateAttemptedAt sets the "attempted_at" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertBulk) UpdateAttemptedAt() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateAttemptedAt() + }) +} + +// SetTrigger sets the "trigger" field. +func (u *ProviderAssignmentRunUpsertBulk) SetTrigger(v string) *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetTrigger(v) + }) +} + +// UpdateTrigger sets the "trigger" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertBulk) UpdateTrigger() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateTrigger() + }) +} + +// SetResult sets the "result" field. +func (u *ProviderAssignmentRunUpsertBulk) SetResult(v string) *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetResult(v) + }) +} + +// UpdateResult sets the "result" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertBulk) UpdateResult() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateResult() + }) +} + +// SetUsedFallback sets the "used_fallback" field. +func (u *ProviderAssignmentRunUpsertBulk) SetUsedFallback(v bool) *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetUsedFallback(v) + }) +} + +// UpdateUsedFallback sets the "used_fallback" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertBulk) UpdateUsedFallback() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateUsedFallback() + }) +} + +// SetMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertBulk) SetMarketBuyRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetMarketBuyRateSnapshot(v) + }) +} + +// AddMarketBuyRateSnapshot adds v to the "market_buy_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertBulk) AddMarketBuyRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.AddMarketBuyRateSnapshot(v) + }) +} + +// UpdateMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertBulk) UpdateMarketBuyRateSnapshot() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateMarketBuyRateSnapshot() + }) +} + +// ClearMarketBuyRateSnapshot clears the value of the "market_buy_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertBulk) ClearMarketBuyRateSnapshot() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.ClearMarketBuyRateSnapshot() + }) +} + +// SetMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertBulk) SetMarketSellRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetMarketSellRateSnapshot(v) + }) +} + +// AddMarketSellRateSnapshot adds v to the "market_sell_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertBulk) AddMarketSellRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.AddMarketSellRateSnapshot(v) + }) +} + +// UpdateMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertBulk) UpdateMarketSellRateSnapshot() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateMarketSellRateSnapshot() + }) +} + +// ClearMarketSellRateSnapshot clears the value of the "market_sell_rate_snapshot" field. +func (u *ProviderAssignmentRunUpsertBulk) ClearMarketSellRateSnapshot() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.ClearMarketSellRateSnapshot() + }) +} + +// SetErrorMessage sets the "error_message" field. +func (u *ProviderAssignmentRunUpsertBulk) SetErrorMessage(v string) *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.SetErrorMessage(v) + }) +} + +// UpdateErrorMessage sets the "error_message" field to the value that was provided on create. +func (u *ProviderAssignmentRunUpsertBulk) UpdateErrorMessage() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.UpdateErrorMessage() + }) +} + +// ClearErrorMessage clears the value of the "error_message" field. +func (u *ProviderAssignmentRunUpsertBulk) ClearErrorMessage() *ProviderAssignmentRunUpsertBulk { + return u.Update(func(s *ProviderAssignmentRunUpsert) { + s.ClearErrorMessage() + }) +} + +// Exec executes the query. +func (u *ProviderAssignmentRunUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the ProviderAssignmentRunCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ProviderAssignmentRunCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ProviderAssignmentRunUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/providerassignmentrun_delete.go b/ent/providerassignmentrun_delete.go new file mode 100644 index 000000000..3ba76527f --- /dev/null +++ b/ent/providerassignmentrun_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/paycrest/aggregator/ent/predicate" + "github.com/paycrest/aggregator/ent/providerassignmentrun" +) + +// ProviderAssignmentRunDelete is the builder for deleting a ProviderAssignmentRun entity. +type ProviderAssignmentRunDelete struct { + config + hooks []Hook + mutation *ProviderAssignmentRunMutation +} + +// Where appends a list predicates to the ProviderAssignmentRunDelete builder. +func (_d *ProviderAssignmentRunDelete) Where(ps ...predicate.ProviderAssignmentRun) *ProviderAssignmentRunDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ProviderAssignmentRunDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ProviderAssignmentRunDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ProviderAssignmentRunDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(providerassignmentrun.Table, sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ProviderAssignmentRunDeleteOne is the builder for deleting a single ProviderAssignmentRun entity. +type ProviderAssignmentRunDeleteOne struct { + _d *ProviderAssignmentRunDelete +} + +// Where appends a list predicates to the ProviderAssignmentRunDelete builder. +func (_d *ProviderAssignmentRunDeleteOne) Where(ps ...predicate.ProviderAssignmentRun) *ProviderAssignmentRunDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ProviderAssignmentRunDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{providerassignmentrun.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ProviderAssignmentRunDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/providerassignmentrun_query.go b/ent/providerassignmentrun_query.go new file mode 100644 index 000000000..03eb3da93 --- /dev/null +++ b/ent/providerassignmentrun_query.go @@ -0,0 +1,690 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/predicate" + "github.com/paycrest/aggregator/ent/providerassignmentrun" + "github.com/paycrest/aggregator/ent/providerordertoken" +) + +// ProviderAssignmentRunQuery is the builder for querying ProviderAssignmentRun entities. +type ProviderAssignmentRunQuery struct { + config + ctx *QueryContext + order []providerassignmentrun.OrderOption + inters []Interceptor + predicates []predicate.ProviderAssignmentRun + withPaymentOrder *PaymentOrderQuery + withProviderOrderToken *ProviderOrderTokenQuery + withFKs bool + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ProviderAssignmentRunQuery builder. +func (_q *ProviderAssignmentRunQuery) Where(ps ...predicate.ProviderAssignmentRun) *ProviderAssignmentRunQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ProviderAssignmentRunQuery) Limit(limit int) *ProviderAssignmentRunQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ProviderAssignmentRunQuery) Offset(offset int) *ProviderAssignmentRunQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *ProviderAssignmentRunQuery) Unique(unique bool) *ProviderAssignmentRunQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ProviderAssignmentRunQuery) Order(o ...providerassignmentrun.OrderOption) *ProviderAssignmentRunQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryPaymentOrder chains the current query on the "payment_order" edge. +func (_q *ProviderAssignmentRunQuery) QueryPaymentOrder() *PaymentOrderQuery { + query := (&PaymentOrderClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(providerassignmentrun.Table, providerassignmentrun.FieldID, selector), + sqlgraph.To(paymentorder.Table, paymentorder.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, providerassignmentrun.PaymentOrderTable, providerassignmentrun.PaymentOrderColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryProviderOrderToken chains the current query on the "provider_order_token" edge. +func (_q *ProviderAssignmentRunQuery) QueryProviderOrderToken() *ProviderOrderTokenQuery { + query := (&ProviderOrderTokenClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(providerassignmentrun.Table, providerassignmentrun.FieldID, selector), + sqlgraph.To(providerordertoken.Table, providerordertoken.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, providerassignmentrun.ProviderOrderTokenTable, providerassignmentrun.ProviderOrderTokenColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ProviderAssignmentRun entity from the query. +// Returns a *NotFoundError when no ProviderAssignmentRun was found. +func (_q *ProviderAssignmentRunQuery) First(ctx context.Context) (*ProviderAssignmentRun, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{providerassignmentrun.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ProviderAssignmentRunQuery) FirstX(ctx context.Context) *ProviderAssignmentRun { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ProviderAssignmentRun ID from the query. +// Returns a *NotFoundError when no ProviderAssignmentRun ID was found. +func (_q *ProviderAssignmentRunQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{providerassignmentrun.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ProviderAssignmentRunQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ProviderAssignmentRun entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ProviderAssignmentRun entity is found. +// Returns a *NotFoundError when no ProviderAssignmentRun entities are found. +func (_q *ProviderAssignmentRunQuery) Only(ctx context.Context) (*ProviderAssignmentRun, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{providerassignmentrun.Label} + default: + return nil, &NotSingularError{providerassignmentrun.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ProviderAssignmentRunQuery) OnlyX(ctx context.Context) *ProviderAssignmentRun { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ProviderAssignmentRun ID in the query. +// Returns a *NotSingularError when more than one ProviderAssignmentRun ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ProviderAssignmentRunQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{providerassignmentrun.Label} + default: + err = &NotSingularError{providerassignmentrun.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ProviderAssignmentRunQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of ProviderAssignmentRuns. +func (_q *ProviderAssignmentRunQuery) All(ctx context.Context) ([]*ProviderAssignmentRun, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ProviderAssignmentRun, *ProviderAssignmentRunQuery]() + return withInterceptors[[]*ProviderAssignmentRun](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ProviderAssignmentRunQuery) AllX(ctx context.Context) []*ProviderAssignmentRun { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ProviderAssignmentRun IDs. +func (_q *ProviderAssignmentRunQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(providerassignmentrun.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ProviderAssignmentRunQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ProviderAssignmentRunQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ProviderAssignmentRunQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ProviderAssignmentRunQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ProviderAssignmentRunQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ProviderAssignmentRunQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ProviderAssignmentRunQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ProviderAssignmentRunQuery) Clone() *ProviderAssignmentRunQuery { + if _q == nil { + return nil + } + return &ProviderAssignmentRunQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]providerassignmentrun.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ProviderAssignmentRun{}, _q.predicates...), + withPaymentOrder: _q.withPaymentOrder.Clone(), + withProviderOrderToken: _q.withProviderOrderToken.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithPaymentOrder tells the query-builder to eager-load the nodes that are connected to +// the "payment_order" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ProviderAssignmentRunQuery) WithPaymentOrder(opts ...func(*PaymentOrderQuery)) *ProviderAssignmentRunQuery { + query := (&PaymentOrderClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withPaymentOrder = query + return _q +} + +// WithProviderOrderToken tells the query-builder to eager-load the nodes that are connected to +// the "provider_order_token" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ProviderAssignmentRunQuery) WithProviderOrderToken(opts ...func(*ProviderOrderTokenQuery)) *ProviderAssignmentRunQuery { + query := (&ProviderOrderTokenClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withProviderOrderToken = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// AssignedProviderID string `json:"assigned_provider_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ProviderAssignmentRun.Query(). +// GroupBy(providerassignmentrun.FieldAssignedProviderID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *ProviderAssignmentRunQuery) GroupBy(field string, fields ...string) *ProviderAssignmentRunGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ProviderAssignmentRunGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = providerassignmentrun.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// AssignedProviderID string `json:"assigned_provider_id,omitempty"` +// } +// +// client.ProviderAssignmentRun.Query(). +// Select(providerassignmentrun.FieldAssignedProviderID). +// Scan(ctx, &v) +func (_q *ProviderAssignmentRunQuery) Select(fields ...string) *ProviderAssignmentRunSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ProviderAssignmentRunSelect{ProviderAssignmentRunQuery: _q} + sbuild.label = providerassignmentrun.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ProviderAssignmentRunSelect configured with the given aggregations. +func (_q *ProviderAssignmentRunQuery) Aggregate(fns ...AggregateFunc) *ProviderAssignmentRunSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ProviderAssignmentRunQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !providerassignmentrun.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ProviderAssignmentRunQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ProviderAssignmentRun, error) { + var ( + nodes = []*ProviderAssignmentRun{} + withFKs = _q.withFKs + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withPaymentOrder != nil, + _q.withProviderOrderToken != nil, + } + ) + if _q.withPaymentOrder != nil || _q.withProviderOrderToken != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, providerassignmentrun.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ProviderAssignmentRun).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ProviderAssignmentRun{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withPaymentOrder; query != nil { + if err := _q.loadPaymentOrder(ctx, query, nodes, nil, + func(n *ProviderAssignmentRun, e *PaymentOrder) { n.Edges.PaymentOrder = e }); err != nil { + return nil, err + } + } + if query := _q.withProviderOrderToken; query != nil { + if err := _q.loadProviderOrderToken(ctx, query, nodes, nil, + func(n *ProviderAssignmentRun, e *ProviderOrderToken) { n.Edges.ProviderOrderToken = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ProviderAssignmentRunQuery) loadPaymentOrder(ctx context.Context, query *PaymentOrderQuery, nodes []*ProviderAssignmentRun, init func(*ProviderAssignmentRun), assign func(*ProviderAssignmentRun, *PaymentOrder)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*ProviderAssignmentRun) + for i := range nodes { + if nodes[i].payment_order_provider_assignment_runs == nil { + continue + } + fk := *nodes[i].payment_order_provider_assignment_runs + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(paymentorder.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "payment_order_provider_assignment_runs" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ProviderAssignmentRunQuery) loadProviderOrderToken(ctx context.Context, query *ProviderOrderTokenQuery, nodes []*ProviderAssignmentRun, init func(*ProviderAssignmentRun), assign func(*ProviderAssignmentRun, *ProviderOrderToken)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*ProviderAssignmentRun) + for i := range nodes { + if nodes[i].provider_order_token_assignment_runs == nil { + continue + } + fk := *nodes[i].provider_order_token_assignment_runs + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(providerordertoken.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "provider_order_token_assignment_runs" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ProviderAssignmentRunQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ProviderAssignmentRunQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(providerassignmentrun.Table, providerassignmentrun.Columns, sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, providerassignmentrun.FieldID) + for i := range fields { + if fields[i] != providerassignmentrun.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ProviderAssignmentRunQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(providerassignmentrun.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = providerassignmentrun.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ProviderAssignmentRunGroupBy is the group-by builder for ProviderAssignmentRun entities. +type ProviderAssignmentRunGroupBy struct { + selector + build *ProviderAssignmentRunQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ProviderAssignmentRunGroupBy) Aggregate(fns ...AggregateFunc) *ProviderAssignmentRunGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ProviderAssignmentRunGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ProviderAssignmentRunQuery, *ProviderAssignmentRunGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ProviderAssignmentRunGroupBy) sqlScan(ctx context.Context, root *ProviderAssignmentRunQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ProviderAssignmentRunSelect is the builder for selecting fields of ProviderAssignmentRun entities. +type ProviderAssignmentRunSelect struct { + *ProviderAssignmentRunQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ProviderAssignmentRunSelect) Aggregate(fns ...AggregateFunc) *ProviderAssignmentRunSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ProviderAssignmentRunSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ProviderAssignmentRunQuery, *ProviderAssignmentRunSelect](ctx, _s.ProviderAssignmentRunQuery, _s, _s.inters, v) +} + +func (_s *ProviderAssignmentRunSelect) sqlScan(ctx context.Context, root *ProviderAssignmentRunQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/ent/providerassignmentrun_update.go b/ent/providerassignmentrun_update.go new file mode 100644 index 000000000..f51b8eddd --- /dev/null +++ b/ent/providerassignmentrun_update.go @@ -0,0 +1,816 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/predicate" + "github.com/paycrest/aggregator/ent/providerassignmentrun" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/shopspring/decimal" +) + +// ProviderAssignmentRunUpdate is the builder for updating ProviderAssignmentRun entities. +type ProviderAssignmentRunUpdate struct { + config + hooks []Hook + mutation *ProviderAssignmentRunMutation +} + +// Where appends a list predicates to the ProviderAssignmentRunUpdate builder. +func (_u *ProviderAssignmentRunUpdate) Where(ps ...predicate.ProviderAssignmentRun) *ProviderAssignmentRunUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetAssignedProviderID sets the "assigned_provider_id" field. +func (_u *ProviderAssignmentRunUpdate) SetAssignedProviderID(v string) *ProviderAssignmentRunUpdate { + _u.mutation.SetAssignedProviderID(v) + return _u +} + +// SetNillableAssignedProviderID sets the "assigned_provider_id" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdate) SetNillableAssignedProviderID(v *string) *ProviderAssignmentRunUpdate { + if v != nil { + _u.SetAssignedProviderID(*v) + } + return _u +} + +// ClearAssignedProviderID clears the value of the "assigned_provider_id" field. +func (_u *ProviderAssignmentRunUpdate) ClearAssignedProviderID() *ProviderAssignmentRunUpdate { + _u.mutation.ClearAssignedProviderID() + return _u +} + +// SetAttemptedAt sets the "attempted_at" field. +func (_u *ProviderAssignmentRunUpdate) SetAttemptedAt(v time.Time) *ProviderAssignmentRunUpdate { + _u.mutation.SetAttemptedAt(v) + return _u +} + +// SetNillableAttemptedAt sets the "attempted_at" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdate) SetNillableAttemptedAt(v *time.Time) *ProviderAssignmentRunUpdate { + if v != nil { + _u.SetAttemptedAt(*v) + } + return _u +} + +// SetTrigger sets the "trigger" field. +func (_u *ProviderAssignmentRunUpdate) SetTrigger(v string) *ProviderAssignmentRunUpdate { + _u.mutation.SetTrigger(v) + return _u +} + +// SetNillableTrigger sets the "trigger" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdate) SetNillableTrigger(v *string) *ProviderAssignmentRunUpdate { + if v != nil { + _u.SetTrigger(*v) + } + return _u +} + +// SetResult sets the "result" field. +func (_u *ProviderAssignmentRunUpdate) SetResult(v string) *ProviderAssignmentRunUpdate { + _u.mutation.SetResult(v) + return _u +} + +// SetNillableResult sets the "result" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdate) SetNillableResult(v *string) *ProviderAssignmentRunUpdate { + if v != nil { + _u.SetResult(*v) + } + return _u +} + +// SetUsedFallback sets the "used_fallback" field. +func (_u *ProviderAssignmentRunUpdate) SetUsedFallback(v bool) *ProviderAssignmentRunUpdate { + _u.mutation.SetUsedFallback(v) + return _u +} + +// SetNillableUsedFallback sets the "used_fallback" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdate) SetNillableUsedFallback(v *bool) *ProviderAssignmentRunUpdate { + if v != nil { + _u.SetUsedFallback(*v) + } + return _u +} + +// SetMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdate) SetMarketBuyRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpdate { + _u.mutation.ResetMarketBuyRateSnapshot() + _u.mutation.SetMarketBuyRateSnapshot(v) + return _u +} + +// SetNillableMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdate) SetNillableMarketBuyRateSnapshot(v *decimal.Decimal) *ProviderAssignmentRunUpdate { + if v != nil { + _u.SetMarketBuyRateSnapshot(*v) + } + return _u +} + +// AddMarketBuyRateSnapshot adds value to the "market_buy_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdate) AddMarketBuyRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpdate { + _u.mutation.AddMarketBuyRateSnapshot(v) + return _u +} + +// ClearMarketBuyRateSnapshot clears the value of the "market_buy_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdate) ClearMarketBuyRateSnapshot() *ProviderAssignmentRunUpdate { + _u.mutation.ClearMarketBuyRateSnapshot() + return _u +} + +// SetMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdate) SetMarketSellRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpdate { + _u.mutation.ResetMarketSellRateSnapshot() + _u.mutation.SetMarketSellRateSnapshot(v) + return _u +} + +// SetNillableMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdate) SetNillableMarketSellRateSnapshot(v *decimal.Decimal) *ProviderAssignmentRunUpdate { + if v != nil { + _u.SetMarketSellRateSnapshot(*v) + } + return _u +} + +// AddMarketSellRateSnapshot adds value to the "market_sell_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdate) AddMarketSellRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpdate { + _u.mutation.AddMarketSellRateSnapshot(v) + return _u +} + +// ClearMarketSellRateSnapshot clears the value of the "market_sell_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdate) ClearMarketSellRateSnapshot() *ProviderAssignmentRunUpdate { + _u.mutation.ClearMarketSellRateSnapshot() + return _u +} + +// SetErrorMessage sets the "error_message" field. +func (_u *ProviderAssignmentRunUpdate) SetErrorMessage(v string) *ProviderAssignmentRunUpdate { + _u.mutation.SetErrorMessage(v) + return _u +} + +// SetNillableErrorMessage sets the "error_message" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdate) SetNillableErrorMessage(v *string) *ProviderAssignmentRunUpdate { + if v != nil { + _u.SetErrorMessage(*v) + } + return _u +} + +// ClearErrorMessage clears the value of the "error_message" field. +func (_u *ProviderAssignmentRunUpdate) ClearErrorMessage() *ProviderAssignmentRunUpdate { + _u.mutation.ClearErrorMessage() + return _u +} + +// SetPaymentOrderID sets the "payment_order" edge to the PaymentOrder entity by ID. +func (_u *ProviderAssignmentRunUpdate) SetPaymentOrderID(id uuid.UUID) *ProviderAssignmentRunUpdate { + _u.mutation.SetPaymentOrderID(id) + return _u +} + +// SetPaymentOrder sets the "payment_order" edge to the PaymentOrder entity. +func (_u *ProviderAssignmentRunUpdate) SetPaymentOrder(v *PaymentOrder) *ProviderAssignmentRunUpdate { + return _u.SetPaymentOrderID(v.ID) +} + +// SetProviderOrderTokenID sets the "provider_order_token" edge to the ProviderOrderToken entity by ID. +func (_u *ProviderAssignmentRunUpdate) SetProviderOrderTokenID(id int) *ProviderAssignmentRunUpdate { + _u.mutation.SetProviderOrderTokenID(id) + return _u +} + +// SetNillableProviderOrderTokenID sets the "provider_order_token" edge to the ProviderOrderToken entity by ID if the given value is not nil. +func (_u *ProviderAssignmentRunUpdate) SetNillableProviderOrderTokenID(id *int) *ProviderAssignmentRunUpdate { + if id != nil { + _u = _u.SetProviderOrderTokenID(*id) + } + return _u +} + +// SetProviderOrderToken sets the "provider_order_token" edge to the ProviderOrderToken entity. +func (_u *ProviderAssignmentRunUpdate) SetProviderOrderToken(v *ProviderOrderToken) *ProviderAssignmentRunUpdate { + return _u.SetProviderOrderTokenID(v.ID) +} + +// Mutation returns the ProviderAssignmentRunMutation object of the builder. +func (_u *ProviderAssignmentRunUpdate) Mutation() *ProviderAssignmentRunMutation { + return _u.mutation +} + +// ClearPaymentOrder clears the "payment_order" edge to the PaymentOrder entity. +func (_u *ProviderAssignmentRunUpdate) ClearPaymentOrder() *ProviderAssignmentRunUpdate { + _u.mutation.ClearPaymentOrder() + return _u +} + +// ClearProviderOrderToken clears the "provider_order_token" edge to the ProviderOrderToken entity. +func (_u *ProviderAssignmentRunUpdate) ClearProviderOrderToken() *ProviderAssignmentRunUpdate { + _u.mutation.ClearProviderOrderToken() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ProviderAssignmentRunUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ProviderAssignmentRunUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ProviderAssignmentRunUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ProviderAssignmentRunUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ProviderAssignmentRunUpdate) check() error { + if v, ok := _u.mutation.AssignedProviderID(); ok { + if err := providerassignmentrun.AssignedProviderIDValidator(v); err != nil { + return &ValidationError{Name: "assigned_provider_id", err: fmt.Errorf(`ent: validator failed for field "ProviderAssignmentRun.assigned_provider_id": %w`, err)} + } + } + if v, ok := _u.mutation.Trigger(); ok { + if err := providerassignmentrun.TriggerValidator(v); err != nil { + return &ValidationError{Name: "trigger", err: fmt.Errorf(`ent: validator failed for field "ProviderAssignmentRun.trigger": %w`, err)} + } + } + if v, ok := _u.mutation.Result(); ok { + if err := providerassignmentrun.ResultValidator(v); err != nil { + return &ValidationError{Name: "result", err: fmt.Errorf(`ent: validator failed for field "ProviderAssignmentRun.result": %w`, err)} + } + } + if _u.mutation.PaymentOrderCleared() && len(_u.mutation.PaymentOrderIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ProviderAssignmentRun.payment_order"`) + } + return nil +} + +func (_u *ProviderAssignmentRunUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(providerassignmentrun.Table, providerassignmentrun.Columns, sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.AssignedProviderID(); ok { + _spec.SetField(providerassignmentrun.FieldAssignedProviderID, field.TypeString, value) + } + if _u.mutation.AssignedProviderIDCleared() { + _spec.ClearField(providerassignmentrun.FieldAssignedProviderID, field.TypeString) + } + if value, ok := _u.mutation.AttemptedAt(); ok { + _spec.SetField(providerassignmentrun.FieldAttemptedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.Trigger(); ok { + _spec.SetField(providerassignmentrun.FieldTrigger, field.TypeString, value) + } + if value, ok := _u.mutation.Result(); ok { + _spec.SetField(providerassignmentrun.FieldResult, field.TypeString, value) + } + if value, ok := _u.mutation.UsedFallback(); ok { + _spec.SetField(providerassignmentrun.FieldUsedFallback, field.TypeBool, value) + } + if value, ok := _u.mutation.MarketBuyRateSnapshot(); ok { + _spec.SetField(providerassignmentrun.FieldMarketBuyRateSnapshot, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedMarketBuyRateSnapshot(); ok { + _spec.AddField(providerassignmentrun.FieldMarketBuyRateSnapshot, field.TypeFloat64, value) + } + if _u.mutation.MarketBuyRateSnapshotCleared() { + _spec.ClearField(providerassignmentrun.FieldMarketBuyRateSnapshot, field.TypeFloat64) + } + if value, ok := _u.mutation.MarketSellRateSnapshot(); ok { + _spec.SetField(providerassignmentrun.FieldMarketSellRateSnapshot, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedMarketSellRateSnapshot(); ok { + _spec.AddField(providerassignmentrun.FieldMarketSellRateSnapshot, field.TypeFloat64, value) + } + if _u.mutation.MarketSellRateSnapshotCleared() { + _spec.ClearField(providerassignmentrun.FieldMarketSellRateSnapshot, field.TypeFloat64) + } + if value, ok := _u.mutation.ErrorMessage(); ok { + _spec.SetField(providerassignmentrun.FieldErrorMessage, field.TypeString, value) + } + if _u.mutation.ErrorMessageCleared() { + _spec.ClearField(providerassignmentrun.FieldErrorMessage, field.TypeString) + } + if _u.mutation.PaymentOrderCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerassignmentrun.PaymentOrderTable, + Columns: []string{providerassignmentrun.PaymentOrderColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.PaymentOrderIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerassignmentrun.PaymentOrderTable, + Columns: []string{providerassignmentrun.PaymentOrderColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ProviderOrderTokenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerassignmentrun.ProviderOrderTokenTable, + Columns: []string{providerassignmentrun.ProviderOrderTokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertoken.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ProviderOrderTokenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerassignmentrun.ProviderOrderTokenTable, + Columns: []string{providerassignmentrun.ProviderOrderTokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertoken.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{providerassignmentrun.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ProviderAssignmentRunUpdateOne is the builder for updating a single ProviderAssignmentRun entity. +type ProviderAssignmentRunUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ProviderAssignmentRunMutation +} + +// SetAssignedProviderID sets the "assigned_provider_id" field. +func (_u *ProviderAssignmentRunUpdateOne) SetAssignedProviderID(v string) *ProviderAssignmentRunUpdateOne { + _u.mutation.SetAssignedProviderID(v) + return _u +} + +// SetNillableAssignedProviderID sets the "assigned_provider_id" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdateOne) SetNillableAssignedProviderID(v *string) *ProviderAssignmentRunUpdateOne { + if v != nil { + _u.SetAssignedProviderID(*v) + } + return _u +} + +// ClearAssignedProviderID clears the value of the "assigned_provider_id" field. +func (_u *ProviderAssignmentRunUpdateOne) ClearAssignedProviderID() *ProviderAssignmentRunUpdateOne { + _u.mutation.ClearAssignedProviderID() + return _u +} + +// SetAttemptedAt sets the "attempted_at" field. +func (_u *ProviderAssignmentRunUpdateOne) SetAttemptedAt(v time.Time) *ProviderAssignmentRunUpdateOne { + _u.mutation.SetAttemptedAt(v) + return _u +} + +// SetNillableAttemptedAt sets the "attempted_at" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdateOne) SetNillableAttemptedAt(v *time.Time) *ProviderAssignmentRunUpdateOne { + if v != nil { + _u.SetAttemptedAt(*v) + } + return _u +} + +// SetTrigger sets the "trigger" field. +func (_u *ProviderAssignmentRunUpdateOne) SetTrigger(v string) *ProviderAssignmentRunUpdateOne { + _u.mutation.SetTrigger(v) + return _u +} + +// SetNillableTrigger sets the "trigger" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdateOne) SetNillableTrigger(v *string) *ProviderAssignmentRunUpdateOne { + if v != nil { + _u.SetTrigger(*v) + } + return _u +} + +// SetResult sets the "result" field. +func (_u *ProviderAssignmentRunUpdateOne) SetResult(v string) *ProviderAssignmentRunUpdateOne { + _u.mutation.SetResult(v) + return _u +} + +// SetNillableResult sets the "result" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdateOne) SetNillableResult(v *string) *ProviderAssignmentRunUpdateOne { + if v != nil { + _u.SetResult(*v) + } + return _u +} + +// SetUsedFallback sets the "used_fallback" field. +func (_u *ProviderAssignmentRunUpdateOne) SetUsedFallback(v bool) *ProviderAssignmentRunUpdateOne { + _u.mutation.SetUsedFallback(v) + return _u +} + +// SetNillableUsedFallback sets the "used_fallback" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdateOne) SetNillableUsedFallback(v *bool) *ProviderAssignmentRunUpdateOne { + if v != nil { + _u.SetUsedFallback(*v) + } + return _u +} + +// SetMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdateOne) SetMarketBuyRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpdateOne { + _u.mutation.ResetMarketBuyRateSnapshot() + _u.mutation.SetMarketBuyRateSnapshot(v) + return _u +} + +// SetNillableMarketBuyRateSnapshot sets the "market_buy_rate_snapshot" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdateOne) SetNillableMarketBuyRateSnapshot(v *decimal.Decimal) *ProviderAssignmentRunUpdateOne { + if v != nil { + _u.SetMarketBuyRateSnapshot(*v) + } + return _u +} + +// AddMarketBuyRateSnapshot adds value to the "market_buy_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdateOne) AddMarketBuyRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpdateOne { + _u.mutation.AddMarketBuyRateSnapshot(v) + return _u +} + +// ClearMarketBuyRateSnapshot clears the value of the "market_buy_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdateOne) ClearMarketBuyRateSnapshot() *ProviderAssignmentRunUpdateOne { + _u.mutation.ClearMarketBuyRateSnapshot() + return _u +} + +// SetMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdateOne) SetMarketSellRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpdateOne { + _u.mutation.ResetMarketSellRateSnapshot() + _u.mutation.SetMarketSellRateSnapshot(v) + return _u +} + +// SetNillableMarketSellRateSnapshot sets the "market_sell_rate_snapshot" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdateOne) SetNillableMarketSellRateSnapshot(v *decimal.Decimal) *ProviderAssignmentRunUpdateOne { + if v != nil { + _u.SetMarketSellRateSnapshot(*v) + } + return _u +} + +// AddMarketSellRateSnapshot adds value to the "market_sell_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdateOne) AddMarketSellRateSnapshot(v decimal.Decimal) *ProviderAssignmentRunUpdateOne { + _u.mutation.AddMarketSellRateSnapshot(v) + return _u +} + +// ClearMarketSellRateSnapshot clears the value of the "market_sell_rate_snapshot" field. +func (_u *ProviderAssignmentRunUpdateOne) ClearMarketSellRateSnapshot() *ProviderAssignmentRunUpdateOne { + _u.mutation.ClearMarketSellRateSnapshot() + return _u +} + +// SetErrorMessage sets the "error_message" field. +func (_u *ProviderAssignmentRunUpdateOne) SetErrorMessage(v string) *ProviderAssignmentRunUpdateOne { + _u.mutation.SetErrorMessage(v) + return _u +} + +// SetNillableErrorMessage sets the "error_message" field if the given value is not nil. +func (_u *ProviderAssignmentRunUpdateOne) SetNillableErrorMessage(v *string) *ProviderAssignmentRunUpdateOne { + if v != nil { + _u.SetErrorMessage(*v) + } + return _u +} + +// ClearErrorMessage clears the value of the "error_message" field. +func (_u *ProviderAssignmentRunUpdateOne) ClearErrorMessage() *ProviderAssignmentRunUpdateOne { + _u.mutation.ClearErrorMessage() + return _u +} + +// SetPaymentOrderID sets the "payment_order" edge to the PaymentOrder entity by ID. +func (_u *ProviderAssignmentRunUpdateOne) SetPaymentOrderID(id uuid.UUID) *ProviderAssignmentRunUpdateOne { + _u.mutation.SetPaymentOrderID(id) + return _u +} + +// SetPaymentOrder sets the "payment_order" edge to the PaymentOrder entity. +func (_u *ProviderAssignmentRunUpdateOne) SetPaymentOrder(v *PaymentOrder) *ProviderAssignmentRunUpdateOne { + return _u.SetPaymentOrderID(v.ID) +} + +// SetProviderOrderTokenID sets the "provider_order_token" edge to the ProviderOrderToken entity by ID. +func (_u *ProviderAssignmentRunUpdateOne) SetProviderOrderTokenID(id int) *ProviderAssignmentRunUpdateOne { + _u.mutation.SetProviderOrderTokenID(id) + return _u +} + +// SetNillableProviderOrderTokenID sets the "provider_order_token" edge to the ProviderOrderToken entity by ID if the given value is not nil. +func (_u *ProviderAssignmentRunUpdateOne) SetNillableProviderOrderTokenID(id *int) *ProviderAssignmentRunUpdateOne { + if id != nil { + _u = _u.SetProviderOrderTokenID(*id) + } + return _u +} + +// SetProviderOrderToken sets the "provider_order_token" edge to the ProviderOrderToken entity. +func (_u *ProviderAssignmentRunUpdateOne) SetProviderOrderToken(v *ProviderOrderToken) *ProviderAssignmentRunUpdateOne { + return _u.SetProviderOrderTokenID(v.ID) +} + +// Mutation returns the ProviderAssignmentRunMutation object of the builder. +func (_u *ProviderAssignmentRunUpdateOne) Mutation() *ProviderAssignmentRunMutation { + return _u.mutation +} + +// ClearPaymentOrder clears the "payment_order" edge to the PaymentOrder entity. +func (_u *ProviderAssignmentRunUpdateOne) ClearPaymentOrder() *ProviderAssignmentRunUpdateOne { + _u.mutation.ClearPaymentOrder() + return _u +} + +// ClearProviderOrderToken clears the "provider_order_token" edge to the ProviderOrderToken entity. +func (_u *ProviderAssignmentRunUpdateOne) ClearProviderOrderToken() *ProviderAssignmentRunUpdateOne { + _u.mutation.ClearProviderOrderToken() + return _u +} + +// Where appends a list predicates to the ProviderAssignmentRunUpdate builder. +func (_u *ProviderAssignmentRunUpdateOne) Where(ps ...predicate.ProviderAssignmentRun) *ProviderAssignmentRunUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ProviderAssignmentRunUpdateOne) Select(field string, fields ...string) *ProviderAssignmentRunUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ProviderAssignmentRun entity. +func (_u *ProviderAssignmentRunUpdateOne) Save(ctx context.Context) (*ProviderAssignmentRun, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ProviderAssignmentRunUpdateOne) SaveX(ctx context.Context) *ProviderAssignmentRun { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ProviderAssignmentRunUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ProviderAssignmentRunUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ProviderAssignmentRunUpdateOne) check() error { + if v, ok := _u.mutation.AssignedProviderID(); ok { + if err := providerassignmentrun.AssignedProviderIDValidator(v); err != nil { + return &ValidationError{Name: "assigned_provider_id", err: fmt.Errorf(`ent: validator failed for field "ProviderAssignmentRun.assigned_provider_id": %w`, err)} + } + } + if v, ok := _u.mutation.Trigger(); ok { + if err := providerassignmentrun.TriggerValidator(v); err != nil { + return &ValidationError{Name: "trigger", err: fmt.Errorf(`ent: validator failed for field "ProviderAssignmentRun.trigger": %w`, err)} + } + } + if v, ok := _u.mutation.Result(); ok { + if err := providerassignmentrun.ResultValidator(v); err != nil { + return &ValidationError{Name: "result", err: fmt.Errorf(`ent: validator failed for field "ProviderAssignmentRun.result": %w`, err)} + } + } + if _u.mutation.PaymentOrderCleared() && len(_u.mutation.PaymentOrderIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ProviderAssignmentRun.payment_order"`) + } + return nil +} + +func (_u *ProviderAssignmentRunUpdateOne) sqlSave(ctx context.Context) (_node *ProviderAssignmentRun, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(providerassignmentrun.Table, providerassignmentrun.Columns, sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "ProviderAssignmentRun.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, providerassignmentrun.FieldID) + for _, f := range fields { + if !providerassignmentrun.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != providerassignmentrun.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.AssignedProviderID(); ok { + _spec.SetField(providerassignmentrun.FieldAssignedProviderID, field.TypeString, value) + } + if _u.mutation.AssignedProviderIDCleared() { + _spec.ClearField(providerassignmentrun.FieldAssignedProviderID, field.TypeString) + } + if value, ok := _u.mutation.AttemptedAt(); ok { + _spec.SetField(providerassignmentrun.FieldAttemptedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.Trigger(); ok { + _spec.SetField(providerassignmentrun.FieldTrigger, field.TypeString, value) + } + if value, ok := _u.mutation.Result(); ok { + _spec.SetField(providerassignmentrun.FieldResult, field.TypeString, value) + } + if value, ok := _u.mutation.UsedFallback(); ok { + _spec.SetField(providerassignmentrun.FieldUsedFallback, field.TypeBool, value) + } + if value, ok := _u.mutation.MarketBuyRateSnapshot(); ok { + _spec.SetField(providerassignmentrun.FieldMarketBuyRateSnapshot, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedMarketBuyRateSnapshot(); ok { + _spec.AddField(providerassignmentrun.FieldMarketBuyRateSnapshot, field.TypeFloat64, value) + } + if _u.mutation.MarketBuyRateSnapshotCleared() { + _spec.ClearField(providerassignmentrun.FieldMarketBuyRateSnapshot, field.TypeFloat64) + } + if value, ok := _u.mutation.MarketSellRateSnapshot(); ok { + _spec.SetField(providerassignmentrun.FieldMarketSellRateSnapshot, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedMarketSellRateSnapshot(); ok { + _spec.AddField(providerassignmentrun.FieldMarketSellRateSnapshot, field.TypeFloat64, value) + } + if _u.mutation.MarketSellRateSnapshotCleared() { + _spec.ClearField(providerassignmentrun.FieldMarketSellRateSnapshot, field.TypeFloat64) + } + if value, ok := _u.mutation.ErrorMessage(); ok { + _spec.SetField(providerassignmentrun.FieldErrorMessage, field.TypeString, value) + } + if _u.mutation.ErrorMessageCleared() { + _spec.ClearField(providerassignmentrun.FieldErrorMessage, field.TypeString) + } + if _u.mutation.PaymentOrderCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerassignmentrun.PaymentOrderTable, + Columns: []string{providerassignmentrun.PaymentOrderColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.PaymentOrderIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerassignmentrun.PaymentOrderTable, + Columns: []string{providerassignmentrun.PaymentOrderColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ProviderOrderTokenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerassignmentrun.ProviderOrderTokenTable, + Columns: []string{providerassignmentrun.ProviderOrderTokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertoken.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ProviderOrderTokenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerassignmentrun.ProviderOrderTokenTable, + Columns: []string{providerassignmentrun.ProviderOrderTokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertoken.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &ProviderAssignmentRun{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{providerassignmentrun.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/ent/providerordertoken.go b/ent/providerordertoken.go index 5118ab8d3..e13458202 100644 --- a/ent/providerordertoken.go +++ b/ent/providerordertoken.go @@ -50,6 +50,10 @@ type ProviderOrderToken struct { PayoutAddress string `json:"payout_address,omitempty"` // Network holds the value of the "network" field. Network string `json:"network,omitempty"` + // Score holds the value of the "score" field. + Score decimal.Decimal `json:"score,omitempty"` + // LastOrderAssignedAt holds the value of the "last_order_assigned_at" field. + LastOrderAssignedAt *time.Time `json:"last_order_assigned_at,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the ProviderOrderTokenQuery when eager-loading is set. Edges ProviderOrderTokenEdges `json:"edges"` @@ -67,9 +71,13 @@ type ProviderOrderTokenEdges struct { Token *Token `json:"token,omitempty"` // Currency holds the value of the currency edge. Currency *FiatCurrency `json:"currency,omitempty"` + // ScoreHistories holds the value of the score_histories edge. + ScoreHistories []*ProviderOrderTokenScoreHistory `json:"score_histories,omitempty"` + // AssignmentRuns holds the value of the assignment_runs edge. + AssignmentRuns []*ProviderAssignmentRun `json:"assignment_runs,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [3]bool + loadedTypes [5]bool } // ProviderOrErr returns the Provider value or an error if the edge @@ -105,18 +113,36 @@ func (e ProviderOrderTokenEdges) CurrencyOrErr() (*FiatCurrency, error) { return nil, &NotLoadedError{edge: "currency"} } +// ScoreHistoriesOrErr returns the ScoreHistories value or an error if the edge +// was not loaded in eager-loading. +func (e ProviderOrderTokenEdges) ScoreHistoriesOrErr() ([]*ProviderOrderTokenScoreHistory, error) { + if e.loadedTypes[3] { + return e.ScoreHistories, nil + } + return nil, &NotLoadedError{edge: "score_histories"} +} + +// AssignmentRunsOrErr returns the AssignmentRuns value or an error if the edge +// was not loaded in eager-loading. +func (e ProviderOrderTokenEdges) AssignmentRunsOrErr() ([]*ProviderAssignmentRun, error) { + if e.loadedTypes[4] { + return e.AssignmentRuns, nil + } + return nil, &NotLoadedError{edge: "assignment_runs"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*ProviderOrderToken) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { - case providerordertoken.FieldFixedBuyRate, providerordertoken.FieldFixedSellRate, providerordertoken.FieldFloatingBuyDelta, providerordertoken.FieldFloatingSellDelta, providerordertoken.FieldMaxOrderAmount, providerordertoken.FieldMinOrderAmount, providerordertoken.FieldMaxOrderAmountOtc, providerordertoken.FieldMinOrderAmountOtc, providerordertoken.FieldRateSlippage: + case providerordertoken.FieldFixedBuyRate, providerordertoken.FieldFixedSellRate, providerordertoken.FieldFloatingBuyDelta, providerordertoken.FieldFloatingSellDelta, providerordertoken.FieldMaxOrderAmount, providerordertoken.FieldMinOrderAmount, providerordertoken.FieldMaxOrderAmountOtc, providerordertoken.FieldMinOrderAmountOtc, providerordertoken.FieldRateSlippage, providerordertoken.FieldScore: values[i] = new(decimal.Decimal) case providerordertoken.FieldID: values[i] = new(sql.NullInt64) case providerordertoken.FieldSettlementAddress, providerordertoken.FieldPayoutAddress, providerordertoken.FieldNetwork: values[i] = new(sql.NullString) - case providerordertoken.FieldCreatedAt, providerordertoken.FieldUpdatedAt: + case providerordertoken.FieldCreatedAt, providerordertoken.FieldUpdatedAt, providerordertoken.FieldLastOrderAssignedAt: values[i] = new(sql.NullTime) case providerordertoken.ForeignKeys[0]: // fiat_currency_provider_order_tokens values[i] = &sql.NullScanner{S: new(uuid.UUID)} @@ -229,6 +255,19 @@ func (_m *ProviderOrderToken) assignValues(columns []string, values []any) error } else if value.Valid { _m.Network = value.String } + case providerordertoken.FieldScore: + if value, ok := values[i].(*decimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field score", values[i]) + } else if value != nil { + _m.Score = *value + } + case providerordertoken.FieldLastOrderAssignedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field last_order_assigned_at", values[i]) + } else if value.Valid { + _m.LastOrderAssignedAt = new(time.Time) + *_m.LastOrderAssignedAt = value.Time + } case providerordertoken.ForeignKeys[0]: if value, ok := values[i].(*sql.NullScanner); !ok { return fmt.Errorf("unexpected type %T for field fiat_currency_provider_order_tokens", values[i]) @@ -278,6 +317,16 @@ func (_m *ProviderOrderToken) QueryCurrency() *FiatCurrencyQuery { return NewProviderOrderTokenClient(_m.config).QueryCurrency(_m) } +// QueryScoreHistories queries the "score_histories" edge of the ProviderOrderToken entity. +func (_m *ProviderOrderToken) QueryScoreHistories() *ProviderOrderTokenScoreHistoryQuery { + return NewProviderOrderTokenClient(_m.config).QueryScoreHistories(_m) +} + +// QueryAssignmentRuns queries the "assignment_runs" edge of the ProviderOrderToken entity. +func (_m *ProviderOrderToken) QueryAssignmentRuns() *ProviderAssignmentRunQuery { + return NewProviderOrderTokenClient(_m.config).QueryAssignmentRuns(_m) +} + // Update returns a builder for updating this ProviderOrderToken. // Note that you need to call ProviderOrderToken.Unwrap() before calling this method if this ProviderOrderToken // was returned from a transaction, and the transaction was committed or rolled back. @@ -342,6 +391,14 @@ func (_m *ProviderOrderToken) String() string { builder.WriteString(", ") builder.WriteString("network=") builder.WriteString(_m.Network) + builder.WriteString(", ") + builder.WriteString("score=") + builder.WriteString(fmt.Sprintf("%v", _m.Score)) + builder.WriteString(", ") + if v := _m.LastOrderAssignedAt; v != nil { + builder.WriteString("last_order_assigned_at=") + builder.WriteString(v.Format(time.ANSIC)) + } builder.WriteByte(')') return builder.String() } diff --git a/ent/providerordertoken/providerordertoken.go b/ent/providerordertoken/providerordertoken.go index 9dfcf1b5c..e9f9fffab 100644 --- a/ent/providerordertoken/providerordertoken.go +++ b/ent/providerordertoken/providerordertoken.go @@ -7,6 +7,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/shopspring/decimal" ) const ( @@ -42,12 +43,20 @@ const ( FieldPayoutAddress = "payout_address" // FieldNetwork holds the string denoting the network field in the database. FieldNetwork = "network" + // FieldScore holds the string denoting the score field in the database. + FieldScore = "score" + // FieldLastOrderAssignedAt holds the string denoting the last_order_assigned_at field in the database. + FieldLastOrderAssignedAt = "last_order_assigned_at" // EdgeProvider holds the string denoting the provider edge name in mutations. EdgeProvider = "provider" // EdgeToken holds the string denoting the token edge name in mutations. EdgeToken = "token" // EdgeCurrency holds the string denoting the currency edge name in mutations. EdgeCurrency = "currency" + // EdgeScoreHistories holds the string denoting the score_histories edge name in mutations. + EdgeScoreHistories = "score_histories" + // EdgeAssignmentRuns holds the string denoting the assignment_runs edge name in mutations. + EdgeAssignmentRuns = "assignment_runs" // Table holds the table name of the providerordertoken in the database. Table = "provider_order_tokens" // ProviderTable is the table that holds the provider relation/edge. @@ -71,6 +80,20 @@ const ( CurrencyInverseTable = "fiat_currencies" // CurrencyColumn is the table column denoting the currency relation/edge. CurrencyColumn = "fiat_currency_provider_order_tokens" + // ScoreHistoriesTable is the table that holds the score_histories relation/edge. + ScoreHistoriesTable = "provider_order_token_score_histories" + // ScoreHistoriesInverseTable is the table name for the ProviderOrderTokenScoreHistory entity. + // It exists in this package in order to avoid circular dependency with the "providerordertokenscorehistory" package. + ScoreHistoriesInverseTable = "provider_order_token_score_histories" + // ScoreHistoriesColumn is the table column denoting the score_histories relation/edge. + ScoreHistoriesColumn = "provider_order_token_score_histories" + // AssignmentRunsTable is the table that holds the assignment_runs relation/edge. + AssignmentRunsTable = "provider_assignment_runs" + // AssignmentRunsInverseTable is the table name for the ProviderAssignmentRun entity. + // It exists in this package in order to avoid circular dependency with the "providerassignmentrun" package. + AssignmentRunsInverseTable = "provider_assignment_runs" + // AssignmentRunsColumn is the table column denoting the assignment_runs relation/edge. + AssignmentRunsColumn = "provider_order_token_assignment_runs" ) // Columns holds all SQL columns for providerordertoken fields. @@ -90,6 +113,8 @@ var Columns = []string{ FieldSettlementAddress, FieldPayoutAddress, FieldNetwork, + FieldScore, + FieldLastOrderAssignedAt, } // ForeignKeys holds the SQL foreign-keys that are owned by the "provider_order_tokens" @@ -122,6 +147,8 @@ var ( DefaultUpdatedAt func() time.Time // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. UpdateDefaultUpdatedAt func() time.Time + // DefaultScore holds the default value on creation for the "score" field. + DefaultScore func() decimal.Decimal ) // OrderOption defines the ordering options for the ProviderOrderToken queries. @@ -202,6 +229,16 @@ func ByNetwork(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldNetwork, opts...).ToFunc() } +// ByScore orders the results by the score field. +func ByScore(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScore, opts...).ToFunc() +} + +// ByLastOrderAssignedAt orders the results by the last_order_assigned_at field. +func ByLastOrderAssignedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLastOrderAssignedAt, opts...).ToFunc() +} + // ByProviderField orders the results by provider field. func ByProviderField(field string, opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -222,6 +259,34 @@ func ByCurrencyField(field string, opts ...sql.OrderTermOption) OrderOption { sqlgraph.OrderByNeighborTerms(s, newCurrencyStep(), sql.OrderByField(field, opts...)) } } + +// ByScoreHistoriesCount orders the results by score_histories count. +func ByScoreHistoriesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newScoreHistoriesStep(), opts...) + } +} + +// ByScoreHistories orders the results by score_histories terms. +func ByScoreHistories(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newScoreHistoriesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByAssignmentRunsCount orders the results by assignment_runs count. +func ByAssignmentRunsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newAssignmentRunsStep(), opts...) + } +} + +// ByAssignmentRuns orders the results by assignment_runs terms. +func ByAssignmentRuns(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newAssignmentRunsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newProviderStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -243,3 +308,17 @@ func newCurrencyStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.M2O, true, CurrencyTable, CurrencyColumn), ) } +func newScoreHistoriesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ScoreHistoriesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ScoreHistoriesTable, ScoreHistoriesColumn), + ) +} +func newAssignmentRunsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(AssignmentRunsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AssignmentRunsTable, AssignmentRunsColumn), + ) +} diff --git a/ent/providerordertoken/where.go b/ent/providerordertoken/where.go index d573c95d0..4536e045c 100644 --- a/ent/providerordertoken/where.go +++ b/ent/providerordertoken/where.go @@ -126,6 +126,16 @@ func Network(v string) predicate.ProviderOrderToken { return predicate.ProviderOrderToken(sql.FieldEQ(FieldNetwork, v)) } +// Score applies equality check predicate on the "score" field. It's identical to ScoreEQ. +func Score(v decimal.Decimal) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldEQ(FieldScore, v)) +} + +// LastOrderAssignedAt applies equality check predicate on the "last_order_assigned_at" field. It's identical to LastOrderAssignedAtEQ. +func LastOrderAssignedAt(v time.Time) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldEQ(FieldLastOrderAssignedAt, v)) +} + // CreatedAtEQ applies the EQ predicate on the "created_at" field. func CreatedAtEQ(v time.Time) predicate.ProviderOrderToken { return predicate.ProviderOrderToken(sql.FieldEQ(FieldCreatedAt, v)) @@ -821,6 +831,96 @@ func NetworkContainsFold(v string) predicate.ProviderOrderToken { return predicate.ProviderOrderToken(sql.FieldContainsFold(FieldNetwork, v)) } +// ScoreEQ applies the EQ predicate on the "score" field. +func ScoreEQ(v decimal.Decimal) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldEQ(FieldScore, v)) +} + +// ScoreNEQ applies the NEQ predicate on the "score" field. +func ScoreNEQ(v decimal.Decimal) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldNEQ(FieldScore, v)) +} + +// ScoreIn applies the In predicate on the "score" field. +func ScoreIn(vs ...decimal.Decimal) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldIn(FieldScore, vs...)) +} + +// ScoreNotIn applies the NotIn predicate on the "score" field. +func ScoreNotIn(vs ...decimal.Decimal) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldNotIn(FieldScore, vs...)) +} + +// ScoreGT applies the GT predicate on the "score" field. +func ScoreGT(v decimal.Decimal) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldGT(FieldScore, v)) +} + +// ScoreGTE applies the GTE predicate on the "score" field. +func ScoreGTE(v decimal.Decimal) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldGTE(FieldScore, v)) +} + +// ScoreLT applies the LT predicate on the "score" field. +func ScoreLT(v decimal.Decimal) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldLT(FieldScore, v)) +} + +// ScoreLTE applies the LTE predicate on the "score" field. +func ScoreLTE(v decimal.Decimal) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldLTE(FieldScore, v)) +} + +// LastOrderAssignedAtEQ applies the EQ predicate on the "last_order_assigned_at" field. +func LastOrderAssignedAtEQ(v time.Time) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldEQ(FieldLastOrderAssignedAt, v)) +} + +// LastOrderAssignedAtNEQ applies the NEQ predicate on the "last_order_assigned_at" field. +func LastOrderAssignedAtNEQ(v time.Time) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldNEQ(FieldLastOrderAssignedAt, v)) +} + +// LastOrderAssignedAtIn applies the In predicate on the "last_order_assigned_at" field. +func LastOrderAssignedAtIn(vs ...time.Time) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldIn(FieldLastOrderAssignedAt, vs...)) +} + +// LastOrderAssignedAtNotIn applies the NotIn predicate on the "last_order_assigned_at" field. +func LastOrderAssignedAtNotIn(vs ...time.Time) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldNotIn(FieldLastOrderAssignedAt, vs...)) +} + +// LastOrderAssignedAtGT applies the GT predicate on the "last_order_assigned_at" field. +func LastOrderAssignedAtGT(v time.Time) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldGT(FieldLastOrderAssignedAt, v)) +} + +// LastOrderAssignedAtGTE applies the GTE predicate on the "last_order_assigned_at" field. +func LastOrderAssignedAtGTE(v time.Time) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldGTE(FieldLastOrderAssignedAt, v)) +} + +// LastOrderAssignedAtLT applies the LT predicate on the "last_order_assigned_at" field. +func LastOrderAssignedAtLT(v time.Time) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldLT(FieldLastOrderAssignedAt, v)) +} + +// LastOrderAssignedAtLTE applies the LTE predicate on the "last_order_assigned_at" field. +func LastOrderAssignedAtLTE(v time.Time) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldLTE(FieldLastOrderAssignedAt, v)) +} + +// LastOrderAssignedAtIsNil applies the IsNil predicate on the "last_order_assigned_at" field. +func LastOrderAssignedAtIsNil() predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldIsNull(FieldLastOrderAssignedAt)) +} + +// LastOrderAssignedAtNotNil applies the NotNil predicate on the "last_order_assigned_at" field. +func LastOrderAssignedAtNotNil() predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(sql.FieldNotNull(FieldLastOrderAssignedAt)) +} + // HasProvider applies the HasEdge predicate on the "provider" edge. func HasProvider() predicate.ProviderOrderToken { return predicate.ProviderOrderToken(func(s *sql.Selector) { @@ -890,6 +990,52 @@ func HasCurrencyWith(preds ...predicate.FiatCurrency) predicate.ProviderOrderTok }) } +// HasScoreHistories applies the HasEdge predicate on the "score_histories" edge. +func HasScoreHistories() predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ScoreHistoriesTable, ScoreHistoriesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasScoreHistoriesWith applies the HasEdge predicate on the "score_histories" edge with a given conditions (other predicates). +func HasScoreHistoriesWith(preds ...predicate.ProviderOrderTokenScoreHistory) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(func(s *sql.Selector) { + step := newScoreHistoriesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasAssignmentRuns applies the HasEdge predicate on the "assignment_runs" edge. +func HasAssignmentRuns() predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, AssignmentRunsTable, AssignmentRunsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasAssignmentRunsWith applies the HasEdge predicate on the "assignment_runs" edge with a given conditions (other predicates). +func HasAssignmentRunsWith(preds ...predicate.ProviderAssignmentRun) predicate.ProviderOrderToken { + return predicate.ProviderOrderToken(func(s *sql.Selector) { + step := newAssignmentRunsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // And groups predicates with the AND operator between them. func And(predicates ...predicate.ProviderOrderToken) predicate.ProviderOrderToken { return predicate.ProviderOrderToken(sql.AndPredicates(predicates...)) diff --git a/ent/providerordertoken_create.go b/ent/providerordertoken_create.go index 6e5348b0c..0501ae08c 100644 --- a/ent/providerordertoken_create.go +++ b/ent/providerordertoken_create.go @@ -13,7 +13,9 @@ import ( "entgo.io/ent/schema/field" "github.com/google/uuid" "github.com/paycrest/aggregator/ent/fiatcurrency" + "github.com/paycrest/aggregator/ent/providerassignmentrun" "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/token" "github.com/shopspring/decimal" @@ -175,6 +177,34 @@ func (_c *ProviderOrderTokenCreate) SetNetwork(v string) *ProviderOrderTokenCrea return _c } +// SetScore sets the "score" field. +func (_c *ProviderOrderTokenCreate) SetScore(v decimal.Decimal) *ProviderOrderTokenCreate { + _c.mutation.SetScore(v) + return _c +} + +// SetNillableScore sets the "score" field if the given value is not nil. +func (_c *ProviderOrderTokenCreate) SetNillableScore(v *decimal.Decimal) *ProviderOrderTokenCreate { + if v != nil { + _c.SetScore(*v) + } + return _c +} + +// SetLastOrderAssignedAt sets the "last_order_assigned_at" field. +func (_c *ProviderOrderTokenCreate) SetLastOrderAssignedAt(v time.Time) *ProviderOrderTokenCreate { + _c.mutation.SetLastOrderAssignedAt(v) + return _c +} + +// SetNillableLastOrderAssignedAt sets the "last_order_assigned_at" field if the given value is not nil. +func (_c *ProviderOrderTokenCreate) SetNillableLastOrderAssignedAt(v *time.Time) *ProviderOrderTokenCreate { + if v != nil { + _c.SetLastOrderAssignedAt(*v) + } + return _c +} + // SetProviderID sets the "provider" edge to the ProviderProfile entity by ID. func (_c *ProviderOrderTokenCreate) SetProviderID(id string) *ProviderOrderTokenCreate { _c.mutation.SetProviderID(id) @@ -208,6 +238,36 @@ func (_c *ProviderOrderTokenCreate) SetCurrency(v *FiatCurrency) *ProviderOrderT return _c.SetCurrencyID(v.ID) } +// AddScoreHistoryIDs adds the "score_histories" edge to the ProviderOrderTokenScoreHistory entity by IDs. +func (_c *ProviderOrderTokenCreate) AddScoreHistoryIDs(ids ...uuid.UUID) *ProviderOrderTokenCreate { + _c.mutation.AddScoreHistoryIDs(ids...) + return _c +} + +// AddScoreHistories adds the "score_histories" edges to the ProviderOrderTokenScoreHistory entity. +func (_c *ProviderOrderTokenCreate) AddScoreHistories(v ...*ProviderOrderTokenScoreHistory) *ProviderOrderTokenCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddScoreHistoryIDs(ids...) +} + +// AddAssignmentRunIDs adds the "assignment_runs" edge to the ProviderAssignmentRun entity by IDs. +func (_c *ProviderOrderTokenCreate) AddAssignmentRunIDs(ids ...uuid.UUID) *ProviderOrderTokenCreate { + _c.mutation.AddAssignmentRunIDs(ids...) + return _c +} + +// AddAssignmentRuns adds the "assignment_runs" edges to the ProviderAssignmentRun entity. +func (_c *ProviderOrderTokenCreate) AddAssignmentRuns(v ...*ProviderAssignmentRun) *ProviderOrderTokenCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddAssignmentRunIDs(ids...) +} + // Mutation returns the ProviderOrderTokenMutation object of the builder. func (_c *ProviderOrderTokenCreate) Mutation() *ProviderOrderTokenMutation { return _c.mutation @@ -251,6 +311,10 @@ func (_c *ProviderOrderTokenCreate) defaults() { v := providerordertoken.DefaultUpdatedAt() _c.mutation.SetUpdatedAt(v) } + if _, ok := _c.mutation.Score(); !ok { + v := providerordertoken.DefaultScore() + _c.mutation.SetScore(v) + } } // check runs all checks and user-defined validators on the builder. @@ -279,6 +343,9 @@ func (_c *ProviderOrderTokenCreate) check() error { if _, ok := _c.mutation.Network(); !ok { return &ValidationError{Name: "network", err: errors.New(`ent: missing required field "ProviderOrderToken.network"`)} } + if _, ok := _c.mutation.Score(); !ok { + return &ValidationError{Name: "score", err: errors.New(`ent: missing required field "ProviderOrderToken.score"`)} + } if len(_c.mutation.ProviderIDs()) == 0 { return &ValidationError{Name: "provider", err: errors.New(`ent: missing required edge "ProviderOrderToken.provider"`)} } @@ -371,6 +438,14 @@ func (_c *ProviderOrderTokenCreate) createSpec() (*ProviderOrderToken, *sqlgraph _spec.SetField(providerordertoken.FieldNetwork, field.TypeString, value) _node.Network = value } + if value, ok := _c.mutation.Score(); ok { + _spec.SetField(providerordertoken.FieldScore, field.TypeFloat64, value) + _node.Score = value + } + if value, ok := _c.mutation.LastOrderAssignedAt(); ok { + _spec.SetField(providerordertoken.FieldLastOrderAssignedAt, field.TypeTime, value) + _node.LastOrderAssignedAt = &value + } if nodes := _c.mutation.ProviderIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -422,6 +497,38 @@ func (_c *ProviderOrderTokenCreate) createSpec() (*ProviderOrderToken, *sqlgraph _node.fiat_currency_provider_order_tokens = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } + if nodes := _c.mutation.ScoreHistoriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.ScoreHistoriesTable, + Columns: []string{providerordertoken.ScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.AssignmentRunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.AssignmentRunsTable, + Columns: []string{providerordertoken.AssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } @@ -720,6 +827,42 @@ func (u *ProviderOrderTokenUpsert) UpdateNetwork() *ProviderOrderTokenUpsert { return u } +// SetScore sets the "score" field. +func (u *ProviderOrderTokenUpsert) SetScore(v decimal.Decimal) *ProviderOrderTokenUpsert { + u.Set(providerordertoken.FieldScore, v) + return u +} + +// UpdateScore sets the "score" field to the value that was provided on create. +func (u *ProviderOrderTokenUpsert) UpdateScore() *ProviderOrderTokenUpsert { + u.SetExcluded(providerordertoken.FieldScore) + return u +} + +// AddScore adds v to the "score" field. +func (u *ProviderOrderTokenUpsert) AddScore(v decimal.Decimal) *ProviderOrderTokenUpsert { + u.Add(providerordertoken.FieldScore, v) + return u +} + +// SetLastOrderAssignedAt sets the "last_order_assigned_at" field. +func (u *ProviderOrderTokenUpsert) SetLastOrderAssignedAt(v time.Time) *ProviderOrderTokenUpsert { + u.Set(providerordertoken.FieldLastOrderAssignedAt, v) + return u +} + +// UpdateLastOrderAssignedAt sets the "last_order_assigned_at" field to the value that was provided on create. +func (u *ProviderOrderTokenUpsert) UpdateLastOrderAssignedAt() *ProviderOrderTokenUpsert { + u.SetExcluded(providerordertoken.FieldLastOrderAssignedAt) + return u +} + +// ClearLastOrderAssignedAt clears the value of the "last_order_assigned_at" field. +func (u *ProviderOrderTokenUpsert) ClearLastOrderAssignedAt() *ProviderOrderTokenUpsert { + u.SetNull(providerordertoken.FieldLastOrderAssignedAt) + return u +} + // UpdateNewValues updates the mutable fields using the new values that were set on create. // Using this option is equivalent to using: // @@ -1052,6 +1195,48 @@ func (u *ProviderOrderTokenUpsertOne) UpdateNetwork() *ProviderOrderTokenUpsertO }) } +// SetScore sets the "score" field. +func (u *ProviderOrderTokenUpsertOne) SetScore(v decimal.Decimal) *ProviderOrderTokenUpsertOne { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.SetScore(v) + }) +} + +// AddScore adds v to the "score" field. +func (u *ProviderOrderTokenUpsertOne) AddScore(v decimal.Decimal) *ProviderOrderTokenUpsertOne { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.AddScore(v) + }) +} + +// UpdateScore sets the "score" field to the value that was provided on create. +func (u *ProviderOrderTokenUpsertOne) UpdateScore() *ProviderOrderTokenUpsertOne { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.UpdateScore() + }) +} + +// SetLastOrderAssignedAt sets the "last_order_assigned_at" field. +func (u *ProviderOrderTokenUpsertOne) SetLastOrderAssignedAt(v time.Time) *ProviderOrderTokenUpsertOne { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.SetLastOrderAssignedAt(v) + }) +} + +// UpdateLastOrderAssignedAt sets the "last_order_assigned_at" field to the value that was provided on create. +func (u *ProviderOrderTokenUpsertOne) UpdateLastOrderAssignedAt() *ProviderOrderTokenUpsertOne { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.UpdateLastOrderAssignedAt() + }) +} + +// ClearLastOrderAssignedAt clears the value of the "last_order_assigned_at" field. +func (u *ProviderOrderTokenUpsertOne) ClearLastOrderAssignedAt() *ProviderOrderTokenUpsertOne { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.ClearLastOrderAssignedAt() + }) +} + // Exec executes the query. func (u *ProviderOrderTokenUpsertOne) Exec(ctx context.Context) error { if len(u.create.conflict) == 0 { @@ -1550,6 +1735,48 @@ func (u *ProviderOrderTokenUpsertBulk) UpdateNetwork() *ProviderOrderTokenUpsert }) } +// SetScore sets the "score" field. +func (u *ProviderOrderTokenUpsertBulk) SetScore(v decimal.Decimal) *ProviderOrderTokenUpsertBulk { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.SetScore(v) + }) +} + +// AddScore adds v to the "score" field. +func (u *ProviderOrderTokenUpsertBulk) AddScore(v decimal.Decimal) *ProviderOrderTokenUpsertBulk { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.AddScore(v) + }) +} + +// UpdateScore sets the "score" field to the value that was provided on create. +func (u *ProviderOrderTokenUpsertBulk) UpdateScore() *ProviderOrderTokenUpsertBulk { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.UpdateScore() + }) +} + +// SetLastOrderAssignedAt sets the "last_order_assigned_at" field. +func (u *ProviderOrderTokenUpsertBulk) SetLastOrderAssignedAt(v time.Time) *ProviderOrderTokenUpsertBulk { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.SetLastOrderAssignedAt(v) + }) +} + +// UpdateLastOrderAssignedAt sets the "last_order_assigned_at" field to the value that was provided on create. +func (u *ProviderOrderTokenUpsertBulk) UpdateLastOrderAssignedAt() *ProviderOrderTokenUpsertBulk { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.UpdateLastOrderAssignedAt() + }) +} + +// ClearLastOrderAssignedAt clears the value of the "last_order_assigned_at" field. +func (u *ProviderOrderTokenUpsertBulk) ClearLastOrderAssignedAt() *ProviderOrderTokenUpsertBulk { + return u.Update(func(s *ProviderOrderTokenUpsert) { + s.ClearLastOrderAssignedAt() + }) +} + // Exec executes the query. func (u *ProviderOrderTokenUpsertBulk) Exec(ctx context.Context) error { if u.create.err != nil { diff --git a/ent/providerordertoken_query.go b/ent/providerordertoken_query.go index 820c655bc..05d73a28c 100644 --- a/ent/providerordertoken_query.go +++ b/ent/providerordertoken_query.go @@ -4,6 +4,7 @@ package ent import ( "context" + "database/sql/driver" "fmt" "math" @@ -14,7 +15,9 @@ import ( "github.com/google/uuid" "github.com/paycrest/aggregator/ent/fiatcurrency" "github.com/paycrest/aggregator/ent/predicate" + "github.com/paycrest/aggregator/ent/providerassignmentrun" "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/token" ) @@ -22,14 +25,16 @@ import ( // ProviderOrderTokenQuery is the builder for querying ProviderOrderToken entities. type ProviderOrderTokenQuery struct { config - ctx *QueryContext - order []providerordertoken.OrderOption - inters []Interceptor - predicates []predicate.ProviderOrderToken - withProvider *ProviderProfileQuery - withToken *TokenQuery - withCurrency *FiatCurrencyQuery - withFKs bool + ctx *QueryContext + order []providerordertoken.OrderOption + inters []Interceptor + predicates []predicate.ProviderOrderToken + withProvider *ProviderProfileQuery + withToken *TokenQuery + withCurrency *FiatCurrencyQuery + withScoreHistories *ProviderOrderTokenScoreHistoryQuery + withAssignmentRuns *ProviderAssignmentRunQuery + withFKs bool // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -132,6 +137,50 @@ func (_q *ProviderOrderTokenQuery) QueryCurrency() *FiatCurrencyQuery { return query } +// QueryScoreHistories chains the current query on the "score_histories" edge. +func (_q *ProviderOrderTokenQuery) QueryScoreHistories() *ProviderOrderTokenScoreHistoryQuery { + query := (&ProviderOrderTokenScoreHistoryClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(providerordertoken.Table, providerordertoken.FieldID, selector), + sqlgraph.To(providerordertokenscorehistory.Table, providerordertokenscorehistory.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, providerordertoken.ScoreHistoriesTable, providerordertoken.ScoreHistoriesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryAssignmentRuns chains the current query on the "assignment_runs" edge. +func (_q *ProviderOrderTokenQuery) QueryAssignmentRuns() *ProviderAssignmentRunQuery { + query := (&ProviderAssignmentRunClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(providerordertoken.Table, providerordertoken.FieldID, selector), + sqlgraph.To(providerassignmentrun.Table, providerassignmentrun.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, providerordertoken.AssignmentRunsTable, providerordertoken.AssignmentRunsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first ProviderOrderToken entity from the query. // Returns a *NotFoundError when no ProviderOrderToken was found. func (_q *ProviderOrderTokenQuery) First(ctx context.Context) (*ProviderOrderToken, error) { @@ -319,14 +368,16 @@ func (_q *ProviderOrderTokenQuery) Clone() *ProviderOrderTokenQuery { return nil } return &ProviderOrderTokenQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]providerordertoken.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.ProviderOrderToken{}, _q.predicates...), - withProvider: _q.withProvider.Clone(), - withToken: _q.withToken.Clone(), - withCurrency: _q.withCurrency.Clone(), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]providerordertoken.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ProviderOrderToken{}, _q.predicates...), + withProvider: _q.withProvider.Clone(), + withToken: _q.withToken.Clone(), + withCurrency: _q.withCurrency.Clone(), + withScoreHistories: _q.withScoreHistories.Clone(), + withAssignmentRuns: _q.withAssignmentRuns.Clone(), // clone intermediate query. sql: _q.sql.Clone(), path: _q.path, @@ -366,6 +417,28 @@ func (_q *ProviderOrderTokenQuery) WithCurrency(opts ...func(*FiatCurrencyQuery) return _q } +// WithScoreHistories tells the query-builder to eager-load the nodes that are connected to +// the "score_histories" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ProviderOrderTokenQuery) WithScoreHistories(opts ...func(*ProviderOrderTokenScoreHistoryQuery)) *ProviderOrderTokenQuery { + query := (&ProviderOrderTokenScoreHistoryClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withScoreHistories = query + return _q +} + +// WithAssignmentRuns tells the query-builder to eager-load the nodes that are connected to +// the "assignment_runs" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ProviderOrderTokenQuery) WithAssignmentRuns(opts ...func(*ProviderAssignmentRunQuery)) *ProviderOrderTokenQuery { + query := (&ProviderAssignmentRunClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withAssignmentRuns = query + return _q +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -445,10 +518,12 @@ func (_q *ProviderOrderTokenQuery) sqlAll(ctx context.Context, hooks ...queryHoo nodes = []*ProviderOrderToken{} withFKs = _q.withFKs _spec = _q.querySpec() - loadedTypes = [3]bool{ + loadedTypes = [5]bool{ _q.withProvider != nil, _q.withToken != nil, _q.withCurrency != nil, + _q.withScoreHistories != nil, + _q.withAssignmentRuns != nil, } ) if _q.withProvider != nil || _q.withToken != nil || _q.withCurrency != nil { @@ -493,6 +568,24 @@ func (_q *ProviderOrderTokenQuery) sqlAll(ctx context.Context, hooks ...queryHoo return nil, err } } + if query := _q.withScoreHistories; query != nil { + if err := _q.loadScoreHistories(ctx, query, nodes, + func(n *ProviderOrderToken) { n.Edges.ScoreHistories = []*ProviderOrderTokenScoreHistory{} }, + func(n *ProviderOrderToken, e *ProviderOrderTokenScoreHistory) { + n.Edges.ScoreHistories = append(n.Edges.ScoreHistories, e) + }); err != nil { + return nil, err + } + } + if query := _q.withAssignmentRuns; query != nil { + if err := _q.loadAssignmentRuns(ctx, query, nodes, + func(n *ProviderOrderToken) { n.Edges.AssignmentRuns = []*ProviderAssignmentRun{} }, + func(n *ProviderOrderToken, e *ProviderAssignmentRun) { + n.Edges.AssignmentRuns = append(n.Edges.AssignmentRuns, e) + }); err != nil { + return nil, err + } + } return nodes, nil } @@ -592,6 +685,68 @@ func (_q *ProviderOrderTokenQuery) loadCurrency(ctx context.Context, query *Fiat } return nil } +func (_q *ProviderOrderTokenQuery) loadScoreHistories(ctx context.Context, query *ProviderOrderTokenScoreHistoryQuery, nodes []*ProviderOrderToken, init func(*ProviderOrderToken), assign func(*ProviderOrderToken, *ProviderOrderTokenScoreHistory)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*ProviderOrderToken) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.withFKs = true + query.Where(predicate.ProviderOrderTokenScoreHistory(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(providerordertoken.ScoreHistoriesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.provider_order_token_score_histories + if fk == nil { + return fmt.Errorf(`foreign-key "provider_order_token_score_histories" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "provider_order_token_score_histories" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *ProviderOrderTokenQuery) loadAssignmentRuns(ctx context.Context, query *ProviderAssignmentRunQuery, nodes []*ProviderOrderToken, init func(*ProviderOrderToken), assign func(*ProviderOrderToken, *ProviderAssignmentRun)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*ProviderOrderToken) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.withFKs = true + query.Where(predicate.ProviderAssignmentRun(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(providerordertoken.AssignmentRunsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.provider_order_token_assignment_runs + if fk == nil { + return fmt.Errorf(`foreign-key "provider_order_token_assignment_runs" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "provider_order_token_assignment_runs" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} func (_q *ProviderOrderTokenQuery) sqlCount(ctx context.Context) (int, error) { _spec := _q.querySpec() diff --git a/ent/providerordertoken_update.go b/ent/providerordertoken_update.go index 5cb2e32f7..22e0d5d43 100644 --- a/ent/providerordertoken_update.go +++ b/ent/providerordertoken_update.go @@ -14,7 +14,9 @@ import ( "github.com/google/uuid" "github.com/paycrest/aggregator/ent/fiatcurrency" "github.com/paycrest/aggregator/ent/predicate" + "github.com/paycrest/aggregator/ent/providerassignmentrun" "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/token" "github.com/shopspring/decimal" @@ -306,6 +308,47 @@ func (_u *ProviderOrderTokenUpdate) SetNillableNetwork(v *string) *ProviderOrder return _u } +// SetScore sets the "score" field. +func (_u *ProviderOrderTokenUpdate) SetScore(v decimal.Decimal) *ProviderOrderTokenUpdate { + _u.mutation.ResetScore() + _u.mutation.SetScore(v) + return _u +} + +// SetNillableScore sets the "score" field if the given value is not nil. +func (_u *ProviderOrderTokenUpdate) SetNillableScore(v *decimal.Decimal) *ProviderOrderTokenUpdate { + if v != nil { + _u.SetScore(*v) + } + return _u +} + +// AddScore adds value to the "score" field. +func (_u *ProviderOrderTokenUpdate) AddScore(v decimal.Decimal) *ProviderOrderTokenUpdate { + _u.mutation.AddScore(v) + return _u +} + +// SetLastOrderAssignedAt sets the "last_order_assigned_at" field. +func (_u *ProviderOrderTokenUpdate) SetLastOrderAssignedAt(v time.Time) *ProviderOrderTokenUpdate { + _u.mutation.SetLastOrderAssignedAt(v) + return _u +} + +// SetNillableLastOrderAssignedAt sets the "last_order_assigned_at" field if the given value is not nil. +func (_u *ProviderOrderTokenUpdate) SetNillableLastOrderAssignedAt(v *time.Time) *ProviderOrderTokenUpdate { + if v != nil { + _u.SetLastOrderAssignedAt(*v) + } + return _u +} + +// ClearLastOrderAssignedAt clears the value of the "last_order_assigned_at" field. +func (_u *ProviderOrderTokenUpdate) ClearLastOrderAssignedAt() *ProviderOrderTokenUpdate { + _u.mutation.ClearLastOrderAssignedAt() + return _u +} + // SetProviderID sets the "provider" edge to the ProviderProfile entity by ID. func (_u *ProviderOrderTokenUpdate) SetProviderID(id string) *ProviderOrderTokenUpdate { _u.mutation.SetProviderID(id) @@ -339,6 +382,36 @@ func (_u *ProviderOrderTokenUpdate) SetCurrency(v *FiatCurrency) *ProviderOrderT return _u.SetCurrencyID(v.ID) } +// AddScoreHistoryIDs adds the "score_histories" edge to the ProviderOrderTokenScoreHistory entity by IDs. +func (_u *ProviderOrderTokenUpdate) AddScoreHistoryIDs(ids ...uuid.UUID) *ProviderOrderTokenUpdate { + _u.mutation.AddScoreHistoryIDs(ids...) + return _u +} + +// AddScoreHistories adds the "score_histories" edges to the ProviderOrderTokenScoreHistory entity. +func (_u *ProviderOrderTokenUpdate) AddScoreHistories(v ...*ProviderOrderTokenScoreHistory) *ProviderOrderTokenUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddScoreHistoryIDs(ids...) +} + +// AddAssignmentRunIDs adds the "assignment_runs" edge to the ProviderAssignmentRun entity by IDs. +func (_u *ProviderOrderTokenUpdate) AddAssignmentRunIDs(ids ...uuid.UUID) *ProviderOrderTokenUpdate { + _u.mutation.AddAssignmentRunIDs(ids...) + return _u +} + +// AddAssignmentRuns adds the "assignment_runs" edges to the ProviderAssignmentRun entity. +func (_u *ProviderOrderTokenUpdate) AddAssignmentRuns(v ...*ProviderAssignmentRun) *ProviderOrderTokenUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddAssignmentRunIDs(ids...) +} + // Mutation returns the ProviderOrderTokenMutation object of the builder. func (_u *ProviderOrderTokenUpdate) Mutation() *ProviderOrderTokenMutation { return _u.mutation @@ -362,6 +435,48 @@ func (_u *ProviderOrderTokenUpdate) ClearCurrency() *ProviderOrderTokenUpdate { return _u } +// ClearScoreHistories clears all "score_histories" edges to the ProviderOrderTokenScoreHistory entity. +func (_u *ProviderOrderTokenUpdate) ClearScoreHistories() *ProviderOrderTokenUpdate { + _u.mutation.ClearScoreHistories() + return _u +} + +// RemoveScoreHistoryIDs removes the "score_histories" edge to ProviderOrderTokenScoreHistory entities by IDs. +func (_u *ProviderOrderTokenUpdate) RemoveScoreHistoryIDs(ids ...uuid.UUID) *ProviderOrderTokenUpdate { + _u.mutation.RemoveScoreHistoryIDs(ids...) + return _u +} + +// RemoveScoreHistories removes "score_histories" edges to ProviderOrderTokenScoreHistory entities. +func (_u *ProviderOrderTokenUpdate) RemoveScoreHistories(v ...*ProviderOrderTokenScoreHistory) *ProviderOrderTokenUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveScoreHistoryIDs(ids...) +} + +// ClearAssignmentRuns clears all "assignment_runs" edges to the ProviderAssignmentRun entity. +func (_u *ProviderOrderTokenUpdate) ClearAssignmentRuns() *ProviderOrderTokenUpdate { + _u.mutation.ClearAssignmentRuns() + return _u +} + +// RemoveAssignmentRunIDs removes the "assignment_runs" edge to ProviderAssignmentRun entities by IDs. +func (_u *ProviderOrderTokenUpdate) RemoveAssignmentRunIDs(ids ...uuid.UUID) *ProviderOrderTokenUpdate { + _u.mutation.RemoveAssignmentRunIDs(ids...) + return _u +} + +// RemoveAssignmentRuns removes "assignment_runs" edges to ProviderAssignmentRun entities. +func (_u *ProviderOrderTokenUpdate) RemoveAssignmentRuns(v ...*ProviderAssignmentRun) *ProviderOrderTokenUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveAssignmentRunIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (_u *ProviderOrderTokenUpdate) Save(ctx context.Context) (int, error) { _u.defaults() @@ -508,6 +623,18 @@ func (_u *ProviderOrderTokenUpdate) sqlSave(ctx context.Context) (_node int, err if value, ok := _u.mutation.Network(); ok { _spec.SetField(providerordertoken.FieldNetwork, field.TypeString, value) } + if value, ok := _u.mutation.Score(); ok { + _spec.SetField(providerordertoken.FieldScore, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedScore(); ok { + _spec.AddField(providerordertoken.FieldScore, field.TypeFloat64, value) + } + if value, ok := _u.mutation.LastOrderAssignedAt(); ok { + _spec.SetField(providerordertoken.FieldLastOrderAssignedAt, field.TypeTime, value) + } + if _u.mutation.LastOrderAssignedAtCleared() { + _spec.ClearField(providerordertoken.FieldLastOrderAssignedAt, field.TypeTime) + } if _u.mutation.ProviderCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -595,6 +722,96 @@ func (_u *ProviderOrderTokenUpdate) sqlSave(ctx context.Context) (_node int, err } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.ScoreHistoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.ScoreHistoriesTable, + Columns: []string{providerordertoken.ScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedScoreHistoriesIDs(); len(nodes) > 0 && !_u.mutation.ScoreHistoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.ScoreHistoriesTable, + Columns: []string{providerordertoken.ScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ScoreHistoriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.ScoreHistoriesTable, + Columns: []string{providerordertoken.ScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.AssignmentRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.AssignmentRunsTable, + Columns: []string{providerordertoken.AssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedAssignmentRunsIDs(); len(nodes) > 0 && !_u.mutation.AssignmentRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.AssignmentRunsTable, + Columns: []string{providerordertoken.AssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.AssignmentRunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.AssignmentRunsTable, + Columns: []string{providerordertoken.AssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{providerordertoken.Label} @@ -888,6 +1105,47 @@ func (_u *ProviderOrderTokenUpdateOne) SetNillableNetwork(v *string) *ProviderOr return _u } +// SetScore sets the "score" field. +func (_u *ProviderOrderTokenUpdateOne) SetScore(v decimal.Decimal) *ProviderOrderTokenUpdateOne { + _u.mutation.ResetScore() + _u.mutation.SetScore(v) + return _u +} + +// SetNillableScore sets the "score" field if the given value is not nil. +func (_u *ProviderOrderTokenUpdateOne) SetNillableScore(v *decimal.Decimal) *ProviderOrderTokenUpdateOne { + if v != nil { + _u.SetScore(*v) + } + return _u +} + +// AddScore adds value to the "score" field. +func (_u *ProviderOrderTokenUpdateOne) AddScore(v decimal.Decimal) *ProviderOrderTokenUpdateOne { + _u.mutation.AddScore(v) + return _u +} + +// SetLastOrderAssignedAt sets the "last_order_assigned_at" field. +func (_u *ProviderOrderTokenUpdateOne) SetLastOrderAssignedAt(v time.Time) *ProviderOrderTokenUpdateOne { + _u.mutation.SetLastOrderAssignedAt(v) + return _u +} + +// SetNillableLastOrderAssignedAt sets the "last_order_assigned_at" field if the given value is not nil. +func (_u *ProviderOrderTokenUpdateOne) SetNillableLastOrderAssignedAt(v *time.Time) *ProviderOrderTokenUpdateOne { + if v != nil { + _u.SetLastOrderAssignedAt(*v) + } + return _u +} + +// ClearLastOrderAssignedAt clears the value of the "last_order_assigned_at" field. +func (_u *ProviderOrderTokenUpdateOne) ClearLastOrderAssignedAt() *ProviderOrderTokenUpdateOne { + _u.mutation.ClearLastOrderAssignedAt() + return _u +} + // SetProviderID sets the "provider" edge to the ProviderProfile entity by ID. func (_u *ProviderOrderTokenUpdateOne) SetProviderID(id string) *ProviderOrderTokenUpdateOne { _u.mutation.SetProviderID(id) @@ -921,6 +1179,36 @@ func (_u *ProviderOrderTokenUpdateOne) SetCurrency(v *FiatCurrency) *ProviderOrd return _u.SetCurrencyID(v.ID) } +// AddScoreHistoryIDs adds the "score_histories" edge to the ProviderOrderTokenScoreHistory entity by IDs. +func (_u *ProviderOrderTokenUpdateOne) AddScoreHistoryIDs(ids ...uuid.UUID) *ProviderOrderTokenUpdateOne { + _u.mutation.AddScoreHistoryIDs(ids...) + return _u +} + +// AddScoreHistories adds the "score_histories" edges to the ProviderOrderTokenScoreHistory entity. +func (_u *ProviderOrderTokenUpdateOne) AddScoreHistories(v ...*ProviderOrderTokenScoreHistory) *ProviderOrderTokenUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddScoreHistoryIDs(ids...) +} + +// AddAssignmentRunIDs adds the "assignment_runs" edge to the ProviderAssignmentRun entity by IDs. +func (_u *ProviderOrderTokenUpdateOne) AddAssignmentRunIDs(ids ...uuid.UUID) *ProviderOrderTokenUpdateOne { + _u.mutation.AddAssignmentRunIDs(ids...) + return _u +} + +// AddAssignmentRuns adds the "assignment_runs" edges to the ProviderAssignmentRun entity. +func (_u *ProviderOrderTokenUpdateOne) AddAssignmentRuns(v ...*ProviderAssignmentRun) *ProviderOrderTokenUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddAssignmentRunIDs(ids...) +} + // Mutation returns the ProviderOrderTokenMutation object of the builder. func (_u *ProviderOrderTokenUpdateOne) Mutation() *ProviderOrderTokenMutation { return _u.mutation @@ -944,6 +1232,48 @@ func (_u *ProviderOrderTokenUpdateOne) ClearCurrency() *ProviderOrderTokenUpdate return _u } +// ClearScoreHistories clears all "score_histories" edges to the ProviderOrderTokenScoreHistory entity. +func (_u *ProviderOrderTokenUpdateOne) ClearScoreHistories() *ProviderOrderTokenUpdateOne { + _u.mutation.ClearScoreHistories() + return _u +} + +// RemoveScoreHistoryIDs removes the "score_histories" edge to ProviderOrderTokenScoreHistory entities by IDs. +func (_u *ProviderOrderTokenUpdateOne) RemoveScoreHistoryIDs(ids ...uuid.UUID) *ProviderOrderTokenUpdateOne { + _u.mutation.RemoveScoreHistoryIDs(ids...) + return _u +} + +// RemoveScoreHistories removes "score_histories" edges to ProviderOrderTokenScoreHistory entities. +func (_u *ProviderOrderTokenUpdateOne) RemoveScoreHistories(v ...*ProviderOrderTokenScoreHistory) *ProviderOrderTokenUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveScoreHistoryIDs(ids...) +} + +// ClearAssignmentRuns clears all "assignment_runs" edges to the ProviderAssignmentRun entity. +func (_u *ProviderOrderTokenUpdateOne) ClearAssignmentRuns() *ProviderOrderTokenUpdateOne { + _u.mutation.ClearAssignmentRuns() + return _u +} + +// RemoveAssignmentRunIDs removes the "assignment_runs" edge to ProviderAssignmentRun entities by IDs. +func (_u *ProviderOrderTokenUpdateOne) RemoveAssignmentRunIDs(ids ...uuid.UUID) *ProviderOrderTokenUpdateOne { + _u.mutation.RemoveAssignmentRunIDs(ids...) + return _u +} + +// RemoveAssignmentRuns removes "assignment_runs" edges to ProviderAssignmentRun entities. +func (_u *ProviderOrderTokenUpdateOne) RemoveAssignmentRuns(v ...*ProviderAssignmentRun) *ProviderOrderTokenUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveAssignmentRunIDs(ids...) +} + // Where appends a list predicates to the ProviderOrderTokenUpdate builder. func (_u *ProviderOrderTokenUpdateOne) Where(ps ...predicate.ProviderOrderToken) *ProviderOrderTokenUpdateOne { _u.mutation.Where(ps...) @@ -1120,6 +1450,18 @@ func (_u *ProviderOrderTokenUpdateOne) sqlSave(ctx context.Context) (_node *Prov if value, ok := _u.mutation.Network(); ok { _spec.SetField(providerordertoken.FieldNetwork, field.TypeString, value) } + if value, ok := _u.mutation.Score(); ok { + _spec.SetField(providerordertoken.FieldScore, field.TypeFloat64, value) + } + if value, ok := _u.mutation.AddedScore(); ok { + _spec.AddField(providerordertoken.FieldScore, field.TypeFloat64, value) + } + if value, ok := _u.mutation.LastOrderAssignedAt(); ok { + _spec.SetField(providerordertoken.FieldLastOrderAssignedAt, field.TypeTime, value) + } + if _u.mutation.LastOrderAssignedAtCleared() { + _spec.ClearField(providerordertoken.FieldLastOrderAssignedAt, field.TypeTime) + } if _u.mutation.ProviderCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -1207,6 +1549,96 @@ func (_u *ProviderOrderTokenUpdateOne) sqlSave(ctx context.Context) (_node *Prov } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.ScoreHistoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.ScoreHistoriesTable, + Columns: []string{providerordertoken.ScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedScoreHistoriesIDs(); len(nodes) > 0 && !_u.mutation.ScoreHistoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.ScoreHistoriesTable, + Columns: []string{providerordertoken.ScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ScoreHistoriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.ScoreHistoriesTable, + Columns: []string{providerordertoken.ScoreHistoriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.AssignmentRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.AssignmentRunsTable, + Columns: []string{providerordertoken.AssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedAssignmentRunsIDs(); len(nodes) > 0 && !_u.mutation.AssignmentRunsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.AssignmentRunsTable, + Columns: []string{providerordertoken.AssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.AssignmentRunsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: providerordertoken.AssignmentRunsTable, + Columns: []string{providerordertoken.AssignmentRunsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerassignmentrun.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &ProviderOrderToken{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/ent/providerordertokenscorehistory.go b/ent/providerordertokenscorehistory.go new file mode 100644 index 000000000..8d458a171 --- /dev/null +++ b/ent/providerordertokenscorehistory.go @@ -0,0 +1,211 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" + "github.com/shopspring/decimal" +) + +// ProviderOrderTokenScoreHistory is the model entity for the ProviderOrderTokenScoreHistory schema. +type ProviderOrderTokenScoreHistory struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // EventType holds the value of the "event_type" field. + EventType string `json:"event_type,omitempty"` + // Delta holds the value of the "delta" field. + Delta decimal.Decimal `json:"delta,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ProviderOrderTokenScoreHistoryQuery when eager-loading is set. + Edges ProviderOrderTokenScoreHistoryEdges `json:"edges"` + payment_order_provider_order_token_score_histories *uuid.UUID + provider_order_token_score_histories *int + selectValues sql.SelectValues +} + +// ProviderOrderTokenScoreHistoryEdges holds the relations/edges for other nodes in the graph. +type ProviderOrderTokenScoreHistoryEdges struct { + // PaymentOrder holds the value of the payment_order edge. + PaymentOrder *PaymentOrder `json:"payment_order,omitempty"` + // ProviderOrderToken holds the value of the provider_order_token edge. + ProviderOrderToken *ProviderOrderToken `json:"provider_order_token,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// PaymentOrderOrErr returns the PaymentOrder value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ProviderOrderTokenScoreHistoryEdges) PaymentOrderOrErr() (*PaymentOrder, error) { + if e.PaymentOrder != nil { + return e.PaymentOrder, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: paymentorder.Label} + } + return nil, &NotLoadedError{edge: "payment_order"} +} + +// ProviderOrderTokenOrErr returns the ProviderOrderToken value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ProviderOrderTokenScoreHistoryEdges) ProviderOrderTokenOrErr() (*ProviderOrderToken, error) { + if e.ProviderOrderToken != nil { + return e.ProviderOrderToken, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: providerordertoken.Label} + } + return nil, &NotLoadedError{edge: "provider_order_token"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ProviderOrderTokenScoreHistory) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case providerordertokenscorehistory.FieldDelta: + values[i] = new(decimal.Decimal) + case providerordertokenscorehistory.FieldEventType: + values[i] = new(sql.NullString) + case providerordertokenscorehistory.FieldCreatedAt, providerordertokenscorehistory.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case providerordertokenscorehistory.FieldID: + values[i] = new(uuid.UUID) + case providerordertokenscorehistory.ForeignKeys[0]: // payment_order_provider_order_token_score_histories + values[i] = &sql.NullScanner{S: new(uuid.UUID)} + case providerordertokenscorehistory.ForeignKeys[1]: // provider_order_token_score_histories + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ProviderOrderTokenScoreHistory fields. +func (_m *ProviderOrderTokenScoreHistory) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case providerordertokenscorehistory.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case providerordertokenscorehistory.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case providerordertokenscorehistory.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + case providerordertokenscorehistory.FieldEventType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field event_type", values[i]) + } else if value.Valid { + _m.EventType = value.String + } + case providerordertokenscorehistory.FieldDelta: + if value, ok := values[i].(*decimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field delta", values[i]) + } else if value != nil { + _m.Delta = *value + } + case providerordertokenscorehistory.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field payment_order_provider_order_token_score_histories", values[i]) + } else if value.Valid { + _m.payment_order_provider_order_token_score_histories = new(uuid.UUID) + *_m.payment_order_provider_order_token_score_histories = *value.S.(*uuid.UUID) + } + case providerordertokenscorehistory.ForeignKeys[1]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field provider_order_token_score_histories", value) + } else if value.Valid { + _m.provider_order_token_score_histories = new(int) + *_m.provider_order_token_score_histories = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ProviderOrderTokenScoreHistory. +// This includes values selected through modifiers, order, etc. +func (_m *ProviderOrderTokenScoreHistory) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryPaymentOrder queries the "payment_order" edge of the ProviderOrderTokenScoreHistory entity. +func (_m *ProviderOrderTokenScoreHistory) QueryPaymentOrder() *PaymentOrderQuery { + return NewProviderOrderTokenScoreHistoryClient(_m.config).QueryPaymentOrder(_m) +} + +// QueryProviderOrderToken queries the "provider_order_token" edge of the ProviderOrderTokenScoreHistory entity. +func (_m *ProviderOrderTokenScoreHistory) QueryProviderOrderToken() *ProviderOrderTokenQuery { + return NewProviderOrderTokenScoreHistoryClient(_m.config).QueryProviderOrderToken(_m) +} + +// Update returns a builder for updating this ProviderOrderTokenScoreHistory. +// Note that you need to call ProviderOrderTokenScoreHistory.Unwrap() before calling this method if this ProviderOrderTokenScoreHistory +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ProviderOrderTokenScoreHistory) Update() *ProviderOrderTokenScoreHistoryUpdateOne { + return NewProviderOrderTokenScoreHistoryClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ProviderOrderTokenScoreHistory entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *ProviderOrderTokenScoreHistory) Unwrap() *ProviderOrderTokenScoreHistory { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: ProviderOrderTokenScoreHistory is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ProviderOrderTokenScoreHistory) String() string { + var builder strings.Builder + builder.WriteString("ProviderOrderTokenScoreHistory(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("event_type=") + builder.WriteString(_m.EventType) + builder.WriteString(", ") + builder.WriteString("delta=") + builder.WriteString(fmt.Sprintf("%v", _m.Delta)) + builder.WriteByte(')') + return builder.String() +} + +// ProviderOrderTokenScoreHistories is a parsable slice of ProviderOrderTokenScoreHistory. +type ProviderOrderTokenScoreHistories []*ProviderOrderTokenScoreHistory diff --git a/ent/providerordertokenscorehistory/providerordertokenscorehistory.go b/ent/providerordertokenscorehistory/providerordertokenscorehistory.go new file mode 100644 index 000000000..e20a07bb9 --- /dev/null +++ b/ent/providerordertokenscorehistory/providerordertokenscorehistory.go @@ -0,0 +1,153 @@ +// Code generated by ent, DO NOT EDIT. + +package providerordertokenscorehistory + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the providerordertokenscorehistory type in the database. + Label = "provider_order_token_score_history" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // FieldEventType holds the string denoting the event_type field in the database. + FieldEventType = "event_type" + // FieldDelta holds the string denoting the delta field in the database. + FieldDelta = "delta" + // EdgePaymentOrder holds the string denoting the payment_order edge name in mutations. + EdgePaymentOrder = "payment_order" + // EdgeProviderOrderToken holds the string denoting the provider_order_token edge name in mutations. + EdgeProviderOrderToken = "provider_order_token" + // Table holds the table name of the providerordertokenscorehistory in the database. + Table = "provider_order_token_score_histories" + // PaymentOrderTable is the table that holds the payment_order relation/edge. + PaymentOrderTable = "provider_order_token_score_histories" + // PaymentOrderInverseTable is the table name for the PaymentOrder entity. + // It exists in this package in order to avoid circular dependency with the "paymentorder" package. + PaymentOrderInverseTable = "payment_orders" + // PaymentOrderColumn is the table column denoting the payment_order relation/edge. + PaymentOrderColumn = "payment_order_provider_order_token_score_histories" + // ProviderOrderTokenTable is the table that holds the provider_order_token relation/edge. + ProviderOrderTokenTable = "provider_order_token_score_histories" + // ProviderOrderTokenInverseTable is the table name for the ProviderOrderToken entity. + // It exists in this package in order to avoid circular dependency with the "providerordertoken" package. + ProviderOrderTokenInverseTable = "provider_order_tokens" + // ProviderOrderTokenColumn is the table column denoting the provider_order_token relation/edge. + ProviderOrderTokenColumn = "provider_order_token_score_histories" +) + +// Columns holds all SQL columns for providerordertokenscorehistory fields. +var Columns = []string{ + FieldID, + FieldCreatedAt, + FieldUpdatedAt, + FieldEventType, + FieldDelta, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "provider_order_token_score_histories" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "payment_order_provider_order_token_score_histories", + "provider_order_token_score_histories", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} + +// Note that the variables below are initialized by the runtime +// package on the initialization of the application. Therefore, +// it should be imported in the main as follows: +// +// import _ "github.com/paycrest/aggregator/ent/runtime" +var ( + Hooks [1]ent.Hook + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time + // EventTypeValidator is a validator for the "event_type" field. It is called by the builders before save. + EventTypeValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// OrderOption defines the ordering options for the ProviderOrderTokenScoreHistory queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByEventType orders the results by the event_type field. +func ByEventType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEventType, opts...).ToFunc() +} + +// ByDelta orders the results by the delta field. +func ByDelta(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDelta, opts...).ToFunc() +} + +// ByPaymentOrderField orders the results by payment_order field. +func ByPaymentOrderField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newPaymentOrderStep(), sql.OrderByField(field, opts...)) + } +} + +// ByProviderOrderTokenField orders the results by provider_order_token field. +func ByProviderOrderTokenField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newProviderOrderTokenStep(), sql.OrderByField(field, opts...)) + } +} +func newPaymentOrderStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(PaymentOrderInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, PaymentOrderTable, PaymentOrderColumn), + ) +} +func newProviderOrderTokenStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ProviderOrderTokenInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ProviderOrderTokenTable, ProviderOrderTokenColumn), + ) +} diff --git a/ent/providerordertokenscorehistory/where.go b/ent/providerordertokenscorehistory/where.go new file mode 100644 index 000000000..322350181 --- /dev/null +++ b/ent/providerordertokenscorehistory/where.go @@ -0,0 +1,324 @@ +// Code generated by ent, DO NOT EDIT. + +package providerordertokenscorehistory + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent/predicate" + "github.com/shopspring/decimal" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldLTE(FieldID, id)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// EventType applies equality check predicate on the "event_type" field. It's identical to EventTypeEQ. +func EventType(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldEQ(FieldEventType, v)) +} + +// Delta applies equality check predicate on the "delta" field. It's identical to DeltaEQ. +func Delta(v decimal.Decimal) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldEQ(FieldDelta, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// EventTypeEQ applies the EQ predicate on the "event_type" field. +func EventTypeEQ(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldEQ(FieldEventType, v)) +} + +// EventTypeNEQ applies the NEQ predicate on the "event_type" field. +func EventTypeNEQ(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldNEQ(FieldEventType, v)) +} + +// EventTypeIn applies the In predicate on the "event_type" field. +func EventTypeIn(vs ...string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldIn(FieldEventType, vs...)) +} + +// EventTypeNotIn applies the NotIn predicate on the "event_type" field. +func EventTypeNotIn(vs ...string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldNotIn(FieldEventType, vs...)) +} + +// EventTypeGT applies the GT predicate on the "event_type" field. +func EventTypeGT(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldGT(FieldEventType, v)) +} + +// EventTypeGTE applies the GTE predicate on the "event_type" field. +func EventTypeGTE(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldGTE(FieldEventType, v)) +} + +// EventTypeLT applies the LT predicate on the "event_type" field. +func EventTypeLT(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldLT(FieldEventType, v)) +} + +// EventTypeLTE applies the LTE predicate on the "event_type" field. +func EventTypeLTE(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldLTE(FieldEventType, v)) +} + +// EventTypeContains applies the Contains predicate on the "event_type" field. +func EventTypeContains(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldContains(FieldEventType, v)) +} + +// EventTypeHasPrefix applies the HasPrefix predicate on the "event_type" field. +func EventTypeHasPrefix(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldHasPrefix(FieldEventType, v)) +} + +// EventTypeHasSuffix applies the HasSuffix predicate on the "event_type" field. +func EventTypeHasSuffix(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldHasSuffix(FieldEventType, v)) +} + +// EventTypeEqualFold applies the EqualFold predicate on the "event_type" field. +func EventTypeEqualFold(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldEqualFold(FieldEventType, v)) +} + +// EventTypeContainsFold applies the ContainsFold predicate on the "event_type" field. +func EventTypeContainsFold(v string) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldContainsFold(FieldEventType, v)) +} + +// DeltaEQ applies the EQ predicate on the "delta" field. +func DeltaEQ(v decimal.Decimal) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldEQ(FieldDelta, v)) +} + +// DeltaNEQ applies the NEQ predicate on the "delta" field. +func DeltaNEQ(v decimal.Decimal) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldNEQ(FieldDelta, v)) +} + +// DeltaIn applies the In predicate on the "delta" field. +func DeltaIn(vs ...decimal.Decimal) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldIn(FieldDelta, vs...)) +} + +// DeltaNotIn applies the NotIn predicate on the "delta" field. +func DeltaNotIn(vs ...decimal.Decimal) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldNotIn(FieldDelta, vs...)) +} + +// DeltaGT applies the GT predicate on the "delta" field. +func DeltaGT(v decimal.Decimal) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldGT(FieldDelta, v)) +} + +// DeltaGTE applies the GTE predicate on the "delta" field. +func DeltaGTE(v decimal.Decimal) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldGTE(FieldDelta, v)) +} + +// DeltaLT applies the LT predicate on the "delta" field. +func DeltaLT(v decimal.Decimal) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldLT(FieldDelta, v)) +} + +// DeltaLTE applies the LTE predicate on the "delta" field. +func DeltaLTE(v decimal.Decimal) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.FieldLTE(FieldDelta, v)) +} + +// HasPaymentOrder applies the HasEdge predicate on the "payment_order" edge. +func HasPaymentOrder() predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, PaymentOrderTable, PaymentOrderColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasPaymentOrderWith applies the HasEdge predicate on the "payment_order" edge with a given conditions (other predicates). +func HasPaymentOrderWith(preds ...predicate.PaymentOrder) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(func(s *sql.Selector) { + step := newPaymentOrderStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasProviderOrderToken applies the HasEdge predicate on the "provider_order_token" edge. +func HasProviderOrderToken() predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ProviderOrderTokenTable, ProviderOrderTokenColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasProviderOrderTokenWith applies the HasEdge predicate on the "provider_order_token" edge with a given conditions (other predicates). +func HasProviderOrderTokenWith(preds ...predicate.ProviderOrderToken) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(func(s *sql.Selector) { + step := newProviderOrderTokenStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.ProviderOrderTokenScoreHistory) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ProviderOrderTokenScoreHistory) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ProviderOrderTokenScoreHistory) predicate.ProviderOrderTokenScoreHistory { + return predicate.ProviderOrderTokenScoreHistory(sql.NotPredicates(p)) +} diff --git a/ent/providerordertokenscorehistory_create.go b/ent/providerordertokenscorehistory_create.go new file mode 100644 index 000000000..371acf2a6 --- /dev/null +++ b/ent/providerordertokenscorehistory_create.go @@ -0,0 +1,672 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" + "github.com/shopspring/decimal" +) + +// ProviderOrderTokenScoreHistoryCreate is the builder for creating a ProviderOrderTokenScoreHistory entity. +type ProviderOrderTokenScoreHistoryCreate struct { + config + mutation *ProviderOrderTokenScoreHistoryMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetCreatedAt(v time.Time) *ProviderOrderTokenScoreHistoryCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetNillableCreatedAt(v *time.Time) *ProviderOrderTokenScoreHistoryCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetUpdatedAt(v time.Time) *ProviderOrderTokenScoreHistoryCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetNillableUpdatedAt(v *time.Time) *ProviderOrderTokenScoreHistoryCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetEventType sets the "event_type" field. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetEventType(v string) *ProviderOrderTokenScoreHistoryCreate { + _c.mutation.SetEventType(v) + return _c +} + +// SetDelta sets the "delta" field. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetDelta(v decimal.Decimal) *ProviderOrderTokenScoreHistoryCreate { + _c.mutation.SetDelta(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetID(v uuid.UUID) *ProviderOrderTokenScoreHistoryCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetNillableID(v *uuid.UUID) *ProviderOrderTokenScoreHistoryCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetPaymentOrderID sets the "payment_order" edge to the PaymentOrder entity by ID. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetPaymentOrderID(id uuid.UUID) *ProviderOrderTokenScoreHistoryCreate { + _c.mutation.SetPaymentOrderID(id) + return _c +} + +// SetPaymentOrder sets the "payment_order" edge to the PaymentOrder entity. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetPaymentOrder(v *PaymentOrder) *ProviderOrderTokenScoreHistoryCreate { + return _c.SetPaymentOrderID(v.ID) +} + +// SetProviderOrderTokenID sets the "provider_order_token" edge to the ProviderOrderToken entity by ID. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetProviderOrderTokenID(id int) *ProviderOrderTokenScoreHistoryCreate { + _c.mutation.SetProviderOrderTokenID(id) + return _c +} + +// SetProviderOrderToken sets the "provider_order_token" edge to the ProviderOrderToken entity. +func (_c *ProviderOrderTokenScoreHistoryCreate) SetProviderOrderToken(v *ProviderOrderToken) *ProviderOrderTokenScoreHistoryCreate { + return _c.SetProviderOrderTokenID(v.ID) +} + +// Mutation returns the ProviderOrderTokenScoreHistoryMutation object of the builder. +func (_c *ProviderOrderTokenScoreHistoryCreate) Mutation() *ProviderOrderTokenScoreHistoryMutation { + return _c.mutation +} + +// Save creates the ProviderOrderTokenScoreHistory in the database. +func (_c *ProviderOrderTokenScoreHistoryCreate) Save(ctx context.Context) (*ProviderOrderTokenScoreHistory, error) { + if err := _c.defaults(); err != nil { + return nil, err + } + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ProviderOrderTokenScoreHistoryCreate) SaveX(ctx context.Context) *ProviderOrderTokenScoreHistory { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ProviderOrderTokenScoreHistoryCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ProviderOrderTokenScoreHistoryCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *ProviderOrderTokenScoreHistoryCreate) defaults() error { + if _, ok := _c.mutation.CreatedAt(); !ok { + if providerordertokenscorehistory.DefaultCreatedAt == nil { + return fmt.Errorf("ent: uninitialized providerordertokenscorehistory.DefaultCreatedAt (forgotten import ent/runtime?)") + } + v := providerordertokenscorehistory.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + if providerordertokenscorehistory.DefaultUpdatedAt == nil { + return fmt.Errorf("ent: uninitialized providerordertokenscorehistory.DefaultUpdatedAt (forgotten import ent/runtime?)") + } + v := providerordertokenscorehistory.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + if providerordertokenscorehistory.DefaultID == nil { + return fmt.Errorf("ent: uninitialized providerordertokenscorehistory.DefaultID (forgotten import ent/runtime?)") + } + v := providerordertokenscorehistory.DefaultID() + _c.mutation.SetID(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ProviderOrderTokenScoreHistoryCreate) check() error { + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "ProviderOrderTokenScoreHistory.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "ProviderOrderTokenScoreHistory.updated_at"`)} + } + if _, ok := _c.mutation.EventType(); !ok { + return &ValidationError{Name: "event_type", err: errors.New(`ent: missing required field "ProviderOrderTokenScoreHistory.event_type"`)} + } + if v, ok := _c.mutation.EventType(); ok { + if err := providerordertokenscorehistory.EventTypeValidator(v); err != nil { + return &ValidationError{Name: "event_type", err: fmt.Errorf(`ent: validator failed for field "ProviderOrderTokenScoreHistory.event_type": %w`, err)} + } + } + if _, ok := _c.mutation.Delta(); !ok { + return &ValidationError{Name: "delta", err: errors.New(`ent: missing required field "ProviderOrderTokenScoreHistory.delta"`)} + } + if len(_c.mutation.PaymentOrderIDs()) == 0 { + return &ValidationError{Name: "payment_order", err: errors.New(`ent: missing required edge "ProviderOrderTokenScoreHistory.payment_order"`)} + } + if len(_c.mutation.ProviderOrderTokenIDs()) == 0 { + return &ValidationError{Name: "provider_order_token", err: errors.New(`ent: missing required edge "ProviderOrderTokenScoreHistory.provider_order_token"`)} + } + return nil +} + +func (_c *ProviderOrderTokenScoreHistoryCreate) sqlSave(ctx context.Context) (*ProviderOrderTokenScoreHistory, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(*uuid.UUID); ok { + _node.ID = *id + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ProviderOrderTokenScoreHistoryCreate) createSpec() (*ProviderOrderTokenScoreHistory, *sqlgraph.CreateSpec) { + var ( + _node = &ProviderOrderTokenScoreHistory{config: _c.config} + _spec = sqlgraph.NewCreateSpec(providerordertokenscorehistory.Table, sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(providerordertokenscorehistory.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(providerordertokenscorehistory.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.EventType(); ok { + _spec.SetField(providerordertokenscorehistory.FieldEventType, field.TypeString, value) + _node.EventType = value + } + if value, ok := _c.mutation.Delta(); ok { + _spec.SetField(providerordertokenscorehistory.FieldDelta, field.TypeFloat64, value) + _node.Delta = value + } + if nodes := _c.mutation.PaymentOrderIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerordertokenscorehistory.PaymentOrderTable, + Columns: []string{providerordertokenscorehistory.PaymentOrderColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.payment_order_provider_order_token_score_histories = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ProviderOrderTokenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerordertokenscorehistory.ProviderOrderTokenTable, + Columns: []string{providerordertokenscorehistory.ProviderOrderTokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertoken.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.provider_order_token_score_histories = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ProviderOrderTokenScoreHistory.Create(). +// SetCreatedAt(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ProviderOrderTokenScoreHistoryUpsert) { +// SetCreatedAt(v+v). +// }). +// Exec(ctx) +func (_c *ProviderOrderTokenScoreHistoryCreate) OnConflict(opts ...sql.ConflictOption) *ProviderOrderTokenScoreHistoryUpsertOne { + _c.conflict = opts + return &ProviderOrderTokenScoreHistoryUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ProviderOrderTokenScoreHistory.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ProviderOrderTokenScoreHistoryCreate) OnConflictColumns(columns ...string) *ProviderOrderTokenScoreHistoryUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ProviderOrderTokenScoreHistoryUpsertOne{ + create: _c, + } +} + +type ( + // ProviderOrderTokenScoreHistoryUpsertOne is the builder for "upsert"-ing + // one ProviderOrderTokenScoreHistory node. + ProviderOrderTokenScoreHistoryUpsertOne struct { + create *ProviderOrderTokenScoreHistoryCreate + } + + // ProviderOrderTokenScoreHistoryUpsert is the "OnConflict" setter. + ProviderOrderTokenScoreHistoryUpsert struct { + *sql.UpdateSet + } +) + +// SetUpdatedAt sets the "updated_at" field. +func (u *ProviderOrderTokenScoreHistoryUpsert) SetUpdatedAt(v time.Time) *ProviderOrderTokenScoreHistoryUpsert { + u.Set(providerordertokenscorehistory.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ProviderOrderTokenScoreHistoryUpsert) UpdateUpdatedAt() *ProviderOrderTokenScoreHistoryUpsert { + u.SetExcluded(providerordertokenscorehistory.FieldUpdatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.ProviderOrderTokenScoreHistory.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(providerordertokenscorehistory.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ProviderOrderTokenScoreHistoryUpsertOne) UpdateNewValues() *ProviderOrderTokenScoreHistoryUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(providerordertokenscorehistory.FieldID) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(providerordertokenscorehistory.FieldCreatedAt) + } + if _, exists := u.create.mutation.EventType(); exists { + s.SetIgnore(providerordertokenscorehistory.FieldEventType) + } + if _, exists := u.create.mutation.Delta(); exists { + s.SetIgnore(providerordertokenscorehistory.FieldDelta) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ProviderOrderTokenScoreHistory.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ProviderOrderTokenScoreHistoryUpsertOne) Ignore() *ProviderOrderTokenScoreHistoryUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ProviderOrderTokenScoreHistoryUpsertOne) DoNothing() *ProviderOrderTokenScoreHistoryUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ProviderOrderTokenScoreHistoryCreate.OnConflict +// documentation for more info. +func (u *ProviderOrderTokenScoreHistoryUpsertOne) Update(set func(*ProviderOrderTokenScoreHistoryUpsert)) *ProviderOrderTokenScoreHistoryUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ProviderOrderTokenScoreHistoryUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ProviderOrderTokenScoreHistoryUpsertOne) SetUpdatedAt(v time.Time) *ProviderOrderTokenScoreHistoryUpsertOne { + return u.Update(func(s *ProviderOrderTokenScoreHistoryUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ProviderOrderTokenScoreHistoryUpsertOne) UpdateUpdatedAt() *ProviderOrderTokenScoreHistoryUpsertOne { + return u.Update(func(s *ProviderOrderTokenScoreHistoryUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *ProviderOrderTokenScoreHistoryUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ProviderOrderTokenScoreHistoryCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ProviderOrderTokenScoreHistoryUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *ProviderOrderTokenScoreHistoryUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("ent: ProviderOrderTokenScoreHistoryUpsertOne.ID is not supported by MySQL driver. Use ProviderOrderTokenScoreHistoryUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *ProviderOrderTokenScoreHistoryUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ProviderOrderTokenScoreHistoryCreateBulk is the builder for creating many ProviderOrderTokenScoreHistory entities in bulk. +type ProviderOrderTokenScoreHistoryCreateBulk struct { + config + err error + builders []*ProviderOrderTokenScoreHistoryCreate + conflict []sql.ConflictOption +} + +// Save creates the ProviderOrderTokenScoreHistory entities in the database. +func (_c *ProviderOrderTokenScoreHistoryCreateBulk) Save(ctx context.Context) ([]*ProviderOrderTokenScoreHistory, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ProviderOrderTokenScoreHistory, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ProviderOrderTokenScoreHistoryMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ProviderOrderTokenScoreHistoryCreateBulk) SaveX(ctx context.Context) []*ProviderOrderTokenScoreHistory { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ProviderOrderTokenScoreHistoryCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ProviderOrderTokenScoreHistoryCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ProviderOrderTokenScoreHistory.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ProviderOrderTokenScoreHistoryUpsert) { +// SetCreatedAt(v+v). +// }). +// Exec(ctx) +func (_c *ProviderOrderTokenScoreHistoryCreateBulk) OnConflict(opts ...sql.ConflictOption) *ProviderOrderTokenScoreHistoryUpsertBulk { + _c.conflict = opts + return &ProviderOrderTokenScoreHistoryUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ProviderOrderTokenScoreHistory.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ProviderOrderTokenScoreHistoryCreateBulk) OnConflictColumns(columns ...string) *ProviderOrderTokenScoreHistoryUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ProviderOrderTokenScoreHistoryUpsertBulk{ + create: _c, + } +} + +// ProviderOrderTokenScoreHistoryUpsertBulk is the builder for "upsert"-ing +// a bulk of ProviderOrderTokenScoreHistory nodes. +type ProviderOrderTokenScoreHistoryUpsertBulk struct { + create *ProviderOrderTokenScoreHistoryCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ProviderOrderTokenScoreHistory.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(providerordertokenscorehistory.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ProviderOrderTokenScoreHistoryUpsertBulk) UpdateNewValues() *ProviderOrderTokenScoreHistoryUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(providerordertokenscorehistory.FieldID) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(providerordertokenscorehistory.FieldCreatedAt) + } + if _, exists := b.mutation.EventType(); exists { + s.SetIgnore(providerordertokenscorehistory.FieldEventType) + } + if _, exists := b.mutation.Delta(); exists { + s.SetIgnore(providerordertokenscorehistory.FieldDelta) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ProviderOrderTokenScoreHistory.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ProviderOrderTokenScoreHistoryUpsertBulk) Ignore() *ProviderOrderTokenScoreHistoryUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ProviderOrderTokenScoreHistoryUpsertBulk) DoNothing() *ProviderOrderTokenScoreHistoryUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ProviderOrderTokenScoreHistoryCreateBulk.OnConflict +// documentation for more info. +func (u *ProviderOrderTokenScoreHistoryUpsertBulk) Update(set func(*ProviderOrderTokenScoreHistoryUpsert)) *ProviderOrderTokenScoreHistoryUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ProviderOrderTokenScoreHistoryUpsert{UpdateSet: update}) + })) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *ProviderOrderTokenScoreHistoryUpsertBulk) SetUpdatedAt(v time.Time) *ProviderOrderTokenScoreHistoryUpsertBulk { + return u.Update(func(s *ProviderOrderTokenScoreHistoryUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *ProviderOrderTokenScoreHistoryUpsertBulk) UpdateUpdatedAt() *ProviderOrderTokenScoreHistoryUpsertBulk { + return u.Update(func(s *ProviderOrderTokenScoreHistoryUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *ProviderOrderTokenScoreHistoryUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the ProviderOrderTokenScoreHistoryCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ProviderOrderTokenScoreHistoryCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ProviderOrderTokenScoreHistoryUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/providerordertokenscorehistory_delete.go b/ent/providerordertokenscorehistory_delete.go new file mode 100644 index 000000000..525984ba3 --- /dev/null +++ b/ent/providerordertokenscorehistory_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/paycrest/aggregator/ent/predicate" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" +) + +// ProviderOrderTokenScoreHistoryDelete is the builder for deleting a ProviderOrderTokenScoreHistory entity. +type ProviderOrderTokenScoreHistoryDelete struct { + config + hooks []Hook + mutation *ProviderOrderTokenScoreHistoryMutation +} + +// Where appends a list predicates to the ProviderOrderTokenScoreHistoryDelete builder. +func (_d *ProviderOrderTokenScoreHistoryDelete) Where(ps ...predicate.ProviderOrderTokenScoreHistory) *ProviderOrderTokenScoreHistoryDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ProviderOrderTokenScoreHistoryDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ProviderOrderTokenScoreHistoryDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ProviderOrderTokenScoreHistoryDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(providerordertokenscorehistory.Table, sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ProviderOrderTokenScoreHistoryDeleteOne is the builder for deleting a single ProviderOrderTokenScoreHistory entity. +type ProviderOrderTokenScoreHistoryDeleteOne struct { + _d *ProviderOrderTokenScoreHistoryDelete +} + +// Where appends a list predicates to the ProviderOrderTokenScoreHistoryDelete builder. +func (_d *ProviderOrderTokenScoreHistoryDeleteOne) Where(ps ...predicate.ProviderOrderTokenScoreHistory) *ProviderOrderTokenScoreHistoryDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ProviderOrderTokenScoreHistoryDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{providerordertokenscorehistory.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ProviderOrderTokenScoreHistoryDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/providerordertokenscorehistory_query.go b/ent/providerordertokenscorehistory_query.go new file mode 100644 index 000000000..073ee7d45 --- /dev/null +++ b/ent/providerordertokenscorehistory_query.go @@ -0,0 +1,690 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/predicate" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" +) + +// ProviderOrderTokenScoreHistoryQuery is the builder for querying ProviderOrderTokenScoreHistory entities. +type ProviderOrderTokenScoreHistoryQuery struct { + config + ctx *QueryContext + order []providerordertokenscorehistory.OrderOption + inters []Interceptor + predicates []predicate.ProviderOrderTokenScoreHistory + withPaymentOrder *PaymentOrderQuery + withProviderOrderToken *ProviderOrderTokenQuery + withFKs bool + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ProviderOrderTokenScoreHistoryQuery builder. +func (_q *ProviderOrderTokenScoreHistoryQuery) Where(ps ...predicate.ProviderOrderTokenScoreHistory) *ProviderOrderTokenScoreHistoryQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ProviderOrderTokenScoreHistoryQuery) Limit(limit int) *ProviderOrderTokenScoreHistoryQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ProviderOrderTokenScoreHistoryQuery) Offset(offset int) *ProviderOrderTokenScoreHistoryQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *ProviderOrderTokenScoreHistoryQuery) Unique(unique bool) *ProviderOrderTokenScoreHistoryQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ProviderOrderTokenScoreHistoryQuery) Order(o ...providerordertokenscorehistory.OrderOption) *ProviderOrderTokenScoreHistoryQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryPaymentOrder chains the current query on the "payment_order" edge. +func (_q *ProviderOrderTokenScoreHistoryQuery) QueryPaymentOrder() *PaymentOrderQuery { + query := (&PaymentOrderClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(providerordertokenscorehistory.Table, providerordertokenscorehistory.FieldID, selector), + sqlgraph.To(paymentorder.Table, paymentorder.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, providerordertokenscorehistory.PaymentOrderTable, providerordertokenscorehistory.PaymentOrderColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryProviderOrderToken chains the current query on the "provider_order_token" edge. +func (_q *ProviderOrderTokenScoreHistoryQuery) QueryProviderOrderToken() *ProviderOrderTokenQuery { + query := (&ProviderOrderTokenClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(providerordertokenscorehistory.Table, providerordertokenscorehistory.FieldID, selector), + sqlgraph.To(providerordertoken.Table, providerordertoken.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, providerordertokenscorehistory.ProviderOrderTokenTable, providerordertokenscorehistory.ProviderOrderTokenColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ProviderOrderTokenScoreHistory entity from the query. +// Returns a *NotFoundError when no ProviderOrderTokenScoreHistory was found. +func (_q *ProviderOrderTokenScoreHistoryQuery) First(ctx context.Context) (*ProviderOrderTokenScoreHistory, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{providerordertokenscorehistory.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ProviderOrderTokenScoreHistoryQuery) FirstX(ctx context.Context) *ProviderOrderTokenScoreHistory { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ProviderOrderTokenScoreHistory ID from the query. +// Returns a *NotFoundError when no ProviderOrderTokenScoreHistory ID was found. +func (_q *ProviderOrderTokenScoreHistoryQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{providerordertokenscorehistory.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ProviderOrderTokenScoreHistoryQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ProviderOrderTokenScoreHistory entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ProviderOrderTokenScoreHistory entity is found. +// Returns a *NotFoundError when no ProviderOrderTokenScoreHistory entities are found. +func (_q *ProviderOrderTokenScoreHistoryQuery) Only(ctx context.Context) (*ProviderOrderTokenScoreHistory, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{providerordertokenscorehistory.Label} + default: + return nil, &NotSingularError{providerordertokenscorehistory.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ProviderOrderTokenScoreHistoryQuery) OnlyX(ctx context.Context) *ProviderOrderTokenScoreHistory { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ProviderOrderTokenScoreHistory ID in the query. +// Returns a *NotSingularError when more than one ProviderOrderTokenScoreHistory ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ProviderOrderTokenScoreHistoryQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{providerordertokenscorehistory.Label} + default: + err = &NotSingularError{providerordertokenscorehistory.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ProviderOrderTokenScoreHistoryQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of ProviderOrderTokenScoreHistories. +func (_q *ProviderOrderTokenScoreHistoryQuery) All(ctx context.Context) ([]*ProviderOrderTokenScoreHistory, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ProviderOrderTokenScoreHistory, *ProviderOrderTokenScoreHistoryQuery]() + return withInterceptors[[]*ProviderOrderTokenScoreHistory](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ProviderOrderTokenScoreHistoryQuery) AllX(ctx context.Context) []*ProviderOrderTokenScoreHistory { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ProviderOrderTokenScoreHistory IDs. +func (_q *ProviderOrderTokenScoreHistoryQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(providerordertokenscorehistory.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ProviderOrderTokenScoreHistoryQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ProviderOrderTokenScoreHistoryQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ProviderOrderTokenScoreHistoryQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ProviderOrderTokenScoreHistoryQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ProviderOrderTokenScoreHistoryQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ProviderOrderTokenScoreHistoryQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ProviderOrderTokenScoreHistoryQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ProviderOrderTokenScoreHistoryQuery) Clone() *ProviderOrderTokenScoreHistoryQuery { + if _q == nil { + return nil + } + return &ProviderOrderTokenScoreHistoryQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]providerordertokenscorehistory.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ProviderOrderTokenScoreHistory{}, _q.predicates...), + withPaymentOrder: _q.withPaymentOrder.Clone(), + withProviderOrderToken: _q.withProviderOrderToken.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithPaymentOrder tells the query-builder to eager-load the nodes that are connected to +// the "payment_order" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ProviderOrderTokenScoreHistoryQuery) WithPaymentOrder(opts ...func(*PaymentOrderQuery)) *ProviderOrderTokenScoreHistoryQuery { + query := (&PaymentOrderClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withPaymentOrder = query + return _q +} + +// WithProviderOrderToken tells the query-builder to eager-load the nodes that are connected to +// the "provider_order_token" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ProviderOrderTokenScoreHistoryQuery) WithProviderOrderToken(opts ...func(*ProviderOrderTokenQuery)) *ProviderOrderTokenScoreHistoryQuery { + query := (&ProviderOrderTokenClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withProviderOrderToken = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// CreatedAt time.Time `json:"created_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ProviderOrderTokenScoreHistory.Query(). +// GroupBy(providerordertokenscorehistory.FieldCreatedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *ProviderOrderTokenScoreHistoryQuery) GroupBy(field string, fields ...string) *ProviderOrderTokenScoreHistoryGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ProviderOrderTokenScoreHistoryGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = providerordertokenscorehistory.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// CreatedAt time.Time `json:"created_at,omitempty"` +// } +// +// client.ProviderOrderTokenScoreHistory.Query(). +// Select(providerordertokenscorehistory.FieldCreatedAt). +// Scan(ctx, &v) +func (_q *ProviderOrderTokenScoreHistoryQuery) Select(fields ...string) *ProviderOrderTokenScoreHistorySelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ProviderOrderTokenScoreHistorySelect{ProviderOrderTokenScoreHistoryQuery: _q} + sbuild.label = providerordertokenscorehistory.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ProviderOrderTokenScoreHistorySelect configured with the given aggregations. +func (_q *ProviderOrderTokenScoreHistoryQuery) Aggregate(fns ...AggregateFunc) *ProviderOrderTokenScoreHistorySelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ProviderOrderTokenScoreHistoryQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !providerordertokenscorehistory.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ProviderOrderTokenScoreHistoryQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ProviderOrderTokenScoreHistory, error) { + var ( + nodes = []*ProviderOrderTokenScoreHistory{} + withFKs = _q.withFKs + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withPaymentOrder != nil, + _q.withProviderOrderToken != nil, + } + ) + if _q.withPaymentOrder != nil || _q.withProviderOrderToken != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, providerordertokenscorehistory.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ProviderOrderTokenScoreHistory).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ProviderOrderTokenScoreHistory{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withPaymentOrder; query != nil { + if err := _q.loadPaymentOrder(ctx, query, nodes, nil, + func(n *ProviderOrderTokenScoreHistory, e *PaymentOrder) { n.Edges.PaymentOrder = e }); err != nil { + return nil, err + } + } + if query := _q.withProviderOrderToken; query != nil { + if err := _q.loadProviderOrderToken(ctx, query, nodes, nil, + func(n *ProviderOrderTokenScoreHistory, e *ProviderOrderToken) { n.Edges.ProviderOrderToken = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ProviderOrderTokenScoreHistoryQuery) loadPaymentOrder(ctx context.Context, query *PaymentOrderQuery, nodes []*ProviderOrderTokenScoreHistory, init func(*ProviderOrderTokenScoreHistory), assign func(*ProviderOrderTokenScoreHistory, *PaymentOrder)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*ProviderOrderTokenScoreHistory) + for i := range nodes { + if nodes[i].payment_order_provider_order_token_score_histories == nil { + continue + } + fk := *nodes[i].payment_order_provider_order_token_score_histories + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(paymentorder.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "payment_order_provider_order_token_score_histories" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ProviderOrderTokenScoreHistoryQuery) loadProviderOrderToken(ctx context.Context, query *ProviderOrderTokenQuery, nodes []*ProviderOrderTokenScoreHistory, init func(*ProviderOrderTokenScoreHistory), assign func(*ProviderOrderTokenScoreHistory, *ProviderOrderToken)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*ProviderOrderTokenScoreHistory) + for i := range nodes { + if nodes[i].provider_order_token_score_histories == nil { + continue + } + fk := *nodes[i].provider_order_token_score_histories + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(providerordertoken.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "provider_order_token_score_histories" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ProviderOrderTokenScoreHistoryQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ProviderOrderTokenScoreHistoryQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(providerordertokenscorehistory.Table, providerordertokenscorehistory.Columns, sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, providerordertokenscorehistory.FieldID) + for i := range fields { + if fields[i] != providerordertokenscorehistory.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ProviderOrderTokenScoreHistoryQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(providerordertokenscorehistory.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = providerordertokenscorehistory.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ProviderOrderTokenScoreHistoryGroupBy is the group-by builder for ProviderOrderTokenScoreHistory entities. +type ProviderOrderTokenScoreHistoryGroupBy struct { + selector + build *ProviderOrderTokenScoreHistoryQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ProviderOrderTokenScoreHistoryGroupBy) Aggregate(fns ...AggregateFunc) *ProviderOrderTokenScoreHistoryGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ProviderOrderTokenScoreHistoryGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ProviderOrderTokenScoreHistoryQuery, *ProviderOrderTokenScoreHistoryGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ProviderOrderTokenScoreHistoryGroupBy) sqlScan(ctx context.Context, root *ProviderOrderTokenScoreHistoryQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ProviderOrderTokenScoreHistorySelect is the builder for selecting fields of ProviderOrderTokenScoreHistory entities. +type ProviderOrderTokenScoreHistorySelect struct { + *ProviderOrderTokenScoreHistoryQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ProviderOrderTokenScoreHistorySelect) Aggregate(fns ...AggregateFunc) *ProviderOrderTokenScoreHistorySelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ProviderOrderTokenScoreHistorySelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ProviderOrderTokenScoreHistoryQuery, *ProviderOrderTokenScoreHistorySelect](ctx, _s.ProviderOrderTokenScoreHistoryQuery, _s, _s.inters, v) +} + +func (_s *ProviderOrderTokenScoreHistorySelect) sqlScan(ctx context.Context, root *ProviderOrderTokenScoreHistoryQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/ent/providerordertokenscorehistory_update.go b/ent/providerordertokenscorehistory_update.go new file mode 100644 index 000000000..062d41714 --- /dev/null +++ b/ent/providerordertokenscorehistory_update.go @@ -0,0 +1,439 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/predicate" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" +) + +// ProviderOrderTokenScoreHistoryUpdate is the builder for updating ProviderOrderTokenScoreHistory entities. +type ProviderOrderTokenScoreHistoryUpdate struct { + config + hooks []Hook + mutation *ProviderOrderTokenScoreHistoryMutation +} + +// Where appends a list predicates to the ProviderOrderTokenScoreHistoryUpdate builder. +func (_u *ProviderOrderTokenScoreHistoryUpdate) Where(ps ...predicate.ProviderOrderTokenScoreHistory) *ProviderOrderTokenScoreHistoryUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ProviderOrderTokenScoreHistoryUpdate) SetUpdatedAt(v time.Time) *ProviderOrderTokenScoreHistoryUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetPaymentOrderID sets the "payment_order" edge to the PaymentOrder entity by ID. +func (_u *ProviderOrderTokenScoreHistoryUpdate) SetPaymentOrderID(id uuid.UUID) *ProviderOrderTokenScoreHistoryUpdate { + _u.mutation.SetPaymentOrderID(id) + return _u +} + +// SetPaymentOrder sets the "payment_order" edge to the PaymentOrder entity. +func (_u *ProviderOrderTokenScoreHistoryUpdate) SetPaymentOrder(v *PaymentOrder) *ProviderOrderTokenScoreHistoryUpdate { + return _u.SetPaymentOrderID(v.ID) +} + +// SetProviderOrderTokenID sets the "provider_order_token" edge to the ProviderOrderToken entity by ID. +func (_u *ProviderOrderTokenScoreHistoryUpdate) SetProviderOrderTokenID(id int) *ProviderOrderTokenScoreHistoryUpdate { + _u.mutation.SetProviderOrderTokenID(id) + return _u +} + +// SetProviderOrderToken sets the "provider_order_token" edge to the ProviderOrderToken entity. +func (_u *ProviderOrderTokenScoreHistoryUpdate) SetProviderOrderToken(v *ProviderOrderToken) *ProviderOrderTokenScoreHistoryUpdate { + return _u.SetProviderOrderTokenID(v.ID) +} + +// Mutation returns the ProviderOrderTokenScoreHistoryMutation object of the builder. +func (_u *ProviderOrderTokenScoreHistoryUpdate) Mutation() *ProviderOrderTokenScoreHistoryMutation { + return _u.mutation +} + +// ClearPaymentOrder clears the "payment_order" edge to the PaymentOrder entity. +func (_u *ProviderOrderTokenScoreHistoryUpdate) ClearPaymentOrder() *ProviderOrderTokenScoreHistoryUpdate { + _u.mutation.ClearPaymentOrder() + return _u +} + +// ClearProviderOrderToken clears the "provider_order_token" edge to the ProviderOrderToken entity. +func (_u *ProviderOrderTokenScoreHistoryUpdate) ClearProviderOrderToken() *ProviderOrderTokenScoreHistoryUpdate { + _u.mutation.ClearProviderOrderToken() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ProviderOrderTokenScoreHistoryUpdate) Save(ctx context.Context) (int, error) { + if err := _u.defaults(); err != nil { + return 0, err + } + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ProviderOrderTokenScoreHistoryUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ProviderOrderTokenScoreHistoryUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ProviderOrderTokenScoreHistoryUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ProviderOrderTokenScoreHistoryUpdate) defaults() error { + if _, ok := _u.mutation.UpdatedAt(); !ok { + if providerordertokenscorehistory.UpdateDefaultUpdatedAt == nil { + return fmt.Errorf("ent: uninitialized providerordertokenscorehistory.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)") + } + v := providerordertokenscorehistory.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ProviderOrderTokenScoreHistoryUpdate) check() error { + if _u.mutation.PaymentOrderCleared() && len(_u.mutation.PaymentOrderIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ProviderOrderTokenScoreHistory.payment_order"`) + } + if _u.mutation.ProviderOrderTokenCleared() && len(_u.mutation.ProviderOrderTokenIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ProviderOrderTokenScoreHistory.provider_order_token"`) + } + return nil +} + +func (_u *ProviderOrderTokenScoreHistoryUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(providerordertokenscorehistory.Table, providerordertokenscorehistory.Columns, sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(providerordertokenscorehistory.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.PaymentOrderCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerordertokenscorehistory.PaymentOrderTable, + Columns: []string{providerordertokenscorehistory.PaymentOrderColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.PaymentOrderIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerordertokenscorehistory.PaymentOrderTable, + Columns: []string{providerordertokenscorehistory.PaymentOrderColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ProviderOrderTokenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerordertokenscorehistory.ProviderOrderTokenTable, + Columns: []string{providerordertokenscorehistory.ProviderOrderTokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertoken.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ProviderOrderTokenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerordertokenscorehistory.ProviderOrderTokenTable, + Columns: []string{providerordertokenscorehistory.ProviderOrderTokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertoken.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{providerordertokenscorehistory.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ProviderOrderTokenScoreHistoryUpdateOne is the builder for updating a single ProviderOrderTokenScoreHistory entity. +type ProviderOrderTokenScoreHistoryUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ProviderOrderTokenScoreHistoryMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) SetUpdatedAt(v time.Time) *ProviderOrderTokenScoreHistoryUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetPaymentOrderID sets the "payment_order" edge to the PaymentOrder entity by ID. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) SetPaymentOrderID(id uuid.UUID) *ProviderOrderTokenScoreHistoryUpdateOne { + _u.mutation.SetPaymentOrderID(id) + return _u +} + +// SetPaymentOrder sets the "payment_order" edge to the PaymentOrder entity. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) SetPaymentOrder(v *PaymentOrder) *ProviderOrderTokenScoreHistoryUpdateOne { + return _u.SetPaymentOrderID(v.ID) +} + +// SetProviderOrderTokenID sets the "provider_order_token" edge to the ProviderOrderToken entity by ID. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) SetProviderOrderTokenID(id int) *ProviderOrderTokenScoreHistoryUpdateOne { + _u.mutation.SetProviderOrderTokenID(id) + return _u +} + +// SetProviderOrderToken sets the "provider_order_token" edge to the ProviderOrderToken entity. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) SetProviderOrderToken(v *ProviderOrderToken) *ProviderOrderTokenScoreHistoryUpdateOne { + return _u.SetProviderOrderTokenID(v.ID) +} + +// Mutation returns the ProviderOrderTokenScoreHistoryMutation object of the builder. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) Mutation() *ProviderOrderTokenScoreHistoryMutation { + return _u.mutation +} + +// ClearPaymentOrder clears the "payment_order" edge to the PaymentOrder entity. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) ClearPaymentOrder() *ProviderOrderTokenScoreHistoryUpdateOne { + _u.mutation.ClearPaymentOrder() + return _u +} + +// ClearProviderOrderToken clears the "provider_order_token" edge to the ProviderOrderToken entity. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) ClearProviderOrderToken() *ProviderOrderTokenScoreHistoryUpdateOne { + _u.mutation.ClearProviderOrderToken() + return _u +} + +// Where appends a list predicates to the ProviderOrderTokenScoreHistoryUpdate builder. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) Where(ps ...predicate.ProviderOrderTokenScoreHistory) *ProviderOrderTokenScoreHistoryUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) Select(field string, fields ...string) *ProviderOrderTokenScoreHistoryUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ProviderOrderTokenScoreHistory entity. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) Save(ctx context.Context) (*ProviderOrderTokenScoreHistory, error) { + if err := _u.defaults(); err != nil { + return nil, err + } + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) SaveX(ctx context.Context) *ProviderOrderTokenScoreHistory { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) defaults() error { + if _, ok := _u.mutation.UpdatedAt(); !ok { + if providerordertokenscorehistory.UpdateDefaultUpdatedAt == nil { + return fmt.Errorf("ent: uninitialized providerordertokenscorehistory.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)") + } + v := providerordertokenscorehistory.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) check() error { + if _u.mutation.PaymentOrderCleared() && len(_u.mutation.PaymentOrderIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ProviderOrderTokenScoreHistory.payment_order"`) + } + if _u.mutation.ProviderOrderTokenCleared() && len(_u.mutation.ProviderOrderTokenIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ProviderOrderTokenScoreHistory.provider_order_token"`) + } + return nil +} + +func (_u *ProviderOrderTokenScoreHistoryUpdateOne) sqlSave(ctx context.Context) (_node *ProviderOrderTokenScoreHistory, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(providerordertokenscorehistory.Table, providerordertokenscorehistory.Columns, sqlgraph.NewFieldSpec(providerordertokenscorehistory.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "ProviderOrderTokenScoreHistory.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, providerordertokenscorehistory.FieldID) + for _, f := range fields { + if !providerordertokenscorehistory.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != providerordertokenscorehistory.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(providerordertokenscorehistory.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.PaymentOrderCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerordertokenscorehistory.PaymentOrderTable, + Columns: []string{providerordertokenscorehistory.PaymentOrderColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.PaymentOrderIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerordertokenscorehistory.PaymentOrderTable, + Columns: []string{providerordertokenscorehistory.PaymentOrderColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ProviderOrderTokenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerordertokenscorehistory.ProviderOrderTokenTable, + Columns: []string{providerordertokenscorehistory.ProviderOrderTokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertoken.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ProviderOrderTokenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: providerordertokenscorehistory.ProviderOrderTokenTable, + Columns: []string{providerordertokenscorehistory.ProviderOrderTokenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(providerordertoken.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &ProviderOrderTokenScoreHistory{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{providerordertokenscorehistory.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/ent/providerprofile.go b/ent/providerprofile.go index 8ba14c868..a9acd25e6 100644 --- a/ent/providerprofile.go +++ b/ent/providerprofile.go @@ -48,8 +48,6 @@ type ProviderProfileEdges struct { APIKey *APIKey `json:"api_key,omitempty"` // ProviderBalances holds the value of the provider_balances edge. ProviderBalances []*ProviderBalances `json:"provider_balances,omitempty"` - // ProvisionBuckets holds the value of the provision_buckets edge. - ProvisionBuckets []*ProvisionBucket `json:"provision_buckets,omitempty"` // OrderTokens holds the value of the order_tokens edge. OrderTokens []*ProviderOrderToken `json:"order_tokens,omitempty"` // ProviderRating holds the value of the provider_rating edge. @@ -60,7 +58,7 @@ type ProviderProfileEdges struct { FiatAccounts []*ProviderFiatAccount `json:"fiat_accounts,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [8]bool + loadedTypes [7]bool } // UserOrErr returns the User value or an error if the edge @@ -94,19 +92,10 @@ func (e ProviderProfileEdges) ProviderBalancesOrErr() ([]*ProviderBalances, erro return nil, &NotLoadedError{edge: "provider_balances"} } -// ProvisionBucketsOrErr returns the ProvisionBuckets value or an error if the edge -// was not loaded in eager-loading. -func (e ProviderProfileEdges) ProvisionBucketsOrErr() ([]*ProvisionBucket, error) { - if e.loadedTypes[3] { - return e.ProvisionBuckets, nil - } - return nil, &NotLoadedError{edge: "provision_buckets"} -} - // OrderTokensOrErr returns the OrderTokens value or an error if the edge // was not loaded in eager-loading. func (e ProviderProfileEdges) OrderTokensOrErr() ([]*ProviderOrderToken, error) { - if e.loadedTypes[4] { + if e.loadedTypes[3] { return e.OrderTokens, nil } return nil, &NotLoadedError{edge: "order_tokens"} @@ -117,7 +106,7 @@ func (e ProviderProfileEdges) OrderTokensOrErr() ([]*ProviderOrderToken, error) func (e ProviderProfileEdges) ProviderRatingOrErr() (*ProviderRating, error) { if e.ProviderRating != nil { return e.ProviderRating, nil - } else if e.loadedTypes[5] { + } else if e.loadedTypes[4] { return nil, &NotFoundError{label: providerrating.Label} } return nil, &NotLoadedError{edge: "provider_rating"} @@ -126,7 +115,7 @@ func (e ProviderProfileEdges) ProviderRatingOrErr() (*ProviderRating, error) { // AssignedOrdersOrErr returns the AssignedOrders value or an error if the edge // was not loaded in eager-loading. func (e ProviderProfileEdges) AssignedOrdersOrErr() ([]*PaymentOrder, error) { - if e.loadedTypes[6] { + if e.loadedTypes[5] { return e.AssignedOrders, nil } return nil, &NotLoadedError{edge: "assigned_orders"} @@ -135,7 +124,7 @@ func (e ProviderProfileEdges) AssignedOrdersOrErr() ([]*PaymentOrder, error) { // FiatAccountsOrErr returns the FiatAccounts value or an error if the edge // was not loaded in eager-loading. func (e ProviderProfileEdges) FiatAccountsOrErr() ([]*ProviderFiatAccount, error) { - if e.loadedTypes[7] { + if e.loadedTypes[6] { return e.FiatAccounts, nil } return nil, &NotLoadedError{edge: "fiat_accounts"} @@ -246,11 +235,6 @@ func (_m *ProviderProfile) QueryProviderBalances() *ProviderBalancesQuery { return NewProviderProfileClient(_m.config).QueryProviderBalances(_m) } -// QueryProvisionBuckets queries the "provision_buckets" edge of the ProviderProfile entity. -func (_m *ProviderProfile) QueryProvisionBuckets() *ProvisionBucketQuery { - return NewProviderProfileClient(_m.config).QueryProvisionBuckets(_m) -} - // QueryOrderTokens queries the "order_tokens" edge of the ProviderProfile entity. func (_m *ProviderProfile) QueryOrderTokens() *ProviderOrderTokenQuery { return NewProviderProfileClient(_m.config).QueryOrderTokens(_m) diff --git a/ent/providerprofile/providerprofile.go b/ent/providerprofile/providerprofile.go index 83a3d5bed..dd03ea116 100644 --- a/ent/providerprofile/providerprofile.go +++ b/ent/providerprofile/providerprofile.go @@ -33,8 +33,6 @@ const ( EdgeAPIKey = "api_key" // EdgeProviderBalances holds the string denoting the provider_balances edge name in mutations. EdgeProviderBalances = "provider_balances" - // EdgeProvisionBuckets holds the string denoting the provision_buckets edge name in mutations. - EdgeProvisionBuckets = "provision_buckets" // EdgeOrderTokens holds the string denoting the order_tokens edge name in mutations. EdgeOrderTokens = "order_tokens" // EdgeProviderRating holds the string denoting the provider_rating edge name in mutations. @@ -66,11 +64,6 @@ const ( ProviderBalancesInverseTable = "provider_balances" // ProviderBalancesColumn is the table column denoting the provider_balances relation/edge. ProviderBalancesColumn = "provider_profile_provider_balances" - // ProvisionBucketsTable is the table that holds the provision_buckets relation/edge. The primary key declared below. - ProvisionBucketsTable = "provision_bucket_provider_profiles" - // ProvisionBucketsInverseTable is the table name for the ProvisionBucket entity. - // It exists in this package in order to avoid circular dependency with the "provisionbucket" package. - ProvisionBucketsInverseTable = "provision_buckets" // OrderTokensTable is the table that holds the order_tokens relation/edge. OrderTokensTable = "provider_order_tokens" // OrderTokensInverseTable is the table name for the ProviderOrderToken entity. @@ -118,12 +111,6 @@ var ForeignKeys = []string{ "user_provider_profile", } -var ( - // ProvisionBucketsPrimaryKey and ProvisionBucketsColumn2 are the table columns denoting the - // primary key for the provision_buckets relation (M2M). - ProvisionBucketsPrimaryKey = []string{"provision_bucket_id", "provider_profile_id"} -) - // ValidColumn reports if the column name is valid (part of the table columns). func ValidColumn(column string) bool { for i := range Columns { @@ -270,20 +257,6 @@ func ByProviderBalances(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption } } -// ByProvisionBucketsCount orders the results by provision_buckets count. -func ByProvisionBucketsCount(opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newProvisionBucketsStep(), opts...) - } -} - -// ByProvisionBuckets orders the results by provision_buckets terms. -func ByProvisionBuckets(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newProvisionBucketsStep(), append([]sql.OrderTerm{term}, terms...)...) - } -} - // ByOrderTokensCount orders the results by order_tokens count. func ByOrderTokensCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -353,13 +326,6 @@ func newProviderBalancesStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, ProviderBalancesTable, ProviderBalancesColumn), ) } -func newProvisionBucketsStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(ProvisionBucketsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, ProvisionBucketsTable, ProvisionBucketsPrimaryKey...), - ) -} func newOrderTokensStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), diff --git a/ent/providerprofile/where.go b/ent/providerprofile/where.go index b246d1ebe..99eb3b9df 100644 --- a/ent/providerprofile/where.go +++ b/ent/providerprofile/where.go @@ -394,29 +394,6 @@ func HasProviderBalancesWith(preds ...predicate.ProviderBalances) predicate.Prov }) } -// HasProvisionBuckets applies the HasEdge predicate on the "provision_buckets" edge. -func HasProvisionBuckets() predicate.ProviderProfile { - return predicate.ProviderProfile(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, ProvisionBucketsTable, ProvisionBucketsPrimaryKey...), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasProvisionBucketsWith applies the HasEdge predicate on the "provision_buckets" edge with a given conditions (other predicates). -func HasProvisionBucketsWith(preds ...predicate.ProvisionBucket) predicate.ProviderProfile { - return predicate.ProviderProfile(func(s *sql.Selector) { - step := newProvisionBucketsStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - // HasOrderTokens applies the HasEdge predicate on the "order_tokens" edge. func HasOrderTokens() predicate.ProviderProfile { return predicate.ProviderProfile(func(s *sql.Selector) { diff --git a/ent/providerprofile_create.go b/ent/providerprofile_create.go index 21b6a8594..d4f83d863 100644 --- a/ent/providerprofile_create.go +++ b/ent/providerprofile_create.go @@ -20,7 +20,6 @@ import ( "github.com/paycrest/aggregator/ent/providerordertoken" "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/providerrating" - "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/paycrest/aggregator/ent/user" ) @@ -175,21 +174,6 @@ func (_c *ProviderProfileCreate) AddProviderBalances(v ...*ProviderBalances) *Pr return _c.AddProviderBalanceIDs(ids...) } -// AddProvisionBucketIDs adds the "provision_buckets" edge to the ProvisionBucket entity by IDs. -func (_c *ProviderProfileCreate) AddProvisionBucketIDs(ids ...int) *ProviderProfileCreate { - _c.mutation.AddProvisionBucketIDs(ids...) - return _c -} - -// AddProvisionBuckets adds the "provision_buckets" edges to the ProvisionBucket entity. -func (_c *ProviderProfileCreate) AddProvisionBuckets(v ...*ProvisionBucket) *ProviderProfileCreate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _c.AddProvisionBucketIDs(ids...) -} - // AddOrderTokenIDs adds the "order_tokens" edge to the ProviderOrderToken entity by IDs. func (_c *ProviderProfileCreate) AddOrderTokenIDs(ids ...int) *ProviderProfileCreate { _c.mutation.AddOrderTokenIDs(ids...) @@ -452,22 +436,6 @@ func (_c *ProviderProfileCreate) createSpec() (*ProviderProfile, *sqlgraph.Creat } _spec.Edges = append(_spec.Edges, edge) } - if nodes := _c.mutation.ProvisionBucketsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: providerprofile.ProvisionBucketsTable, - Columns: providerprofile.ProvisionBucketsPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } if nodes := _c.mutation.OrderTokensIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/ent/providerprofile_query.go b/ent/providerprofile_query.go index ce6c92cf2..dbd941fed 100644 --- a/ent/providerprofile_query.go +++ b/ent/providerprofile_query.go @@ -21,7 +21,6 @@ import ( "github.com/paycrest/aggregator/ent/providerordertoken" "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/providerrating" - "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/paycrest/aggregator/ent/user" ) @@ -35,7 +34,6 @@ type ProviderProfileQuery struct { withUser *UserQuery withAPIKey *APIKeyQuery withProviderBalances *ProviderBalancesQuery - withProvisionBuckets *ProvisionBucketQuery withOrderTokens *ProviderOrderTokenQuery withProviderRating *ProviderRatingQuery withAssignedOrders *PaymentOrderQuery @@ -143,28 +141,6 @@ func (_q *ProviderProfileQuery) QueryProviderBalances() *ProviderBalancesQuery { return query } -// QueryProvisionBuckets chains the current query on the "provision_buckets" edge. -func (_q *ProviderProfileQuery) QueryProvisionBuckets() *ProvisionBucketQuery { - query := (&ProvisionBucketClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(providerprofile.Table, providerprofile.FieldID, selector), - sqlgraph.To(provisionbucket.Table, provisionbucket.FieldID), - sqlgraph.Edge(sqlgraph.M2M, true, providerprofile.ProvisionBucketsTable, providerprofile.ProvisionBucketsPrimaryKey...), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - // QueryOrderTokens chains the current query on the "order_tokens" edge. func (_q *ProviderProfileQuery) QueryOrderTokens() *ProviderOrderTokenQuery { query := (&ProviderOrderTokenClient{config: _q.config}).Query() @@ -448,7 +424,6 @@ func (_q *ProviderProfileQuery) Clone() *ProviderProfileQuery { withUser: _q.withUser.Clone(), withAPIKey: _q.withAPIKey.Clone(), withProviderBalances: _q.withProviderBalances.Clone(), - withProvisionBuckets: _q.withProvisionBuckets.Clone(), withOrderTokens: _q.withOrderTokens.Clone(), withProviderRating: _q.withProviderRating.Clone(), withAssignedOrders: _q.withAssignedOrders.Clone(), @@ -492,17 +467,6 @@ func (_q *ProviderProfileQuery) WithProviderBalances(opts ...func(*ProviderBalan return _q } -// WithProvisionBuckets tells the query-builder to eager-load the nodes that are connected to -// the "provision_buckets" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *ProviderProfileQuery) WithProvisionBuckets(opts ...func(*ProvisionBucketQuery)) *ProviderProfileQuery { - query := (&ProvisionBucketClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withProvisionBuckets = query - return _q -} - // WithOrderTokens tells the query-builder to eager-load the nodes that are connected to // the "order_tokens" edge. The optional arguments are used to configure the query builder of the edge. func (_q *ProviderProfileQuery) WithOrderTokens(opts ...func(*ProviderOrderTokenQuery)) *ProviderProfileQuery { @@ -626,11 +590,10 @@ func (_q *ProviderProfileQuery) sqlAll(ctx context.Context, hooks ...queryHook) nodes = []*ProviderProfile{} withFKs = _q.withFKs _spec = _q.querySpec() - loadedTypes = [8]bool{ + loadedTypes = [7]bool{ _q.withUser != nil, _q.withAPIKey != nil, _q.withProviderBalances != nil, - _q.withProvisionBuckets != nil, _q.withOrderTokens != nil, _q.withProviderRating != nil, _q.withAssignedOrders != nil, @@ -682,15 +645,6 @@ func (_q *ProviderProfileQuery) sqlAll(ctx context.Context, hooks ...queryHook) return nil, err } } - if query := _q.withProvisionBuckets; query != nil { - if err := _q.loadProvisionBuckets(ctx, query, nodes, - func(n *ProviderProfile) { n.Edges.ProvisionBuckets = []*ProvisionBucket{} }, - func(n *ProviderProfile, e *ProvisionBucket) { - n.Edges.ProvisionBuckets = append(n.Edges.ProvisionBuckets, e) - }); err != nil { - return nil, err - } - } if query := _q.withOrderTokens; query != nil { if err := _q.loadOrderTokens(ctx, query, nodes, func(n *ProviderProfile) { n.Edges.OrderTokens = []*ProviderOrderToken{} }, @@ -814,67 +768,6 @@ func (_q *ProviderProfileQuery) loadProviderBalances(ctx context.Context, query } return nil } -func (_q *ProviderProfileQuery) loadProvisionBuckets(ctx context.Context, query *ProvisionBucketQuery, nodes []*ProviderProfile, init func(*ProviderProfile), assign func(*ProviderProfile, *ProvisionBucket)) error { - edgeIDs := make([]driver.Value, len(nodes)) - byID := make(map[string]*ProviderProfile) - nids := make(map[int]map[*ProviderProfile]struct{}) - for i, node := range nodes { - edgeIDs[i] = node.ID - byID[node.ID] = node - if init != nil { - init(node) - } - } - query.Where(func(s *sql.Selector) { - joinT := sql.Table(providerprofile.ProvisionBucketsTable) - s.Join(joinT).On(s.C(provisionbucket.FieldID), joinT.C(providerprofile.ProvisionBucketsPrimaryKey[0])) - s.Where(sql.InValues(joinT.C(providerprofile.ProvisionBucketsPrimaryKey[1]), edgeIDs...)) - columns := s.SelectedColumns() - s.Select(joinT.C(providerprofile.ProvisionBucketsPrimaryKey[1])) - s.AppendSelect(columns...) - s.SetDistinct(false) - }) - if err := query.prepareQuery(ctx); err != nil { - return err - } - qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { - return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { - assign := spec.Assign - values := spec.ScanValues - spec.ScanValues = func(columns []string) ([]any, error) { - values, err := values(columns[1:]) - if err != nil { - return nil, err - } - return append([]any{new(sql.NullString)}, values...), nil - } - spec.Assign = func(columns []string, values []any) error { - outValue := values[0].(*sql.NullString).String - inValue := int(values[1].(*sql.NullInt64).Int64) - if nids[inValue] == nil { - nids[inValue] = map[*ProviderProfile]struct{}{byID[outValue]: {}} - return assign(columns[1:], values[1:]) - } - nids[inValue][byID[outValue]] = struct{}{} - return nil - } - }) - }) - neighbors, err := withInterceptors[[]*ProvisionBucket](ctx, query, qr, query.inters) - if err != nil { - return err - } - for _, n := range neighbors { - nodes, ok := nids[n.ID] - if !ok { - return fmt.Errorf(`unexpected "provision_buckets" node returned %v`, n.ID) - } - for kn := range nodes { - assign(kn, n) - } - } - return nil -} func (_q *ProviderProfileQuery) loadOrderTokens(ctx context.Context, query *ProviderOrderTokenQuery, nodes []*ProviderProfile, init func(*ProviderProfile), assign func(*ProviderProfile, *ProviderOrderToken)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[string]*ProviderProfile) diff --git a/ent/providerprofile_update.go b/ent/providerprofile_update.go index dec575aab..257dd26d0 100644 --- a/ent/providerprofile_update.go +++ b/ent/providerprofile_update.go @@ -20,7 +20,6 @@ import ( "github.com/paycrest/aggregator/ent/providerordertoken" "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/providerrating" - "github.com/paycrest/aggregator/ent/provisionbucket" ) // ProviderProfileUpdate is the builder for updating ProviderProfile entities. @@ -158,21 +157,6 @@ func (_u *ProviderProfileUpdate) AddProviderBalances(v ...*ProviderBalances) *Pr return _u.AddProviderBalanceIDs(ids...) } -// AddProvisionBucketIDs adds the "provision_buckets" edge to the ProvisionBucket entity by IDs. -func (_u *ProviderProfileUpdate) AddProvisionBucketIDs(ids ...int) *ProviderProfileUpdate { - _u.mutation.AddProvisionBucketIDs(ids...) - return _u -} - -// AddProvisionBuckets adds the "provision_buckets" edges to the ProvisionBucket entity. -func (_u *ProviderProfileUpdate) AddProvisionBuckets(v ...*ProvisionBucket) *ProviderProfileUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddProvisionBucketIDs(ids...) -} - // AddOrderTokenIDs adds the "order_tokens" edge to the ProviderOrderToken entity by IDs. func (_u *ProviderProfileUpdate) AddOrderTokenIDs(ids ...int) *ProviderProfileUpdate { _u.mutation.AddOrderTokenIDs(ids...) @@ -269,27 +253,6 @@ func (_u *ProviderProfileUpdate) RemoveProviderBalances(v ...*ProviderBalances) return _u.RemoveProviderBalanceIDs(ids...) } -// ClearProvisionBuckets clears all "provision_buckets" edges to the ProvisionBucket entity. -func (_u *ProviderProfileUpdate) ClearProvisionBuckets() *ProviderProfileUpdate { - _u.mutation.ClearProvisionBuckets() - return _u -} - -// RemoveProvisionBucketIDs removes the "provision_buckets" edge to ProvisionBucket entities by IDs. -func (_u *ProviderProfileUpdate) RemoveProvisionBucketIDs(ids ...int) *ProviderProfileUpdate { - _u.mutation.RemoveProvisionBucketIDs(ids...) - return _u -} - -// RemoveProvisionBuckets removes "provision_buckets" edges to ProvisionBucket entities. -func (_u *ProviderProfileUpdate) RemoveProvisionBuckets(v ...*ProvisionBucket) *ProviderProfileUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveProvisionBucketIDs(ids...) -} - // ClearOrderTokens clears all "order_tokens" edges to the ProviderOrderToken entity. func (_u *ProviderProfileUpdate) ClearOrderTokens() *ProviderProfileUpdate { _u.mutation.ClearOrderTokens() @@ -528,51 +491,6 @@ func (_u *ProviderProfileUpdate) sqlSave(ctx context.Context) (_node int, err er } _spec.Edges.Add = append(_spec.Edges.Add, edge) } - if _u.mutation.ProvisionBucketsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: providerprofile.ProvisionBucketsTable, - Columns: providerprofile.ProvisionBucketsPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedProvisionBucketsIDs(); len(nodes) > 0 && !_u.mutation.ProvisionBucketsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: providerprofile.ProvisionBucketsTable, - Columns: providerprofile.ProvisionBucketsPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.ProvisionBucketsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: providerprofile.ProvisionBucketsTable, - Columns: providerprofile.ProvisionBucketsPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } if _u.mutation.OrderTokensCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -879,21 +797,6 @@ func (_u *ProviderProfileUpdateOne) AddProviderBalances(v ...*ProviderBalances) return _u.AddProviderBalanceIDs(ids...) } -// AddProvisionBucketIDs adds the "provision_buckets" edge to the ProvisionBucket entity by IDs. -func (_u *ProviderProfileUpdateOne) AddProvisionBucketIDs(ids ...int) *ProviderProfileUpdateOne { - _u.mutation.AddProvisionBucketIDs(ids...) - return _u -} - -// AddProvisionBuckets adds the "provision_buckets" edges to the ProvisionBucket entity. -func (_u *ProviderProfileUpdateOne) AddProvisionBuckets(v ...*ProvisionBucket) *ProviderProfileUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddProvisionBucketIDs(ids...) -} - // AddOrderTokenIDs adds the "order_tokens" edge to the ProviderOrderToken entity by IDs. func (_u *ProviderProfileUpdateOne) AddOrderTokenIDs(ids ...int) *ProviderProfileUpdateOne { _u.mutation.AddOrderTokenIDs(ids...) @@ -990,27 +893,6 @@ func (_u *ProviderProfileUpdateOne) RemoveProviderBalances(v ...*ProviderBalance return _u.RemoveProviderBalanceIDs(ids...) } -// ClearProvisionBuckets clears all "provision_buckets" edges to the ProvisionBucket entity. -func (_u *ProviderProfileUpdateOne) ClearProvisionBuckets() *ProviderProfileUpdateOne { - _u.mutation.ClearProvisionBuckets() - return _u -} - -// RemoveProvisionBucketIDs removes the "provision_buckets" edge to ProvisionBucket entities by IDs. -func (_u *ProviderProfileUpdateOne) RemoveProvisionBucketIDs(ids ...int) *ProviderProfileUpdateOne { - _u.mutation.RemoveProvisionBucketIDs(ids...) - return _u -} - -// RemoveProvisionBuckets removes "provision_buckets" edges to ProvisionBucket entities. -func (_u *ProviderProfileUpdateOne) RemoveProvisionBuckets(v ...*ProvisionBucket) *ProviderProfileUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveProvisionBucketIDs(ids...) -} - // ClearOrderTokens clears all "order_tokens" edges to the ProviderOrderToken entity. func (_u *ProviderProfileUpdateOne) ClearOrderTokens() *ProviderProfileUpdateOne { _u.mutation.ClearOrderTokens() @@ -1279,51 +1161,6 @@ func (_u *ProviderProfileUpdateOne) sqlSave(ctx context.Context) (_node *Provide } _spec.Edges.Add = append(_spec.Edges.Add, edge) } - if _u.mutation.ProvisionBucketsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: providerprofile.ProvisionBucketsTable, - Columns: providerprofile.ProvisionBucketsPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedProvisionBucketsIDs(); len(nodes) > 0 && !_u.mutation.ProvisionBucketsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: providerprofile.ProvisionBucketsTable, - Columns: providerprofile.ProvisionBucketsPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.ProvisionBucketsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: true, - Table: providerprofile.ProvisionBucketsTable, - Columns: providerprofile.ProvisionBucketsPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } if _u.mutation.OrderTokensCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/ent/provisionbucket.go b/ent/provisionbucket.go index 5d4cf961e..08b20f33c 100644 --- a/ent/provisionbucket.go +++ b/ent/provisionbucket.go @@ -10,7 +10,6 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" "github.com/google/uuid" - "github.com/paycrest/aggregator/ent/fiatcurrency" "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/shopspring/decimal" ) @@ -26,53 +25,9 @@ type ProvisionBucket struct { MaxAmount decimal.Decimal `json:"max_amount,omitempty"` // CreatedAt holds the value of the "created_at" field. CreatedAt time.Time `json:"created_at,omitempty"` - // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the ProvisionBucketQuery when eager-loading is set. - Edges ProvisionBucketEdges `json:"edges"` - fiat_currency_provision_buckets *uuid.UUID - selectValues sql.SelectValues -} - -// ProvisionBucketEdges holds the relations/edges for other nodes in the graph. -type ProvisionBucketEdges struct { - // Currency holds the value of the currency edge. - Currency *FiatCurrency `json:"currency,omitempty"` - // PaymentOrders holds the value of the payment_orders edge. - PaymentOrders []*PaymentOrder `json:"payment_orders,omitempty"` - // ProviderProfiles holds the value of the provider_profiles edge. - ProviderProfiles []*ProviderProfile `json:"provider_profiles,omitempty"` - // loadedTypes holds the information for reporting if a - // type was loaded (or requested) in eager-loading or not. - loadedTypes [3]bool -} - -// CurrencyOrErr returns the Currency value or an error if the edge -// was not loaded in eager-loading, or loaded but was not found. -func (e ProvisionBucketEdges) CurrencyOrErr() (*FiatCurrency, error) { - if e.Currency != nil { - return e.Currency, nil - } else if e.loadedTypes[0] { - return nil, &NotFoundError{label: fiatcurrency.Label} - } - return nil, &NotLoadedError{edge: "currency"} -} - -// PaymentOrdersOrErr returns the PaymentOrders value or an error if the edge -// was not loaded in eager-loading. -func (e ProvisionBucketEdges) PaymentOrdersOrErr() ([]*PaymentOrder, error) { - if e.loadedTypes[1] { - return e.PaymentOrders, nil - } - return nil, &NotLoadedError{edge: "payment_orders"} -} - -// ProviderProfilesOrErr returns the ProviderProfiles value or an error if the edge -// was not loaded in eager-loading. -func (e ProvisionBucketEdges) ProviderProfilesOrErr() ([]*ProviderProfile, error) { - if e.loadedTypes[2] { - return e.ProviderProfiles, nil - } - return nil, &NotLoadedError{edge: "provider_profiles"} + // FiatCurrencyID holds the value of the "fiat_currency_id" field. + FiatCurrencyID *uuid.UUID `json:"fiat_currency_id,omitempty"` + selectValues sql.SelectValues } // scanValues returns the types for scanning values from sql.Rows. @@ -80,14 +35,14 @@ func (*ProvisionBucket) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { + case provisionbucket.FieldFiatCurrencyID: + values[i] = &sql.NullScanner{S: new(uuid.UUID)} case provisionbucket.FieldMinAmount, provisionbucket.FieldMaxAmount: values[i] = new(decimal.Decimal) case provisionbucket.FieldID: values[i] = new(sql.NullInt64) case provisionbucket.FieldCreatedAt: values[i] = new(sql.NullTime) - case provisionbucket.ForeignKeys[0]: // fiat_currency_provision_buckets - values[i] = &sql.NullScanner{S: new(uuid.UUID)} default: values[i] = new(sql.UnknownType) } @@ -127,12 +82,12 @@ func (_m *ProvisionBucket) assignValues(columns []string, values []any) error { } else if value.Valid { _m.CreatedAt = value.Time } - case provisionbucket.ForeignKeys[0]: + case provisionbucket.FieldFiatCurrencyID: if value, ok := values[i].(*sql.NullScanner); !ok { - return fmt.Errorf("unexpected type %T for field fiat_currency_provision_buckets", values[i]) + return fmt.Errorf("unexpected type %T for field fiat_currency_id", values[i]) } else if value.Valid { - _m.fiat_currency_provision_buckets = new(uuid.UUID) - *_m.fiat_currency_provision_buckets = *value.S.(*uuid.UUID) + _m.FiatCurrencyID = new(uuid.UUID) + *_m.FiatCurrencyID = *value.S.(*uuid.UUID) } default: _m.selectValues.Set(columns[i], values[i]) @@ -147,21 +102,6 @@ func (_m *ProvisionBucket) Value(name string) (ent.Value, error) { return _m.selectValues.Get(name) } -// QueryCurrency queries the "currency" edge of the ProvisionBucket entity. -func (_m *ProvisionBucket) QueryCurrency() *FiatCurrencyQuery { - return NewProvisionBucketClient(_m.config).QueryCurrency(_m) -} - -// QueryPaymentOrders queries the "payment_orders" edge of the ProvisionBucket entity. -func (_m *ProvisionBucket) QueryPaymentOrders() *PaymentOrderQuery { - return NewProvisionBucketClient(_m.config).QueryPaymentOrders(_m) -} - -// QueryProviderProfiles queries the "provider_profiles" edge of the ProvisionBucket entity. -func (_m *ProvisionBucket) QueryProviderProfiles() *ProviderProfileQuery { - return NewProvisionBucketClient(_m.config).QueryProviderProfiles(_m) -} - // Update returns a builder for updating this ProvisionBucket. // Note that you need to call ProvisionBucket.Unwrap() before calling this method if this ProvisionBucket // was returned from a transaction, and the transaction was committed or rolled back. @@ -193,6 +133,11 @@ func (_m *ProvisionBucket) String() string { builder.WriteString(", ") builder.WriteString("created_at=") builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.FiatCurrencyID; v != nil { + builder.WriteString("fiat_currency_id=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } builder.WriteByte(')') return builder.String() } diff --git a/ent/provisionbucket/provisionbucket.go b/ent/provisionbucket/provisionbucket.go index 2068c5065..d84268fb9 100644 --- a/ent/provisionbucket/provisionbucket.go +++ b/ent/provisionbucket/provisionbucket.go @@ -6,7 +6,6 @@ import ( "time" "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" ) const ( @@ -20,33 +19,10 @@ const ( FieldMaxAmount = "max_amount" // FieldCreatedAt holds the string denoting the created_at field in the database. FieldCreatedAt = "created_at" - // EdgeCurrency holds the string denoting the currency edge name in mutations. - EdgeCurrency = "currency" - // EdgePaymentOrders holds the string denoting the payment_orders edge name in mutations. - EdgePaymentOrders = "payment_orders" - // EdgeProviderProfiles holds the string denoting the provider_profiles edge name in mutations. - EdgeProviderProfiles = "provider_profiles" + // FieldFiatCurrencyID holds the string denoting the fiat_currency_id field in the database. + FieldFiatCurrencyID = "fiat_currency_provision_buckets" // Table holds the table name of the provisionbucket in the database. Table = "provision_buckets" - // CurrencyTable is the table that holds the currency relation/edge. - CurrencyTable = "provision_buckets" - // CurrencyInverseTable is the table name for the FiatCurrency entity. - // It exists in this package in order to avoid circular dependency with the "fiatcurrency" package. - CurrencyInverseTable = "fiat_currencies" - // CurrencyColumn is the table column denoting the currency relation/edge. - CurrencyColumn = "fiat_currency_provision_buckets" - // PaymentOrdersTable is the table that holds the payment_orders relation/edge. - PaymentOrdersTable = "payment_orders" - // PaymentOrdersInverseTable is the table name for the PaymentOrder entity. - // It exists in this package in order to avoid circular dependency with the "paymentorder" package. - PaymentOrdersInverseTable = "payment_orders" - // PaymentOrdersColumn is the table column denoting the payment_orders relation/edge. - PaymentOrdersColumn = "provision_bucket_payment_orders" - // ProviderProfilesTable is the table that holds the provider_profiles relation/edge. The primary key declared below. - ProviderProfilesTable = "provision_bucket_provider_profiles" - // ProviderProfilesInverseTable is the table name for the ProviderProfile entity. - // It exists in this package in order to avoid circular dependency with the "providerprofile" package. - ProviderProfilesInverseTable = "provider_profiles" ) // Columns holds all SQL columns for provisionbucket fields. @@ -55,20 +31,9 @@ var Columns = []string{ FieldMinAmount, FieldMaxAmount, FieldCreatedAt, + FieldFiatCurrencyID, } -// ForeignKeys holds the SQL foreign-keys that are owned by the "provision_buckets" -// table and are not defined as standalone fields in the schema. -var ForeignKeys = []string{ - "fiat_currency_provision_buckets", -} - -var ( - // ProviderProfilesPrimaryKey and ProviderProfilesColumn2 are the table columns denoting the - // primary key for the provider_profiles relation (M2M). - ProviderProfilesPrimaryKey = []string{"provision_bucket_id", "provider_profile_id"} -) - // ValidColumn reports if the column name is valid (part of the table columns). func ValidColumn(column string) bool { for i := range Columns { @@ -76,11 +41,6 @@ func ValidColumn(column string) bool { return true } } - for i := range ForeignKeys { - if column == ForeignKeys[i] { - return true - } - } return false } @@ -112,58 +72,7 @@ func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() } -// ByCurrencyField orders the results by currency field. -func ByCurrencyField(field string, opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newCurrencyStep(), sql.OrderByField(field, opts...)) - } -} - -// ByPaymentOrdersCount orders the results by payment_orders count. -func ByPaymentOrdersCount(opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newPaymentOrdersStep(), opts...) - } -} - -// ByPaymentOrders orders the results by payment_orders terms. -func ByPaymentOrders(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newPaymentOrdersStep(), append([]sql.OrderTerm{term}, terms...)...) - } -} - -// ByProviderProfilesCount orders the results by provider_profiles count. -func ByProviderProfilesCount(opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newProviderProfilesStep(), opts...) - } -} - -// ByProviderProfiles orders the results by provider_profiles terms. -func ByProviderProfiles(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newProviderProfilesStep(), append([]sql.OrderTerm{term}, terms...)...) - } -} -func newCurrencyStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(CurrencyInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, CurrencyTable, CurrencyColumn), - ) -} -func newPaymentOrdersStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(PaymentOrdersInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, PaymentOrdersTable, PaymentOrdersColumn), - ) -} -func newProviderProfilesStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(ProviderProfilesInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, ProviderProfilesTable, ProviderProfilesPrimaryKey...), - ) +// ByFiatCurrencyID orders the results by the fiat_currency_id field. +func ByFiatCurrencyID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFiatCurrencyID, opts...).ToFunc() } diff --git a/ent/provisionbucket/where.go b/ent/provisionbucket/where.go index 3a8f0a0f2..4aa5034bc 100644 --- a/ent/provisionbucket/where.go +++ b/ent/provisionbucket/where.go @@ -6,7 +6,7 @@ import ( "time" "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" "github.com/paycrest/aggregator/ent/predicate" "github.com/shopspring/decimal" ) @@ -71,6 +71,11 @@ func CreatedAt(v time.Time) predicate.ProvisionBucket { return predicate.ProvisionBucket(sql.FieldEQ(FieldCreatedAt, v)) } +// FiatCurrencyID applies equality check predicate on the "fiat_currency_id" field. It's identical to FiatCurrencyIDEQ. +func FiatCurrencyID(v uuid.UUID) predicate.ProvisionBucket { + return predicate.ProvisionBucket(sql.FieldEQ(FieldFiatCurrencyID, v)) +} + // MinAmountEQ applies the EQ predicate on the "min_amount" field. func MinAmountEQ(v decimal.Decimal) predicate.ProvisionBucket { return predicate.ProvisionBucket(sql.FieldEQ(FieldMinAmount, v)) @@ -191,73 +196,54 @@ func CreatedAtLTE(v time.Time) predicate.ProvisionBucket { return predicate.ProvisionBucket(sql.FieldLTE(FieldCreatedAt, v)) } -// HasCurrency applies the HasEdge predicate on the "currency" edge. -func HasCurrency() predicate.ProvisionBucket { - return predicate.ProvisionBucket(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, CurrencyTable, CurrencyColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasCurrencyWith applies the HasEdge predicate on the "currency" edge with a given conditions (other predicates). -func HasCurrencyWith(preds ...predicate.FiatCurrency) predicate.ProvisionBucket { - return predicate.ProvisionBucket(func(s *sql.Selector) { - step := newCurrencyStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// HasPaymentOrders applies the HasEdge predicate on the "payment_orders" edge. -func HasPaymentOrders() predicate.ProvisionBucket { - return predicate.ProvisionBucket(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, PaymentOrdersTable, PaymentOrdersColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasPaymentOrdersWith applies the HasEdge predicate on the "payment_orders" edge with a given conditions (other predicates). -func HasPaymentOrdersWith(preds ...predicate.PaymentOrder) predicate.ProvisionBucket { - return predicate.ProvisionBucket(func(s *sql.Selector) { - step := newPaymentOrdersStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// HasProviderProfiles applies the HasEdge predicate on the "provider_profiles" edge. -func HasProviderProfiles() predicate.ProvisionBucket { - return predicate.ProvisionBucket(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, ProviderProfilesTable, ProviderProfilesPrimaryKey...), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasProviderProfilesWith applies the HasEdge predicate on the "provider_profiles" edge with a given conditions (other predicates). -func HasProviderProfilesWith(preds ...predicate.ProviderProfile) predicate.ProvisionBucket { - return predicate.ProvisionBucket(func(s *sql.Selector) { - step := newProviderProfilesStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) +// FiatCurrencyIDEQ applies the EQ predicate on the "fiat_currency_id" field. +func FiatCurrencyIDEQ(v uuid.UUID) predicate.ProvisionBucket { + return predicate.ProvisionBucket(sql.FieldEQ(FieldFiatCurrencyID, v)) +} + +// FiatCurrencyIDNEQ applies the NEQ predicate on the "fiat_currency_id" field. +func FiatCurrencyIDNEQ(v uuid.UUID) predicate.ProvisionBucket { + return predicate.ProvisionBucket(sql.FieldNEQ(FieldFiatCurrencyID, v)) +} + +// FiatCurrencyIDIn applies the In predicate on the "fiat_currency_id" field. +func FiatCurrencyIDIn(vs ...uuid.UUID) predicate.ProvisionBucket { + return predicate.ProvisionBucket(sql.FieldIn(FieldFiatCurrencyID, vs...)) +} + +// FiatCurrencyIDNotIn applies the NotIn predicate on the "fiat_currency_id" field. +func FiatCurrencyIDNotIn(vs ...uuid.UUID) predicate.ProvisionBucket { + return predicate.ProvisionBucket(sql.FieldNotIn(FieldFiatCurrencyID, vs...)) +} + +// FiatCurrencyIDGT applies the GT predicate on the "fiat_currency_id" field. +func FiatCurrencyIDGT(v uuid.UUID) predicate.ProvisionBucket { + return predicate.ProvisionBucket(sql.FieldGT(FieldFiatCurrencyID, v)) +} + +// FiatCurrencyIDGTE applies the GTE predicate on the "fiat_currency_id" field. +func FiatCurrencyIDGTE(v uuid.UUID) predicate.ProvisionBucket { + return predicate.ProvisionBucket(sql.FieldGTE(FieldFiatCurrencyID, v)) +} + +// FiatCurrencyIDLT applies the LT predicate on the "fiat_currency_id" field. +func FiatCurrencyIDLT(v uuid.UUID) predicate.ProvisionBucket { + return predicate.ProvisionBucket(sql.FieldLT(FieldFiatCurrencyID, v)) +} + +// FiatCurrencyIDLTE applies the LTE predicate on the "fiat_currency_id" field. +func FiatCurrencyIDLTE(v uuid.UUID) predicate.ProvisionBucket { + return predicate.ProvisionBucket(sql.FieldLTE(FieldFiatCurrencyID, v)) +} + +// FiatCurrencyIDIsNil applies the IsNil predicate on the "fiat_currency_id" field. +func FiatCurrencyIDIsNil() predicate.ProvisionBucket { + return predicate.ProvisionBucket(sql.FieldIsNull(FieldFiatCurrencyID)) +} + +// FiatCurrencyIDNotNil applies the NotNil predicate on the "fiat_currency_id" field. +func FiatCurrencyIDNotNil() predicate.ProvisionBucket { + return predicate.ProvisionBucket(sql.FieldNotNull(FieldFiatCurrencyID)) } // And groups predicates with the AND operator between them. diff --git a/ent/provisionbucket_create.go b/ent/provisionbucket_create.go index a763b56ca..9aabefa25 100644 --- a/ent/provisionbucket_create.go +++ b/ent/provisionbucket_create.go @@ -12,9 +12,6 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/google/uuid" - "github.com/paycrest/aggregator/ent/fiatcurrency" - "github.com/paycrest/aggregator/ent/paymentorder" - "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/shopspring/decimal" ) @@ -53,47 +50,20 @@ func (_c *ProvisionBucketCreate) SetNillableCreatedAt(v *time.Time) *ProvisionBu return _c } -// SetCurrencyID sets the "currency" edge to the FiatCurrency entity by ID. -func (_c *ProvisionBucketCreate) SetCurrencyID(id uuid.UUID) *ProvisionBucketCreate { - _c.mutation.SetCurrencyID(id) +// SetFiatCurrencyID sets the "fiat_currency_id" field. +func (_c *ProvisionBucketCreate) SetFiatCurrencyID(v uuid.UUID) *ProvisionBucketCreate { + _c.mutation.SetFiatCurrencyID(v) return _c } -// SetCurrency sets the "currency" edge to the FiatCurrency entity. -func (_c *ProvisionBucketCreate) SetCurrency(v *FiatCurrency) *ProvisionBucketCreate { - return _c.SetCurrencyID(v.ID) -} - -// AddPaymentOrderIDs adds the "payment_orders" edge to the PaymentOrder entity by IDs. -func (_c *ProvisionBucketCreate) AddPaymentOrderIDs(ids ...uuid.UUID) *ProvisionBucketCreate { - _c.mutation.AddPaymentOrderIDs(ids...) - return _c -} - -// AddPaymentOrders adds the "payment_orders" edges to the PaymentOrder entity. -func (_c *ProvisionBucketCreate) AddPaymentOrders(v ...*PaymentOrder) *ProvisionBucketCreate { - ids := make([]uuid.UUID, len(v)) - for i := range v { - ids[i] = v[i].ID +// SetNillableFiatCurrencyID sets the "fiat_currency_id" field if the given value is not nil. +func (_c *ProvisionBucketCreate) SetNillableFiatCurrencyID(v *uuid.UUID) *ProvisionBucketCreate { + if v != nil { + _c.SetFiatCurrencyID(*v) } - return _c.AddPaymentOrderIDs(ids...) -} - -// AddProviderProfileIDs adds the "provider_profiles" edge to the ProviderProfile entity by IDs. -func (_c *ProvisionBucketCreate) AddProviderProfileIDs(ids ...string) *ProvisionBucketCreate { - _c.mutation.AddProviderProfileIDs(ids...) return _c } -// AddProviderProfiles adds the "provider_profiles" edges to the ProviderProfile entity. -func (_c *ProvisionBucketCreate) AddProviderProfiles(v ...*ProviderProfile) *ProvisionBucketCreate { - ids := make([]string, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _c.AddProviderProfileIDs(ids...) -} - // Mutation returns the ProvisionBucketMutation object of the builder. func (_c *ProvisionBucketCreate) Mutation() *ProvisionBucketMutation { return _c.mutation @@ -146,9 +116,6 @@ func (_c *ProvisionBucketCreate) check() error { if _, ok := _c.mutation.CreatedAt(); !ok { return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "ProvisionBucket.created_at"`)} } - if len(_c.mutation.CurrencyIDs()) == 0 { - return &ValidationError{Name: "currency", err: errors.New(`ent: missing required edge "ProvisionBucket.currency"`)} - } return nil } @@ -188,54 +155,9 @@ func (_c *ProvisionBucketCreate) createSpec() (*ProvisionBucket, *sqlgraph.Creat _spec.SetField(provisionbucket.FieldCreatedAt, field.TypeTime, value) _node.CreatedAt = value } - if nodes := _c.mutation.CurrencyIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: provisionbucket.CurrencyTable, - Columns: []string{provisionbucket.CurrencyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(fiatcurrency.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _node.fiat_currency_provision_buckets = &nodes[0] - _spec.Edges = append(_spec.Edges, edge) - } - if nodes := _c.mutation.PaymentOrdersIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: provisionbucket.PaymentOrdersTable, - Columns: []string{provisionbucket.PaymentOrdersColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - if nodes := _c.mutation.ProviderProfilesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: provisionbucket.ProviderProfilesTable, - Columns: provisionbucket.ProviderProfilesPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(providerprofile.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) + if value, ok := _c.mutation.FiatCurrencyID(); ok { + _spec.SetField(provisionbucket.FieldFiatCurrencyID, field.TypeUUID, value) + _node.FiatCurrencyID = &value } return _node, _spec } @@ -325,6 +247,24 @@ func (u *ProvisionBucketUpsert) AddMaxAmount(v decimal.Decimal) *ProvisionBucket return u } +// SetFiatCurrencyID sets the "fiat_currency_id" field. +func (u *ProvisionBucketUpsert) SetFiatCurrencyID(v uuid.UUID) *ProvisionBucketUpsert { + u.Set(provisionbucket.FieldFiatCurrencyID, v) + return u +} + +// UpdateFiatCurrencyID sets the "fiat_currency_id" field to the value that was provided on create. +func (u *ProvisionBucketUpsert) UpdateFiatCurrencyID() *ProvisionBucketUpsert { + u.SetExcluded(provisionbucket.FieldFiatCurrencyID) + return u +} + +// ClearFiatCurrencyID clears the value of the "fiat_currency_id" field. +func (u *ProvisionBucketUpsert) ClearFiatCurrencyID() *ProvisionBucketUpsert { + u.SetNull(provisionbucket.FieldFiatCurrencyID) + return u +} + // UpdateNewValues updates the mutable fields using the new values that were set on create. // Using this option is equivalent to using: // @@ -412,6 +352,27 @@ func (u *ProvisionBucketUpsertOne) UpdateMaxAmount() *ProvisionBucketUpsertOne { }) } +// SetFiatCurrencyID sets the "fiat_currency_id" field. +func (u *ProvisionBucketUpsertOne) SetFiatCurrencyID(v uuid.UUID) *ProvisionBucketUpsertOne { + return u.Update(func(s *ProvisionBucketUpsert) { + s.SetFiatCurrencyID(v) + }) +} + +// UpdateFiatCurrencyID sets the "fiat_currency_id" field to the value that was provided on create. +func (u *ProvisionBucketUpsertOne) UpdateFiatCurrencyID() *ProvisionBucketUpsertOne { + return u.Update(func(s *ProvisionBucketUpsert) { + s.UpdateFiatCurrencyID() + }) +} + +// ClearFiatCurrencyID clears the value of the "fiat_currency_id" field. +func (u *ProvisionBucketUpsertOne) ClearFiatCurrencyID() *ProvisionBucketUpsertOne { + return u.Update(func(s *ProvisionBucketUpsert) { + s.ClearFiatCurrencyID() + }) +} + // Exec executes the query. func (u *ProvisionBucketUpsertOne) Exec(ctx context.Context) error { if len(u.create.conflict) == 0 { @@ -665,6 +626,27 @@ func (u *ProvisionBucketUpsertBulk) UpdateMaxAmount() *ProvisionBucketUpsertBulk }) } +// SetFiatCurrencyID sets the "fiat_currency_id" field. +func (u *ProvisionBucketUpsertBulk) SetFiatCurrencyID(v uuid.UUID) *ProvisionBucketUpsertBulk { + return u.Update(func(s *ProvisionBucketUpsert) { + s.SetFiatCurrencyID(v) + }) +} + +// UpdateFiatCurrencyID sets the "fiat_currency_id" field to the value that was provided on create. +func (u *ProvisionBucketUpsertBulk) UpdateFiatCurrencyID() *ProvisionBucketUpsertBulk { + return u.Update(func(s *ProvisionBucketUpsert) { + s.UpdateFiatCurrencyID() + }) +} + +// ClearFiatCurrencyID clears the value of the "fiat_currency_id" field. +func (u *ProvisionBucketUpsertBulk) ClearFiatCurrencyID() *ProvisionBucketUpsertBulk { + return u.Update(func(s *ProvisionBucketUpsert) { + s.ClearFiatCurrencyID() + }) +} + // Exec executes the query. func (u *ProvisionBucketUpsertBulk) Exec(ctx context.Context) error { if u.create.err != nil { diff --git a/ent/provisionbucket_query.go b/ent/provisionbucket_query.go index 301a5a73c..119b05441 100644 --- a/ent/provisionbucket_query.go +++ b/ent/provisionbucket_query.go @@ -4,7 +4,6 @@ package ent import ( "context" - "database/sql/driver" "fmt" "math" @@ -12,25 +11,17 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" - "github.com/google/uuid" - "github.com/paycrest/aggregator/ent/fiatcurrency" - "github.com/paycrest/aggregator/ent/paymentorder" "github.com/paycrest/aggregator/ent/predicate" - "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/provisionbucket" ) // ProvisionBucketQuery is the builder for querying ProvisionBucket entities. type ProvisionBucketQuery struct { config - ctx *QueryContext - order []provisionbucket.OrderOption - inters []Interceptor - predicates []predicate.ProvisionBucket - withCurrency *FiatCurrencyQuery - withPaymentOrders *PaymentOrderQuery - withProviderProfiles *ProviderProfileQuery - withFKs bool + ctx *QueryContext + order []provisionbucket.OrderOption + inters []Interceptor + predicates []predicate.ProvisionBucket // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -67,72 +58,6 @@ func (_q *ProvisionBucketQuery) Order(o ...provisionbucket.OrderOption) *Provisi return _q } -// QueryCurrency chains the current query on the "currency" edge. -func (_q *ProvisionBucketQuery) QueryCurrency() *FiatCurrencyQuery { - query := (&FiatCurrencyClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(provisionbucket.Table, provisionbucket.FieldID, selector), - sqlgraph.To(fiatcurrency.Table, fiatcurrency.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, provisionbucket.CurrencyTable, provisionbucket.CurrencyColumn), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// QueryPaymentOrders chains the current query on the "payment_orders" edge. -func (_q *ProvisionBucketQuery) QueryPaymentOrders() *PaymentOrderQuery { - query := (&PaymentOrderClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(provisionbucket.Table, provisionbucket.FieldID, selector), - sqlgraph.To(paymentorder.Table, paymentorder.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, provisionbucket.PaymentOrdersTable, provisionbucket.PaymentOrdersColumn), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// QueryProviderProfiles chains the current query on the "provider_profiles" edge. -func (_q *ProvisionBucketQuery) QueryProviderProfiles() *ProviderProfileQuery { - query := (&ProviderProfileClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(provisionbucket.Table, provisionbucket.FieldID, selector), - sqlgraph.To(providerprofile.Table, providerprofile.FieldID), - sqlgraph.Edge(sqlgraph.M2M, false, provisionbucket.ProviderProfilesTable, provisionbucket.ProviderProfilesPrimaryKey...), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - // First returns the first ProvisionBucket entity from the query. // Returns a *NotFoundError when no ProvisionBucket was found. func (_q *ProvisionBucketQuery) First(ctx context.Context) (*ProvisionBucket, error) { @@ -320,53 +245,17 @@ func (_q *ProvisionBucketQuery) Clone() *ProvisionBucketQuery { return nil } return &ProvisionBucketQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]provisionbucket.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.ProvisionBucket{}, _q.predicates...), - withCurrency: _q.withCurrency.Clone(), - withPaymentOrders: _q.withPaymentOrders.Clone(), - withProviderProfiles: _q.withProviderProfiles.Clone(), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]provisionbucket.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ProvisionBucket{}, _q.predicates...), // clone intermediate query. sql: _q.sql.Clone(), path: _q.path, } } -// WithCurrency tells the query-builder to eager-load the nodes that are connected to -// the "currency" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *ProvisionBucketQuery) WithCurrency(opts ...func(*FiatCurrencyQuery)) *ProvisionBucketQuery { - query := (&FiatCurrencyClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withCurrency = query - return _q -} - -// WithPaymentOrders tells the query-builder to eager-load the nodes that are connected to -// the "payment_orders" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *ProvisionBucketQuery) WithPaymentOrders(opts ...func(*PaymentOrderQuery)) *ProvisionBucketQuery { - query := (&PaymentOrderClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withPaymentOrders = query - return _q -} - -// WithProviderProfiles tells the query-builder to eager-load the nodes that are connected to -// the "provider_profiles" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *ProvisionBucketQuery) WithProviderProfiles(opts ...func(*ProviderProfileQuery)) *ProvisionBucketQuery { - query := (&ProviderProfileClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withProviderProfiles = query - return _q -} - // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -443,28 +332,15 @@ func (_q *ProvisionBucketQuery) prepareQuery(ctx context.Context) error { func (_q *ProvisionBucketQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ProvisionBucket, error) { var ( - nodes = []*ProvisionBucket{} - withFKs = _q.withFKs - _spec = _q.querySpec() - loadedTypes = [3]bool{ - _q.withCurrency != nil, - _q.withPaymentOrders != nil, - _q.withProviderProfiles != nil, - } + nodes = []*ProvisionBucket{} + _spec = _q.querySpec() ) - if _q.withCurrency != nil { - withFKs = true - } - if withFKs { - _spec.Node.Columns = append(_spec.Node.Columns, provisionbucket.ForeignKeys...) - } _spec.ScanValues = func(columns []string) ([]any, error) { return (*ProvisionBucket).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { node := &ProvisionBucket{config: _q.config} nodes = append(nodes, node) - node.Edges.loadedTypes = loadedTypes return node.assignValues(columns, values) } for i := range hooks { @@ -476,156 +352,9 @@ func (_q *ProvisionBucketQuery) sqlAll(ctx context.Context, hooks ...queryHook) if len(nodes) == 0 { return nodes, nil } - if query := _q.withCurrency; query != nil { - if err := _q.loadCurrency(ctx, query, nodes, nil, - func(n *ProvisionBucket, e *FiatCurrency) { n.Edges.Currency = e }); err != nil { - return nil, err - } - } - if query := _q.withPaymentOrders; query != nil { - if err := _q.loadPaymentOrders(ctx, query, nodes, - func(n *ProvisionBucket) { n.Edges.PaymentOrders = []*PaymentOrder{} }, - func(n *ProvisionBucket, e *PaymentOrder) { n.Edges.PaymentOrders = append(n.Edges.PaymentOrders, e) }); err != nil { - return nil, err - } - } - if query := _q.withProviderProfiles; query != nil { - if err := _q.loadProviderProfiles(ctx, query, nodes, - func(n *ProvisionBucket) { n.Edges.ProviderProfiles = []*ProviderProfile{} }, - func(n *ProvisionBucket, e *ProviderProfile) { - n.Edges.ProviderProfiles = append(n.Edges.ProviderProfiles, e) - }); err != nil { - return nil, err - } - } return nodes, nil } -func (_q *ProvisionBucketQuery) loadCurrency(ctx context.Context, query *FiatCurrencyQuery, nodes []*ProvisionBucket, init func(*ProvisionBucket), assign func(*ProvisionBucket, *FiatCurrency)) error { - ids := make([]uuid.UUID, 0, len(nodes)) - nodeids := make(map[uuid.UUID][]*ProvisionBucket) - for i := range nodes { - if nodes[i].fiat_currency_provision_buckets == nil { - continue - } - fk := *nodes[i].fiat_currency_provision_buckets - if _, ok := nodeids[fk]; !ok { - ids = append(ids, fk) - } - nodeids[fk] = append(nodeids[fk], nodes[i]) - } - if len(ids) == 0 { - return nil - } - query.Where(fiatcurrency.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return fmt.Errorf(`unexpected foreign-key "fiat_currency_provision_buckets" returned %v`, n.ID) - } - for i := range nodes { - assign(nodes[i], n) - } - } - return nil -} -func (_q *ProvisionBucketQuery) loadPaymentOrders(ctx context.Context, query *PaymentOrderQuery, nodes []*ProvisionBucket, init func(*ProvisionBucket), assign func(*ProvisionBucket, *PaymentOrder)) error { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[int]*ProvisionBucket) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] - if init != nil { - init(nodes[i]) - } - } - query.withFKs = true - query.Where(predicate.PaymentOrder(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(provisionbucket.PaymentOrdersColumn), fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - fk := n.provision_bucket_payment_orders - if fk == nil { - return fmt.Errorf(`foreign-key "provision_bucket_payment_orders" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "provision_bucket_payment_orders" returned %v for node %v`, *fk, n.ID) - } - assign(node, n) - } - return nil -} -func (_q *ProvisionBucketQuery) loadProviderProfiles(ctx context.Context, query *ProviderProfileQuery, nodes []*ProvisionBucket, init func(*ProvisionBucket), assign func(*ProvisionBucket, *ProviderProfile)) error { - edgeIDs := make([]driver.Value, len(nodes)) - byID := make(map[int]*ProvisionBucket) - nids := make(map[string]map[*ProvisionBucket]struct{}) - for i, node := range nodes { - edgeIDs[i] = node.ID - byID[node.ID] = node - if init != nil { - init(node) - } - } - query.Where(func(s *sql.Selector) { - joinT := sql.Table(provisionbucket.ProviderProfilesTable) - s.Join(joinT).On(s.C(providerprofile.FieldID), joinT.C(provisionbucket.ProviderProfilesPrimaryKey[1])) - s.Where(sql.InValues(joinT.C(provisionbucket.ProviderProfilesPrimaryKey[0]), edgeIDs...)) - columns := s.SelectedColumns() - s.Select(joinT.C(provisionbucket.ProviderProfilesPrimaryKey[0])) - s.AppendSelect(columns...) - s.SetDistinct(false) - }) - if err := query.prepareQuery(ctx); err != nil { - return err - } - qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { - return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { - assign := spec.Assign - values := spec.ScanValues - spec.ScanValues = func(columns []string) ([]any, error) { - values, err := values(columns[1:]) - if err != nil { - return nil, err - } - return append([]any{new(sql.NullInt64)}, values...), nil - } - spec.Assign = func(columns []string, values []any) error { - outValue := int(values[0].(*sql.NullInt64).Int64) - inValue := values[1].(*sql.NullString).String - if nids[inValue] == nil { - nids[inValue] = map[*ProvisionBucket]struct{}{byID[outValue]: {}} - return assign(columns[1:], values[1:]) - } - nids[inValue][byID[outValue]] = struct{}{} - return nil - } - }) - }) - neighbors, err := withInterceptors[[]*ProviderProfile](ctx, query, qr, query.inters) - if err != nil { - return err - } - for _, n := range neighbors { - nodes, ok := nids[n.ID] - if !ok { - return fmt.Errorf(`unexpected "provider_profiles" node returned %v`, n.ID) - } - for kn := range nodes { - assign(kn, n) - } - } - return nil -} - func (_q *ProvisionBucketQuery) sqlCount(ctx context.Context) (int, error) { _spec := _q.querySpec() _spec.Node.Columns = _q.ctx.Fields diff --git a/ent/provisionbucket_update.go b/ent/provisionbucket_update.go index 962166b80..bd7c3c185 100644 --- a/ent/provisionbucket_update.go +++ b/ent/provisionbucket_update.go @@ -11,10 +11,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/google/uuid" - "github.com/paycrest/aggregator/ent/fiatcurrency" - "github.com/paycrest/aggregator/ent/paymentorder" "github.com/paycrest/aggregator/ent/predicate" - "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/shopspring/decimal" ) @@ -74,45 +71,24 @@ func (_u *ProvisionBucketUpdate) AddMaxAmount(v decimal.Decimal) *ProvisionBucke return _u } -// SetCurrencyID sets the "currency" edge to the FiatCurrency entity by ID. -func (_u *ProvisionBucketUpdate) SetCurrencyID(id uuid.UUID) *ProvisionBucketUpdate { - _u.mutation.SetCurrencyID(id) +// SetFiatCurrencyID sets the "fiat_currency_id" field. +func (_u *ProvisionBucketUpdate) SetFiatCurrencyID(v uuid.UUID) *ProvisionBucketUpdate { + _u.mutation.SetFiatCurrencyID(v) return _u } -// SetCurrency sets the "currency" edge to the FiatCurrency entity. -func (_u *ProvisionBucketUpdate) SetCurrency(v *FiatCurrency) *ProvisionBucketUpdate { - return _u.SetCurrencyID(v.ID) -} - -// AddPaymentOrderIDs adds the "payment_orders" edge to the PaymentOrder entity by IDs. -func (_u *ProvisionBucketUpdate) AddPaymentOrderIDs(ids ...uuid.UUID) *ProvisionBucketUpdate { - _u.mutation.AddPaymentOrderIDs(ids...) - return _u -} - -// AddPaymentOrders adds the "payment_orders" edges to the PaymentOrder entity. -func (_u *ProvisionBucketUpdate) AddPaymentOrders(v ...*PaymentOrder) *ProvisionBucketUpdate { - ids := make([]uuid.UUID, len(v)) - for i := range v { - ids[i] = v[i].ID +// SetNillableFiatCurrencyID sets the "fiat_currency_id" field if the given value is not nil. +func (_u *ProvisionBucketUpdate) SetNillableFiatCurrencyID(v *uuid.UUID) *ProvisionBucketUpdate { + if v != nil { + _u.SetFiatCurrencyID(*v) } - return _u.AddPaymentOrderIDs(ids...) -} - -// AddProviderProfileIDs adds the "provider_profiles" edge to the ProviderProfile entity by IDs. -func (_u *ProvisionBucketUpdate) AddProviderProfileIDs(ids ...string) *ProvisionBucketUpdate { - _u.mutation.AddProviderProfileIDs(ids...) return _u } -// AddProviderProfiles adds the "provider_profiles" edges to the ProviderProfile entity. -func (_u *ProvisionBucketUpdate) AddProviderProfiles(v ...*ProviderProfile) *ProvisionBucketUpdate { - ids := make([]string, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddProviderProfileIDs(ids...) +// ClearFiatCurrencyID clears the value of the "fiat_currency_id" field. +func (_u *ProvisionBucketUpdate) ClearFiatCurrencyID() *ProvisionBucketUpdate { + _u.mutation.ClearFiatCurrencyID() + return _u } // Mutation returns the ProvisionBucketMutation object of the builder. @@ -120,54 +96,6 @@ func (_u *ProvisionBucketUpdate) Mutation() *ProvisionBucketMutation { return _u.mutation } -// ClearCurrency clears the "currency" edge to the FiatCurrency entity. -func (_u *ProvisionBucketUpdate) ClearCurrency() *ProvisionBucketUpdate { - _u.mutation.ClearCurrency() - return _u -} - -// ClearPaymentOrders clears all "payment_orders" edges to the PaymentOrder entity. -func (_u *ProvisionBucketUpdate) ClearPaymentOrders() *ProvisionBucketUpdate { - _u.mutation.ClearPaymentOrders() - return _u -} - -// RemovePaymentOrderIDs removes the "payment_orders" edge to PaymentOrder entities by IDs. -func (_u *ProvisionBucketUpdate) RemovePaymentOrderIDs(ids ...uuid.UUID) *ProvisionBucketUpdate { - _u.mutation.RemovePaymentOrderIDs(ids...) - return _u -} - -// RemovePaymentOrders removes "payment_orders" edges to PaymentOrder entities. -func (_u *ProvisionBucketUpdate) RemovePaymentOrders(v ...*PaymentOrder) *ProvisionBucketUpdate { - ids := make([]uuid.UUID, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemovePaymentOrderIDs(ids...) -} - -// ClearProviderProfiles clears all "provider_profiles" edges to the ProviderProfile entity. -func (_u *ProvisionBucketUpdate) ClearProviderProfiles() *ProvisionBucketUpdate { - _u.mutation.ClearProviderProfiles() - return _u -} - -// RemoveProviderProfileIDs removes the "provider_profiles" edge to ProviderProfile entities by IDs. -func (_u *ProvisionBucketUpdate) RemoveProviderProfileIDs(ids ...string) *ProvisionBucketUpdate { - _u.mutation.RemoveProviderProfileIDs(ids...) - return _u -} - -// RemoveProviderProfiles removes "provider_profiles" edges to ProviderProfile entities. -func (_u *ProvisionBucketUpdate) RemoveProviderProfiles(v ...*ProviderProfile) *ProvisionBucketUpdate { - ids := make([]string, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveProviderProfileIDs(ids...) -} - // Save executes the query and returns the number of nodes affected by the update operation. func (_u *ProvisionBucketUpdate) Save(ctx context.Context) (int, error) { return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) @@ -195,18 +123,7 @@ func (_u *ProvisionBucketUpdate) ExecX(ctx context.Context) { } } -// check runs all checks and user-defined validators on the builder. -func (_u *ProvisionBucketUpdate) check() error { - if _u.mutation.CurrencyCleared() && len(_u.mutation.CurrencyIDs()) > 0 { - return errors.New(`ent: clearing a required unique edge "ProvisionBucket.currency"`) - } - return nil -} - func (_u *ProvisionBucketUpdate) sqlSave(ctx context.Context) (_node int, err error) { - if err := _u.check(); err != nil { - return _node, err - } _spec := sqlgraph.NewUpdateSpec(provisionbucket.Table, provisionbucket.Columns, sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt)) if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { @@ -227,124 +144,11 @@ func (_u *ProvisionBucketUpdate) sqlSave(ctx context.Context) (_node int, err er if value, ok := _u.mutation.AddedMaxAmount(); ok { _spec.AddField(provisionbucket.FieldMaxAmount, field.TypeFloat64, value) } - if _u.mutation.CurrencyCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: provisionbucket.CurrencyTable, - Columns: []string{provisionbucket.CurrencyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(fiatcurrency.FieldID, field.TypeUUID), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.CurrencyIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: provisionbucket.CurrencyTable, - Columns: []string{provisionbucket.CurrencyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(fiatcurrency.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _u.mutation.PaymentOrdersCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: provisionbucket.PaymentOrdersTable, - Columns: []string{provisionbucket.PaymentOrdersColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + if value, ok := _u.mutation.FiatCurrencyID(); ok { + _spec.SetField(provisionbucket.FieldFiatCurrencyID, field.TypeUUID, value) } - if nodes := _u.mutation.RemovedPaymentOrdersIDs(); len(nodes) > 0 && !_u.mutation.PaymentOrdersCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: provisionbucket.PaymentOrdersTable, - Columns: []string{provisionbucket.PaymentOrdersColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.PaymentOrdersIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: provisionbucket.PaymentOrdersTable, - Columns: []string{provisionbucket.PaymentOrdersColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _u.mutation.ProviderProfilesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: provisionbucket.ProviderProfilesTable, - Columns: provisionbucket.ProviderProfilesPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(providerprofile.FieldID, field.TypeString), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedProviderProfilesIDs(); len(nodes) > 0 && !_u.mutation.ProviderProfilesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: provisionbucket.ProviderProfilesTable, - Columns: provisionbucket.ProviderProfilesPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(providerprofile.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.ProviderProfilesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: provisionbucket.ProviderProfilesTable, - Columns: provisionbucket.ProviderProfilesPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(providerprofile.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) + if _u.mutation.FiatCurrencyIDCleared() { + _spec.ClearField(provisionbucket.FieldFiatCurrencyID, field.TypeUUID) } if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { @@ -408,45 +212,24 @@ func (_u *ProvisionBucketUpdateOne) AddMaxAmount(v decimal.Decimal) *ProvisionBu return _u } -// SetCurrencyID sets the "currency" edge to the FiatCurrency entity by ID. -func (_u *ProvisionBucketUpdateOne) SetCurrencyID(id uuid.UUID) *ProvisionBucketUpdateOne { - _u.mutation.SetCurrencyID(id) +// SetFiatCurrencyID sets the "fiat_currency_id" field. +func (_u *ProvisionBucketUpdateOne) SetFiatCurrencyID(v uuid.UUID) *ProvisionBucketUpdateOne { + _u.mutation.SetFiatCurrencyID(v) return _u } -// SetCurrency sets the "currency" edge to the FiatCurrency entity. -func (_u *ProvisionBucketUpdateOne) SetCurrency(v *FiatCurrency) *ProvisionBucketUpdateOne { - return _u.SetCurrencyID(v.ID) -} - -// AddPaymentOrderIDs adds the "payment_orders" edge to the PaymentOrder entity by IDs. -func (_u *ProvisionBucketUpdateOne) AddPaymentOrderIDs(ids ...uuid.UUID) *ProvisionBucketUpdateOne { - _u.mutation.AddPaymentOrderIDs(ids...) - return _u -} - -// AddPaymentOrders adds the "payment_orders" edges to the PaymentOrder entity. -func (_u *ProvisionBucketUpdateOne) AddPaymentOrders(v ...*PaymentOrder) *ProvisionBucketUpdateOne { - ids := make([]uuid.UUID, len(v)) - for i := range v { - ids[i] = v[i].ID +// SetNillableFiatCurrencyID sets the "fiat_currency_id" field if the given value is not nil. +func (_u *ProvisionBucketUpdateOne) SetNillableFiatCurrencyID(v *uuid.UUID) *ProvisionBucketUpdateOne { + if v != nil { + _u.SetFiatCurrencyID(*v) } - return _u.AddPaymentOrderIDs(ids...) -} - -// AddProviderProfileIDs adds the "provider_profiles" edge to the ProviderProfile entity by IDs. -func (_u *ProvisionBucketUpdateOne) AddProviderProfileIDs(ids ...string) *ProvisionBucketUpdateOne { - _u.mutation.AddProviderProfileIDs(ids...) return _u } -// AddProviderProfiles adds the "provider_profiles" edges to the ProviderProfile entity. -func (_u *ProvisionBucketUpdateOne) AddProviderProfiles(v ...*ProviderProfile) *ProvisionBucketUpdateOne { - ids := make([]string, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddProviderProfileIDs(ids...) +// ClearFiatCurrencyID clears the value of the "fiat_currency_id" field. +func (_u *ProvisionBucketUpdateOne) ClearFiatCurrencyID() *ProvisionBucketUpdateOne { + _u.mutation.ClearFiatCurrencyID() + return _u } // Mutation returns the ProvisionBucketMutation object of the builder. @@ -454,54 +237,6 @@ func (_u *ProvisionBucketUpdateOne) Mutation() *ProvisionBucketMutation { return _u.mutation } -// ClearCurrency clears the "currency" edge to the FiatCurrency entity. -func (_u *ProvisionBucketUpdateOne) ClearCurrency() *ProvisionBucketUpdateOne { - _u.mutation.ClearCurrency() - return _u -} - -// ClearPaymentOrders clears all "payment_orders" edges to the PaymentOrder entity. -func (_u *ProvisionBucketUpdateOne) ClearPaymentOrders() *ProvisionBucketUpdateOne { - _u.mutation.ClearPaymentOrders() - return _u -} - -// RemovePaymentOrderIDs removes the "payment_orders" edge to PaymentOrder entities by IDs. -func (_u *ProvisionBucketUpdateOne) RemovePaymentOrderIDs(ids ...uuid.UUID) *ProvisionBucketUpdateOne { - _u.mutation.RemovePaymentOrderIDs(ids...) - return _u -} - -// RemovePaymentOrders removes "payment_orders" edges to PaymentOrder entities. -func (_u *ProvisionBucketUpdateOne) RemovePaymentOrders(v ...*PaymentOrder) *ProvisionBucketUpdateOne { - ids := make([]uuid.UUID, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemovePaymentOrderIDs(ids...) -} - -// ClearProviderProfiles clears all "provider_profiles" edges to the ProviderProfile entity. -func (_u *ProvisionBucketUpdateOne) ClearProviderProfiles() *ProvisionBucketUpdateOne { - _u.mutation.ClearProviderProfiles() - return _u -} - -// RemoveProviderProfileIDs removes the "provider_profiles" edge to ProviderProfile entities by IDs. -func (_u *ProvisionBucketUpdateOne) RemoveProviderProfileIDs(ids ...string) *ProvisionBucketUpdateOne { - _u.mutation.RemoveProviderProfileIDs(ids...) - return _u -} - -// RemoveProviderProfiles removes "provider_profiles" edges to ProviderProfile entities. -func (_u *ProvisionBucketUpdateOne) RemoveProviderProfiles(v ...*ProviderProfile) *ProvisionBucketUpdateOne { - ids := make([]string, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveProviderProfileIDs(ids...) -} - // Where appends a list predicates to the ProvisionBucketUpdate builder. func (_u *ProvisionBucketUpdateOne) Where(ps ...predicate.ProvisionBucket) *ProvisionBucketUpdateOne { _u.mutation.Where(ps...) @@ -542,18 +277,7 @@ func (_u *ProvisionBucketUpdateOne) ExecX(ctx context.Context) { } } -// check runs all checks and user-defined validators on the builder. -func (_u *ProvisionBucketUpdateOne) check() error { - if _u.mutation.CurrencyCleared() && len(_u.mutation.CurrencyIDs()) > 0 { - return errors.New(`ent: clearing a required unique edge "ProvisionBucket.currency"`) - } - return nil -} - func (_u *ProvisionBucketUpdateOne) sqlSave(ctx context.Context) (_node *ProvisionBucket, err error) { - if err := _u.check(); err != nil { - return _node, err - } _spec := sqlgraph.NewUpdateSpec(provisionbucket.Table, provisionbucket.Columns, sqlgraph.NewFieldSpec(provisionbucket.FieldID, field.TypeInt)) id, ok := _u.mutation.ID() if !ok { @@ -591,124 +315,11 @@ func (_u *ProvisionBucketUpdateOne) sqlSave(ctx context.Context) (_node *Provisi if value, ok := _u.mutation.AddedMaxAmount(); ok { _spec.AddField(provisionbucket.FieldMaxAmount, field.TypeFloat64, value) } - if _u.mutation.CurrencyCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: provisionbucket.CurrencyTable, - Columns: []string{provisionbucket.CurrencyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(fiatcurrency.FieldID, field.TypeUUID), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.CurrencyIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: provisionbucket.CurrencyTable, - Columns: []string{provisionbucket.CurrencyColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(fiatcurrency.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _u.mutation.PaymentOrdersCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: provisionbucket.PaymentOrdersTable, - Columns: []string{provisionbucket.PaymentOrdersColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + if value, ok := _u.mutation.FiatCurrencyID(); ok { + _spec.SetField(provisionbucket.FieldFiatCurrencyID, field.TypeUUID, value) } - if nodes := _u.mutation.RemovedPaymentOrdersIDs(); len(nodes) > 0 && !_u.mutation.PaymentOrdersCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: provisionbucket.PaymentOrdersTable, - Columns: []string{provisionbucket.PaymentOrdersColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.PaymentOrdersIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: provisionbucket.PaymentOrdersTable, - Columns: []string{provisionbucket.PaymentOrdersColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(paymentorder.FieldID, field.TypeUUID), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _u.mutation.ProviderProfilesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: provisionbucket.ProviderProfilesTable, - Columns: provisionbucket.ProviderProfilesPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(providerprofile.FieldID, field.TypeString), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedProviderProfilesIDs(); len(nodes) > 0 && !_u.mutation.ProviderProfilesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: provisionbucket.ProviderProfilesTable, - Columns: provisionbucket.ProviderProfilesPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(providerprofile.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.ProviderProfilesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2M, - Inverse: false, - Table: provisionbucket.ProviderProfilesTable, - Columns: provisionbucket.ProviderProfilesPrimaryKey, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(providerprofile.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) + if _u.mutation.FiatCurrencyIDCleared() { + _spec.ClearField(provisionbucket.FieldFiatCurrencyID, field.TypeUUID) } _node = &ProvisionBucket{config: _u.config} _spec.Assign = _node.assignValues diff --git a/ent/runtime/runtime.go b/ent/runtime/runtime.go index 5ae00bfc6..f07d781c6 100644 --- a/ent/runtime/runtime.go +++ b/ent/runtime/runtime.go @@ -16,9 +16,11 @@ import ( "github.com/paycrest/aggregator/ent/paymentorder" "github.com/paycrest/aggregator/ent/paymentorderfulfillment" "github.com/paycrest/aggregator/ent/paymentwebhook" + "github.com/paycrest/aggregator/ent/providerassignmentrun" "github.com/paycrest/aggregator/ent/providerbalances" "github.com/paycrest/aggregator/ent/providerfiataccount" "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerordertokenscorehistory" "github.com/paycrest/aggregator/ent/providerprofile" "github.com/paycrest/aggregator/ent/providerrating" "github.com/paycrest/aggregator/ent/provisionbucket" @@ -364,6 +366,32 @@ func init() { paymentwebhookDescID := paymentwebhookFields[0].Descriptor() // paymentwebhook.DefaultID holds the default value on creation for the id field. paymentwebhook.DefaultID = paymentwebhookDescID.Default.(func() uuid.UUID) + providerassignmentrunFields := schema.ProviderAssignmentRun{}.Fields() + _ = providerassignmentrunFields + // providerassignmentrunDescAssignedProviderID is the schema descriptor for assigned_provider_id field. + providerassignmentrunDescAssignedProviderID := providerassignmentrunFields[1].Descriptor() + // providerassignmentrun.AssignedProviderIDValidator is a validator for the "assigned_provider_id" field. It is called by the builders before save. + providerassignmentrun.AssignedProviderIDValidator = providerassignmentrunDescAssignedProviderID.Validators[0].(func(string) error) + // providerassignmentrunDescAttemptedAt is the schema descriptor for attempted_at field. + providerassignmentrunDescAttemptedAt := providerassignmentrunFields[2].Descriptor() + // providerassignmentrun.DefaultAttemptedAt holds the default value on creation for the attempted_at field. + providerassignmentrun.DefaultAttemptedAt = providerassignmentrunDescAttemptedAt.Default.(func() time.Time) + // providerassignmentrunDescTrigger is the schema descriptor for trigger field. + providerassignmentrunDescTrigger := providerassignmentrunFields[3].Descriptor() + // providerassignmentrun.TriggerValidator is a validator for the "trigger" field. It is called by the builders before save. + providerassignmentrun.TriggerValidator = providerassignmentrunDescTrigger.Validators[0].(func(string) error) + // providerassignmentrunDescResult is the schema descriptor for result field. + providerassignmentrunDescResult := providerassignmentrunFields[4].Descriptor() + // providerassignmentrun.ResultValidator is a validator for the "result" field. It is called by the builders before save. + providerassignmentrun.ResultValidator = providerassignmentrunDescResult.Validators[0].(func(string) error) + // providerassignmentrunDescUsedFallback is the schema descriptor for used_fallback field. + providerassignmentrunDescUsedFallback := providerassignmentrunFields[5].Descriptor() + // providerassignmentrun.DefaultUsedFallback holds the default value on creation for the used_fallback field. + providerassignmentrun.DefaultUsedFallback = providerassignmentrunDescUsedFallback.Default.(bool) + // providerassignmentrunDescID is the schema descriptor for id field. + providerassignmentrunDescID := providerassignmentrunFields[0].Descriptor() + // providerassignmentrun.DefaultID holds the default value on creation for the id field. + providerassignmentrun.DefaultID = providerassignmentrunDescID.Default.(func() uuid.UUID) providerbalancesFields := schema.ProviderBalances{}.Fields() _ = providerbalancesFields // providerbalancesDescAvailableBalance is the schema descriptor for available_balance field. @@ -484,6 +512,35 @@ func init() { providerordertoken.DefaultUpdatedAt = providerordertokenDescUpdatedAt.Default.(func() time.Time) // providerordertoken.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. providerordertoken.UpdateDefaultUpdatedAt = providerordertokenDescUpdatedAt.UpdateDefault.(func() time.Time) + // providerordertokenDescScore is the schema descriptor for score field. + providerordertokenDescScore := providerordertokenFields[12].Descriptor() + // providerordertoken.DefaultScore holds the default value on creation for the score field. + providerordertoken.DefaultScore = providerordertokenDescScore.Default.(func() decimal.Decimal) + providerordertokenscorehistoryMixin := schema.ProviderOrderTokenScoreHistory{}.Mixin() + providerordertokenscorehistoryHooks := schema.ProviderOrderTokenScoreHistory{}.Hooks() + providerordertokenscorehistory.Hooks[0] = providerordertokenscorehistoryHooks[0] + providerordertokenscorehistoryMixinFields0 := providerordertokenscorehistoryMixin[0].Fields() + _ = providerordertokenscorehistoryMixinFields0 + providerordertokenscorehistoryFields := schema.ProviderOrderTokenScoreHistory{}.Fields() + _ = providerordertokenscorehistoryFields + // providerordertokenscorehistoryDescCreatedAt is the schema descriptor for created_at field. + providerordertokenscorehistoryDescCreatedAt := providerordertokenscorehistoryMixinFields0[0].Descriptor() + // providerordertokenscorehistory.DefaultCreatedAt holds the default value on creation for the created_at field. + providerordertokenscorehistory.DefaultCreatedAt = providerordertokenscorehistoryDescCreatedAt.Default.(func() time.Time) + // providerordertokenscorehistoryDescUpdatedAt is the schema descriptor for updated_at field. + providerordertokenscorehistoryDescUpdatedAt := providerordertokenscorehistoryMixinFields0[1].Descriptor() + // providerordertokenscorehistory.DefaultUpdatedAt holds the default value on creation for the updated_at field. + providerordertokenscorehistory.DefaultUpdatedAt = providerordertokenscorehistoryDescUpdatedAt.Default.(func() time.Time) + // providerordertokenscorehistory.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + providerordertokenscorehistory.UpdateDefaultUpdatedAt = providerordertokenscorehistoryDescUpdatedAt.UpdateDefault.(func() time.Time) + // providerordertokenscorehistoryDescEventType is the schema descriptor for event_type field. + providerordertokenscorehistoryDescEventType := providerordertokenscorehistoryFields[1].Descriptor() + // providerordertokenscorehistory.EventTypeValidator is a validator for the "event_type" field. It is called by the builders before save. + providerordertokenscorehistory.EventTypeValidator = providerordertokenscorehistoryDescEventType.Validators[0].(func(string) error) + // providerordertokenscorehistoryDescID is the schema descriptor for id field. + providerordertokenscorehistoryDescID := providerordertokenscorehistoryFields[0].Descriptor() + // providerordertokenscorehistory.DefaultID holds the default value on creation for the id field. + providerordertokenscorehistory.DefaultID = providerordertokenscorehistoryDescID.Default.(func() uuid.UUID) providerprofileFields := schema.ProviderProfile{}.Fields() _ = providerprofileFields // providerprofileDescTradingName is the schema descriptor for trading_name field. @@ -705,6 +762,6 @@ func init() { } const ( - Version = "v0.14.5" // Version of ent codegen. - Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen. + Version = "v0.14.6" // Version of ent codegen. + Sum = "h1:/f2696BpwuWAEEG6PVGWflg6+Inrpq4pRWuNlWz/Skk=" // Sum of ent codegen. ) diff --git a/ent/schema/fiatcurrency.go b/ent/schema/fiatcurrency.go index c1de49dcf..4a35f45a6 100644 --- a/ent/schema/fiatcurrency.go +++ b/ent/schema/fiatcurrency.go @@ -46,8 +46,6 @@ func (FiatCurrency) Edges() []ent.Edge { return []ent.Edge{ edge.To("provider_balances", ProviderBalances.Type). Annotations(entsql.OnDelete(entsql.Cascade)), - edge.To("provision_buckets", ProvisionBucket.Type). - Annotations(entsql.OnDelete(entsql.Cascade)), edge.To("institutions", Institution.Type), edge.To("provider_order_tokens", ProviderOrderToken.Type). Annotations(entsql.OnDelete(entsql.Cascade)), diff --git a/ent/schema/paymentorder.go b/ent/schema/paymentorder.go index ef14338ea..066db1453 100644 --- a/ent/schema/paymentorder.go +++ b/ent/schema/paymentorder.go @@ -122,6 +122,20 @@ func (PaymentOrder) Fields() []ent.Field { // Fallback assignment: set when order was assigned via fallback provider (DB-level idempotency). field.Time("fallback_tried_at"). Optional(), + // Persisted assignment market snapshot (floating-rate determinism across retries). + field.Float("assignment_market_buy_rate"). + GoType(decimal.Decimal{}). + Optional(). + Nillable(), + field.Float("assignment_market_sell_rate"). + GoType(decimal.Decimal{}). + Optional(). + Nillable(), + // Legacy bucket FK (no Ent edge in Phase 1; column retained until Phase 2 table drop). + field.Int("legacy_provision_bucket_id"). + Optional(). + Nillable(). + StorageKey("provision_bucket_payment_orders"), } } @@ -140,12 +154,13 @@ func (PaymentOrder) Edges() []ent.Edge { edge.From("provider", ProviderProfile.Type). Ref("assigned_orders"). Unique(), - edge.From("provision_bucket", ProvisionBucket.Type). - Ref("payment_orders"). - Unique(), edge.To("fulfillments", PaymentOrderFulfillment.Type). Annotations(entsql.OnDelete(entsql.Cascade)), edge.To("transactions", TransactionLog.Type), + edge.To("provider_assignment_runs", ProviderAssignmentRun.Type). + Annotations(entsql.OnDelete(entsql.Cascade)), + edge.To("provider_order_token_score_histories", ProviderOrderTokenScoreHistory.Type). + Annotations(entsql.OnDelete(entsql.Cascade)), } } diff --git a/ent/schema/providerassignmentrun.go b/ent/schema/providerassignmentrun.go new file mode 100644 index 000000000..e934899f2 --- /dev/null +++ b/ent/schema/providerassignmentrun.go @@ -0,0 +1,50 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" + "github.com/shopspring/decimal" +) + +// ProviderAssignmentRun records one assignment attempt for audit. FKs cascade on payment_order / provider_order_token delete. +type ProviderAssignmentRun struct { + ent.Schema +} + +func (ProviderAssignmentRun) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New), + field.String("assigned_provider_id").MaxLen(255).Optional().Nillable(), + field.Time("attempted_at").Default(time.Now), + field.String("trigger").MaxLen(64), + field.String("result").MaxLen(32), + field.Bool("used_fallback").Default(false), + field.Float("market_buy_rate_snapshot").GoType(decimal.Decimal{}).Optional().Nillable(), + field.Float("market_sell_rate_snapshot").GoType(decimal.Decimal{}).Optional().Nillable(), + field.Text("error_message").Optional().Nillable(), + } +} + +func (ProviderAssignmentRun) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("payment_order", PaymentOrder.Type). + Ref("provider_assignment_runs"). + Unique(). + Required(), + edge.From("provider_order_token", ProviderOrderToken.Type). + Ref("assignment_runs"). + Unique(), + } +} + +func (ProviderAssignmentRun) Indexes() []ent.Index { + return []ent.Index{ + index.Edges("payment_order"), + index.Edges("provider_order_token"), + } +} diff --git a/ent/schema/providerordertoken.go b/ent/schema/providerordertoken.go index db003c042..d1cc65922 100644 --- a/ent/schema/providerordertoken.go +++ b/ent/schema/providerordertoken.go @@ -2,6 +2,7 @@ package schema import ( "entgo.io/ent" + "entgo.io/ent/dialect/entsql" "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" "entgo.io/ent/schema/index" @@ -48,6 +49,10 @@ func (ProviderOrderToken) Fields() []ent.Field { field.String("settlement_address").Optional(), field.String("payout_address").Optional(), field.String("network"), + field.Float("score"). + GoType(decimal.Decimal{}). + DefaultFunc(func() decimal.Decimal { return decimal.Zero }), + field.Time("last_order_assigned_at").Optional().Nillable(), } } @@ -66,6 +71,10 @@ func (ProviderOrderToken) Edges() []ent.Edge { Ref("provider_order_tokens"). Required(). Unique(), + edge.To("score_histories", ProviderOrderTokenScoreHistory.Type). + Annotations(entsql.OnDelete(entsql.Cascade)), + edge.To("assignment_runs", ProviderAssignmentRun.Type). + Annotations(entsql.OnDelete(entsql.Cascade)), } } diff --git a/ent/schema/providerordertokenscorehistory.go b/ent/schema/providerordertokenscorehistory.go new file mode 100644 index 000000000..0fec84f39 --- /dev/null +++ b/ent/schema/providerordertokenscorehistory.go @@ -0,0 +1,67 @@ +package schema + +import ( + "context" + "fmt" + + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + gen "github.com/paycrest/aggregator/ent" + "github.com/paycrest/aggregator/ent/hook" + "github.com/google/uuid" + "github.com/shopspring/decimal" +) + +// ProviderOrderTokenScoreHistory is append-only; unique (payment_order edge + event_type) enforces idempotent scoring. +// FKs cascade: deleting a payment_order or provider_order_token removes related score history rows. +type ProviderOrderTokenScoreHistory struct { + ent.Schema +} + +func (ProviderOrderTokenScoreHistory) Mixin() []ent.Mixin { + return []ent.Mixin{TimeMixin{}} +} + +func (ProviderOrderTokenScoreHistory) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New).Immutable(), + field.String("event_type").MaxLen(64).Immutable(), + field.Float("delta").GoType(decimal.Decimal{}).Immutable(), + } +} + +func (ProviderOrderTokenScoreHistory) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("payment_order", PaymentOrder.Type). + Ref("provider_order_token_score_histories"). + Unique(). + Required(), + edge.From("provider_order_token", ProviderOrderToken.Type). + Ref("score_histories"). + Unique(). + Required(), + } +} + +func (ProviderOrderTokenScoreHistory) Indexes() []ent.Index { + return []ent.Index{ + index.Edges("payment_order").Fields("event_type").Unique(), + index.Edges("payment_order"), + index.Edges("provider_order_token"), + } +} + +func (ProviderOrderTokenScoreHistory) Hooks() []ent.Hook { + return []ent.Hook{ + hook.On( + func(next ent.Mutator) ent.Mutator { + return hook.ProviderOrderTokenScoreHistoryFunc(func(_ context.Context, m *gen.ProviderOrderTokenScoreHistoryMutation) (ent.Value, error) { + return nil, fmt.Errorf("provider_order_token_score_histories is append-only: updates are not allowed") + }) + }, + ent.OpUpdate|ent.OpUpdateOne, + ), + } +} diff --git a/ent/schema/providerprofile.go b/ent/schema/providerprofile.go index 1571e3a60..67e663c13 100644 --- a/ent/schema/providerprofile.go +++ b/ent/schema/providerprofile.go @@ -52,8 +52,6 @@ func (ProviderProfile) Edges() []ent.Edge { Annotations(entsql.OnDelete(entsql.Cascade)), edge.To("provider_balances", ProviderBalances.Type). Annotations(entsql.OnDelete(entsql.Cascade)), - edge.From("provision_buckets", ProvisionBucket.Type). - Ref("provider_profiles"), edge.To("order_tokens", ProviderOrderToken.Type). Annotations(entsql.OnDelete(entsql.Cascade)), edge.To("provider_rating", ProviderRating.Type). diff --git a/ent/schema/provisionbucket.go b/ent/schema/provisionbucket.go index 342915fd8..c73125418 100644 --- a/ent/schema/provisionbucket.go +++ b/ent/schema/provisionbucket.go @@ -4,18 +4,16 @@ import ( "time" "entgo.io/ent" - "entgo.io/ent/dialect/entsql" - "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" + "github.com/google/uuid" "github.com/shopspring/decimal" ) -// ProvisionBucket holds the schema definition for the ProvisionBucket entity. +// ProvisionBucket is legacy; Phase 1 removes all Ent edges. Table/columns may remain until Phase 2 migration. type ProvisionBucket struct { ent.Schema } -// Fields of the ProvisionBucket. func (ProvisionBucket) Fields() []ent.Field { return []ent.Field{ field.Float("min_amount"). @@ -25,18 +23,13 @@ func (ProvisionBucket) Fields() []ent.Field { field.Time("created_at"). Immutable(). Default(time.Now), + field.UUID("fiat_currency_id", uuid.UUID{}). + Optional(). + Nillable(). + StorageKey("fiat_currency_provision_buckets"), } } -// Edges of the ProvisionBucket. func (ProvisionBucket) Edges() []ent.Edge { - return []ent.Edge{ - edge.From("currency", FiatCurrency.Type). - Ref("provision_buckets"). - Unique(). - Required(), - edge.To("payment_orders", PaymentOrder.Type). - Annotations(entsql.OnDelete(entsql.SetNull)), - edge.To("provider_profiles", ProviderProfile.Type), - } + return nil } diff --git a/ent/tx.go b/ent/tx.go index 445f87437..900bc4f53 100644 --- a/ent/tx.go +++ b/ent/tx.go @@ -32,12 +32,16 @@ type Tx struct { PaymentOrderFulfillment *PaymentOrderFulfillmentClient // PaymentWebhook is the client for interacting with the PaymentWebhook builders. PaymentWebhook *PaymentWebhookClient + // ProviderAssignmentRun is the client for interacting with the ProviderAssignmentRun builders. + ProviderAssignmentRun *ProviderAssignmentRunClient // ProviderBalances is the client for interacting with the ProviderBalances builders. ProviderBalances *ProviderBalancesClient // ProviderFiatAccount is the client for interacting with the ProviderFiatAccount builders. ProviderFiatAccount *ProviderFiatAccountClient // ProviderOrderToken is the client for interacting with the ProviderOrderToken builders. ProviderOrderToken *ProviderOrderTokenClient + // ProviderOrderTokenScoreHistory is the client for interacting with the ProviderOrderTokenScoreHistory builders. + ProviderOrderTokenScoreHistory *ProviderOrderTokenScoreHistoryClient // ProviderProfile is the client for interacting with the ProviderProfile builders. ProviderProfile *ProviderProfileClient // ProviderRating is the client for interacting with the ProviderRating builders. @@ -199,9 +203,11 @@ func (tx *Tx) init() { tx.PaymentOrder = NewPaymentOrderClient(tx.config) tx.PaymentOrderFulfillment = NewPaymentOrderFulfillmentClient(tx.config) tx.PaymentWebhook = NewPaymentWebhookClient(tx.config) + tx.ProviderAssignmentRun = NewProviderAssignmentRunClient(tx.config) tx.ProviderBalances = NewProviderBalancesClient(tx.config) tx.ProviderFiatAccount = NewProviderFiatAccountClient(tx.config) tx.ProviderOrderToken = NewProviderOrderTokenClient(tx.config) + tx.ProviderOrderTokenScoreHistory = NewProviderOrderTokenScoreHistoryClient(tx.config) tx.ProviderProfile = NewProviderProfileClient(tx.config) tx.ProviderRating = NewProviderRatingClient(tx.config) tx.ProvisionBucket = NewProvisionBucketClient(tx.config) diff --git a/services/assignment/assign.go b/services/assignment/assign.go new file mode 100644 index 000000000..95cb028df --- /dev/null +++ b/services/assignment/assign.go @@ -0,0 +1,823 @@ +package assignment + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + + "github.com/paycrest/aggregator/config" + "github.com/paycrest/aggregator/ent" + "github.com/paycrest/aggregator/ent/fiatcurrency" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/paymentorderfulfillment" + "github.com/paycrest/aggregator/ent/providerbalances" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerprofile" + "github.com/paycrest/aggregator/ent/token" + "github.com/paycrest/aggregator/storage" + "github.com/paycrest/aggregator/types" + "github.com/paycrest/aggregator/utils" + "github.com/paycrest/aggregator/utils/logger" + "github.com/shopspring/decimal" +) + +// ErrAssignmentLockHeld means another goroutine holds the Redis assignment lock for this order. +var ErrAssignmentLockHeld = errors.New("assignment lock held") + +func assignmentLockKey(orderID uuid.UUID) string { + return fmt.Sprintf("order_assign_lock_%s", orderID.String()) +} + +// acquireOrderAssignmentLock serializes sendOrderRequest / OTC Redis writes per order ID. +func acquireOrderAssignmentLock(ctx context.Context, orderID uuid.UUID) (release func(), err error) { + key := assignmentLockKey(orderID) + ok, e := storage.RedisClient.SetNX(ctx, key, "1", orderAssignLockTTL).Result() + if e != nil { + return nil, fmt.Errorf("redis SetNX: %w", e) + } + if !ok { + return nil, ErrAssignmentLockHeld + } + return func() { + if delErr := storage.RedisClient.Del(ctx, key).Err(); delErr != nil { + logger.WithFields(logger.Fields{"OrderID": orderID.String(), "Error": delErr.Error()}).Warnf("assign: failed to release assignment lock") + } + }, nil +} + +// resolveOrderRequestRedisConflict handles duplicate / concurrent paths when the assign lock is not free. +func resolveOrderRequestRedisConflict(ctx context.Context, order types.PaymentOrderFields, orderKey string) error { + exists, err := storage.RedisClient.Exists(ctx, orderKey).Result() + if err != nil { + return fmt.Errorf("redis Exists: %w", err) + } + if exists == 0 { + return fmt.Errorf("%w: order_request not ready yet", ErrAssignmentLockHeld) + } + existingProviderID, hErr := storage.RedisClient.HGet(ctx, orderKey, "providerId").Result() + if hErr == nil && existingProviderID == order.ProviderID { + logger.WithFields(logger.Fields{ + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "OrderKey": orderKey, + }).Errorf("Order request already exists in Redis - skipping duplicate notification") + return nil + } + if hErr == nil && existingProviderID != order.ProviderID { + logger.WithFields(logger.Fields{ + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "ExistingProviderID": existingProviderID, + "OrderKey": orderKey, + }).Errorf("Order request exists for different provider - potential race condition") + return fmt.Errorf("order request exists for different provider") + } + return fmt.Errorf("%w: could not read providerId from order_request", ErrAssignmentLockHeld) +} + +// resolveConcurrentAssignmentStart handles AcquireNX failure at the start of AssignPaymentOrderWithTrigger +// when another goroutine already holds the assignment lock or has finished writing order_request. +func resolveConcurrentAssignmentStart(ctx context.Context, order types.PaymentOrderFields, orderKey string) error { + exists, err := storage.RedisClient.Exists(ctx, orderKey).Result() + if err != nil { + return fmt.Errorf("redis Exists: %w", err) + } + if exists > 0 { + if order.ProviderID != "" { + return resolveOrderRequestRedisConflict(ctx, order, orderKey) + } + return nil + } + return fmt.Errorf("%w: assignment in progress for order", ErrAssignmentLockHeld) +} + +// AssignPaymentOrder assigns a payment order to a provider using DB-only selection. +func (s *Service) AssignPaymentOrder(ctx context.Context, order types.PaymentOrderFields) error { + return s.AssignPaymentOrderWithTrigger(ctx, order, AssignmentTriggerInitial) +} + +// TryFallbackAssignment attempts to assign the order to the configured fallback provider using only +// rate and balance checks. Returns a clear error if the fallback provider's rate is outside slippage. +// When assignmentLockHeld is true, the caller already holds order_assign_lock_{orderID} (e.g. AssignPaymentOrderWithTrigger). +func (s *Service) TryFallbackAssignment(ctx context.Context, order *ent.PaymentOrder, assignmentLockHeld bool) error { + orderConf := config.OrderConfig() + fallbackID := orderConf.FallbackProviderID + if fallbackID == "" { + return fmt.Errorf("fallback provider not configured") + } + if order.OrderType == paymentorder.OrderTypeOtc { + return fmt.Errorf("fallback is only for regular orders, not OTC") + } + + orderKey := fmt.Sprintf("order_request_%s", order.ID) + exists, err := storage.RedisClient.Exists(ctx, orderKey).Result() + if err != nil { + return fmt.Errorf("fallback: failed to check order_request: %w", err) + } + if exists > 0 { + return fmt.Errorf("fallback: order %s already has an active order_request", order.ID) + } + + currentOrder, err := storage.Client.PaymentOrder.Query(). + Where(paymentorder.IDEQ(order.ID)). + Only(ctx) + if err != nil { + return fmt.Errorf("fallback: failed to load order: %w", err) + } + if !currentOrder.FallbackTriedAt.IsZero() { + return fmt.Errorf("fallback: order %s already had fallback assignment tried", order.ID) + } + assignable := currentOrder.Status == paymentorder.StatusPending || currentOrder.Status == paymentorder.StatusCancelled + if currentOrder.Status == paymentorder.StatusFulfilled { + tx, txErr := storage.Client.Tx(ctx) + if txErr != nil { + return fmt.Errorf("fallback: failed to start transaction for order %s: %w", order.ID, txErr) + } + deleted, delErr := tx.PaymentOrderFulfillment.Delete(). + Where( + paymentorderfulfillment.HasOrderWith(paymentorder.IDEQ(order.ID)), + paymentorderfulfillment.ValidationStatusEQ(paymentorderfulfillment.ValidationStatusFailed), + ).Exec(ctx) + if delErr != nil { + _ = tx.Rollback() + return fmt.Errorf("fallback: failed to delete fulfillments for order %s: %w", order.ID, delErr) + } + if deleted == 0 { + _ = tx.Rollback() + return fmt.Errorf("fallback: order %s is fulfilled with no failed fulfillments, not assignable", order.ID) + } + if _, updErr := tx.PaymentOrder.UpdateOneID(order.ID). + ClearProvider(). + SetStatus(paymentorder.StatusPending). + Save(ctx); updErr != nil { + _ = tx.Rollback() + return fmt.Errorf("fallback: failed to reset order %s to Pending after deleting fulfillments: %w", order.ID, updErr) + } + if commitErr := tx.Commit(); commitErr != nil { + return fmt.Errorf("fallback: failed to commit transaction for order %s: %w", order.ID, commitErr) + } + assignable = true + } + if !assignable { + return fmt.Errorf("fallback: order %s is in state %s, not assignable", order.ID, currentOrder.Status) + } + + if order.AccountIdentifier == "" || order.Institution == "" || order.AccountName == "" { + return fmt.Errorf("fallback: order %s has no recipient information", order.ID.String()) + } + fields := types.PaymentOrderFields{ + ID: order.ID, + OrderType: order.OrderType.String(), + Token: order.Edges.Token, + Network: nil, + GatewayID: order.GatewayID, + Amount: order.Amount, + Rate: order.Rate, + Institution: order.Institution, + AccountIdentifier: order.AccountIdentifier, + AccountName: order.AccountName, + ProviderID: "", + MessageHash: order.MessageHash, + Memo: order.Memo, + UpdatedAt: order.UpdatedAt, + CreatedAt: order.CreatedAt, + } + if order.Edges.Token != nil && order.Edges.Token.Edges.Network != nil { + fields.Network = order.Edges.Token.Edges.Network + } + if fields.Token == nil { + return fmt.Errorf("fallback: order %s has no token", order.ID.String()) + } + + institution, instErr := utils.GetInstitutionByCode(ctx, order.Institution, true) + if instErr != nil { + return fmt.Errorf("fallback: institution lookup failed for order %s: %w", fields.ID.String(), instErr) + } + if institution.Edges.FiatCurrency == nil { + return fmt.Errorf("fallback: institution %s has no fiat currency for order %s", order.Institution, fields.ID.String()) + } + bucketCurrency := institution.Edges.FiatCurrency + + if orderConf.ProviderStuckFulfillmentThreshold > 0 { + stuckCount, errStuck := utils.GetProviderStuckOrderCount(ctx, fallbackID) + if errStuck == nil && stuckCount >= orderConf.ProviderStuckFulfillmentThreshold { + return &types.ErrNoProviderDueToStuck{CurrencyCode: bucketCurrency.Code} + } + if errStuck != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", errStuck), + "FallbackID": fallbackID, + "Currency": bucketCurrency.Code, + }).Errorf("fallback: failed to get stuck order count, proceeding with assignment (fail-open)") + } + } + + provider, err := storage.Client.ProviderProfile.Get(ctx, fallbackID) + if err != nil { + if ent.IsNotFound(err) { + return fmt.Errorf("fallback provider %s not found", fallbackID) + } + return fmt.Errorf("failed to get fallback provider: %w", err) + } + + network := fields.Token.Edges.Network + if network == nil { + var nErr error + network, nErr = fields.Token.QueryNetwork().Only(ctx) + if nErr != nil { + return fmt.Errorf("fallback: token missing network: %w", nErr) + } + } + + providerToken, err := storage.Client.ProviderOrderToken. + Query(). + Where( + providerordertoken.NetworkEQ(network.Identifier), + providerordertoken.HasProviderWith( + providerprofile.IDEQ(fallbackID), + providerprofile.HasProviderBalancesWith( + providerbalances.HasFiatCurrencyWith(fiatcurrency.CodeEQ(bucketCurrency.Code)), + providerbalances.IsAvailableEQ(true), + ), + ), + providerordertoken.HasTokenWith(token.IDEQ(fields.Token.ID)), + providerordertoken.HasCurrencyWith(fiatcurrency.CodeEQ(bucketCurrency.Code)), + providerordertoken.SettlementAddressNEQ(""), + ). + First(ctx) + if err != nil { + if ent.IsNotFound(err) { + return fmt.Errorf("fallback provider %s has no order token for %s/%s/%s", fallbackID, fields.Token.Symbol, network.Identifier, bucketCurrency.Code) + } + return fmt.Errorf("fallback: failed to get provider order token: %w", err) + } + + providerRate, err := s.GetProviderRate(ctx, provider, fields.Token.Symbol, bucketCurrency.Code, RateSideSell) + if err != nil { + return fmt.Errorf("fallback: failed to get provider rate: %w", err) + } + allowedDeviation := fields.Rate.Mul(providerToken.RateSlippage.Div(decimal.NewFromInt(100))) + if providerRate.Sub(fields.Rate).Abs().GreaterThan(allowedDeviation) { + logger.WithFields(logger.Fields{ + "OrderID": fields.ID.String(), + "FallbackID": fallbackID, + "OrderRate": fields.Rate.String(), + "ProviderRate": providerRate.String(), + "SlippagePct": providerToken.RateSlippage.String(), + }).Errorf("[FALLBACK_ASSIGNMENT] fallback assignment attempted but order rate is too far from what fallback node can fulfill") + return fmt.Errorf("fallback assignment attempted for order %s but order rate is too far from what fallback provider %s can fulfill (provider rate %s, order rate %s, allowed slippage %s%%)", + fields.ID.String(), fallbackID, providerRate.String(), fields.Rate.String(), providerToken.RateSlippage.String()) + } + + bal, err := s.balanceService.GetProviderFiatBalance(ctx, fallbackID, bucketCurrency.Code) + if err != nil { + return fmt.Errorf("fallback: failed to get provider balance: %w", err) + } + if !s.balanceService.CheckBalanceSufficiency(bal, fields.Amount.Mul(fields.Rate).RoundBank(0)) { + return fmt.Errorf("fallback provider %s has insufficient balance for order %s", fallbackID, fields.ID.String()) + } + + fields.ProviderID = fallbackID + if err := s.sendOrderRequest(ctx, fields, assignmentLockHeld); err != nil { + return fmt.Errorf("fallback: send order request: %w", err) + } + if _, setErr := storage.Client.PaymentOrder.UpdateOneID(fields.ID). + SetFallbackTriedAt(time.Now()). + SetOrderPercent(decimal.NewFromInt(100)). + Save(ctx); setErr != nil { + logger.WithFields(logger.Fields{"OrderID": fields.ID.String(), "Error": setErr}).Errorf("[FALLBACK_ASSIGNMENT] failed to set fallback_tried_at on order") + // Non-fatal: order request was sent; persistence can be reconciled later. + } + logger.WithFields(logger.Fields{"OrderID": fields.ID.String(), "FallbackID": fallbackID}).Infof("[FALLBACK_ASSIGNMENT] successful fallback assignment") + return nil +} + +// tryUsePreSetProvider fetches the provider by order.ProviderID, optionally refreshes the rate, +// then assigns via OTC or sendOrderRequest. Returns (true, provider, nil) on success. +// When assignmentLockHeld is true, order_assign_lock_{orderID} is already held by the caller. +func (s *Service) tryUsePreSetProvider(ctx context.Context, order types.PaymentOrderFields, assignmentLockHeld bool) (assigned bool, provider *ent.ProviderProfile, err error) { + provider, err = storage.Client.ProviderProfile. + Query(). + Where(providerprofile.IDEQ(order.ProviderID)). + Only(ctx) + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + }).Errorf("failed to get provider") + return false, nil, err + } + + if !order.UpdatedAt.IsZero() && order.UpdatedAt.Before(time.Now().Add(-10*time.Minute)) { + currencyCode := "" + if order.Institution != "" { + institution, instErr := utils.GetInstitutionByCode(ctx, order.Institution, true) + if instErr == nil && institution != nil && institution.Edges.FiatCurrency != nil { + currencyCode = institution.Edges.FiatCurrency.Code + } + } + if currencyCode != "" { + order.Rate, err = s.GetProviderRate(ctx, provider, order.Token.Symbol, currencyCode, RateSideSell) + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + }).Errorf("failed to get rate for provider") + } else { + _, err = storage.Client.PaymentOrder. + Update(). + Where(paymentorder.MessageHashEQ(order.MessageHash)). + SetRate(order.Rate). + Save(ctx) + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + }).Errorf("failed to update rate for provider") + } + } + } + } + + if order.OrderType == "otc" { + if err := s.assignOtcOrder(ctx, order, assignmentLockHeld); err != nil { + return false, provider, err + } + return true, provider, nil + } + err = s.sendOrderRequest(ctx, order, assignmentLockHeld) + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + }).Errorf("failed to send order request to specific provider") + return false, provider, err + } + return true, provider, nil +} + +// assignOtcOrder assigns an OTC order to a provider in DB then creates a Redis key for reassignment. +// When assignmentLockHeld is true, order_assign_lock_{orderID} is already held by the caller. +func (s *Service) assignOtcOrder(ctx context.Context, order types.PaymentOrderFields, assignmentLockHeld bool) error { + orderConf := config.OrderConfig() + tx, err := storage.Client.Tx(ctx) + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + }).Errorf("Failed to start transaction for OTC order assignment") + return fmt.Errorf("failed to start transaction: %w", err) + } + defer func() { + if err != nil { + _ = tx.Rollback() + } + }() + + if order.ProviderID != "" { + provider, qErr := tx.ProviderProfile.Query().Where(providerprofile.IDEQ(order.ProviderID)).Only(ctx) + if qErr != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", qErr), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + }).Errorf("failed to get provider for OTC order assignment") + return fmt.Errorf("failed to get provider: %w", qErr) + } + if provider != nil { + _, err = tx.PaymentOrder. + Update(). + Where(paymentorder.IDEQ(order.ID)). + SetProvider(provider). + Save(ctx) + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + }).Errorf("failed to assign OTC order to provider") + return fmt.Errorf("failed to assign OTC order: %w", err) + } + } + } + + if err = tx.Commit(); err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + }).Errorf("Failed to commit OTC order assignment transaction") + return fmt.Errorf("failed to commit transaction: %w", err) + } + + orderKey := fmt.Sprintf("order_request_%s", order.ID) + if !assignmentLockHeld { + otcRelease, lockErr := acquireOrderAssignmentLock(ctx, order.ID) + if lockErr != nil { + if errors.Is(lockErr, ErrAssignmentLockHeld) { + return resolveOrderRequestRedisConflict(ctx, order, orderKey) + } + return lockErr + } + defer otcRelease() + } + + exists, err := storage.RedisClient.Exists(ctx, orderKey).Result() + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "OrderKey": orderKey, + }).Errorf("Failed to check if OTC order request exists in Redis") + return fmt.Errorf("failed to check order_request in Redis: %w", err) + } + if exists > 0 { + existingProviderID, hgetErr := storage.RedisClient.HGet(ctx, orderKey, "providerId").Result() + if hgetErr == nil && existingProviderID == order.ProviderID { + logger.WithFields(logger.Fields{ + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "OrderKey": orderKey, + }).Warnf("OTC order request already exists in Redis for same provider - skipping duplicate creation") + return nil + } + if hgetErr == nil && existingProviderID != order.ProviderID { + logger.WithFields(logger.Fields{ + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "ExistingProviderID": existingProviderID, + "OrderKey": orderKey, + }).Errorf("OTC order request exists for different provider - DB/Redis consistency issue") + return fmt.Errorf("order_request exists for different provider (redis=%s, current=%s)", existingProviderID, order.ProviderID) + } + verifyErr := hgetErr + if verifyErr == nil { + verifyErr = fmt.Errorf("providerId missing in Redis hash") + } + logger.WithFields(logger.Fields{ + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "OrderKey": orderKey, + "Error": verifyErr, + }).Errorf("OTC order request exists but could not verify provider - skipping to avoid inconsistency") + return fmt.Errorf("order_request exists but provider could not be verified: %w", verifyErr) + } + + orderRequestData := map[string]interface{}{ + "type": "otc", + "providerId": order.ProviderID, + } + if err = storage.RedisClient.HSet(ctx, orderKey, orderRequestData).Err(); err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "OrderKey": orderKey, + }).Errorf("Failed to create Redis key for OTC order") + return fmt.Errorf("failed to create order_request in Redis: %w", err) + } + if err = storage.RedisClient.ExpireAt(ctx, orderKey, time.Now().Add(orderConf.OrderRequestValidityOtc)).Err(); err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "OrderKey": orderKey, + }).Errorf("Failed to set TTL for OTC order request") + _ = storage.RedisClient.Del(ctx, orderKey).Err() + return fmt.Errorf("failed to set TTL for order_request: %w", err) + } + + return nil +} + +// countProviderInExcludeList counts how many times a provider appears in the exclude list. +func (s *Service) countProviderInExcludeList(excludeList []string, providerID string) int { + count := 0 + for _, id := range excludeList { + if id == providerID { + count++ + } + } + return count +} + +// getExcludePsps returns PSP names to exclude based on the global failure-rate threshold. +// PSPs that have a high failure rate in the last N minutes are excluded globally. +// Per-order exclusion is not used so the same order can retry a PSP after a transient failure. +func (s *Service) getExcludePsps(ctx context.Context) ([]string, error) { + orderConf := config.OrderConfig() + excluded := make(map[string]struct{}) + + window := time.Duration(orderConf.PspExcludeWindowMinutes) * time.Minute + if window <= 0 { + window = 120 * time.Minute + } + since := time.Now().Add(-window) + + fulfillments, err := storage.Client.PaymentOrderFulfillment.Query(). + Where(paymentorderfulfillment.UpdatedAtGTE(since)). + Select( + paymentorderfulfillment.FieldPsp, + paymentorderfulfillment.FieldValidationStatus, + ). + All(ctx) + if err != nil { + return nil, fmt.Errorf("global exclude PSPs: %w", err) + } + + type stats struct{ attempts, failures int } + byPsp := make(map[string]*stats) + for _, f := range fulfillments { + psp := strings.TrimSpace(f.Psp) + if psp == "" { + continue + } + if byPsp[psp] == nil { + byPsp[psp] = &stats{} + } + byPsp[psp].attempts++ + if f.ValidationStatus == paymentorderfulfillment.ValidationStatusFailed { + byPsp[psp].failures++ + } + } + + minAttempts := orderConf.PspExcludeMinAttempts + if minAttempts < 1 { + minAttempts = 5 + } + minFailures := orderConf.PspExcludeMinFailures + if minFailures < 1 { + minFailures = 3 + } + minPercent := orderConf.PspExcludeMinFailurePercent + if minPercent <= 0 { + minPercent = 30 + } + minRate := float64(minPercent) / 100 + + for psp, st := range byPsp { + if st.attempts < minAttempts || st.failures < minFailures { + continue + } + rate := float64(st.failures) / float64(st.attempts) + if rate >= minRate { + excluded[psp] = struct{}{} + } + } + + out := make([]string, 0, len(excluded)) + for p := range excluded { + out = append(out, p) + } + return out, nil +} + +// sendOrderRequest reserves balance, writes the Redis order_request key, and notifies the provider. +// When assignmentLockHeld is true, order_assign_lock_{orderID} is already held by the caller. +func (s *Service) sendOrderRequest(ctx context.Context, order types.PaymentOrderFields, assignmentLockHeld bool) error { + orderConf := config.OrderConfig() + if order.Institution == "" { + return fmt.Errorf("sendOrderRequest: order %s has no institution for currency resolution", order.ID.String()) + } + inst, instErr := utils.GetInstitutionByCode(ctx, order.Institution, true) + if instErr != nil || inst == nil || inst.Edges.FiatCurrency == nil { + return fmt.Errorf("sendOrderRequest: institution or fiat currency for order %s: %w", order.ID.String(), instErr) + } + currency := inst.Edges.FiatCurrency.Code + amount := order.Amount.Mul(order.Rate).RoundBank(0) + + orderKey := fmt.Sprintf("order_request_%s", order.ID) + + if !assignmentLockHeld { + release, lockErr := acquireOrderAssignmentLock(ctx, order.ID) + if lockErr != nil { + if errors.Is(lockErr, ErrAssignmentLockHeld) { + return resolveOrderRequestRedisConflict(ctx, order, orderKey) + } + return lockErr + } + defer release() + } + + exists, err := storage.RedisClient.Exists(ctx, orderKey).Result() + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "OrderKey": orderKey, + }).Errorf("Failed to check if order request exists in Redis") + return err + } + if exists > 0 { + existingProviderID, hErr := storage.RedisClient.HGet(ctx, orderKey, "providerId").Result() + if hErr == nil && existingProviderID == order.ProviderID { + logger.WithFields(logger.Fields{ + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "OrderKey": orderKey, + }).Errorf("Order request already exists in Redis - skipping duplicate notification") + return nil + } + if hErr == nil && existingProviderID != order.ProviderID { + logger.WithFields(logger.Fields{ + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "ExistingProviderID": existingProviderID, + "OrderKey": orderKey, + }).Errorf("Order request exists for different provider - potential race condition") + return fmt.Errorf("order request exists for different provider") + } + } + + tx, err := storage.Client.Tx(ctx) + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "Currency": currency, + "Amount": amount.String(), + }).Errorf("Failed to start transaction for order processing") + return fmt.Errorf("failed to start transaction: %w", err) + } + txCommitted := false + defer func() { + if err != nil && !txCommitted { + _ = tx.Rollback() + } + }() + + err = s.balanceService.ReserveFiatBalance(ctx, order.ProviderID, currency, amount, tx) + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "Currency": currency, + "Amount": amount.String(), + }).Errorf("Failed to reserve balance for order") + return err + } + + orderRequestData := map[string]interface{}{ + "amount": order.Amount.Mul(order.Rate).RoundBank(0).String(), + "institution": order.Institution, + "currency": currency, + "providerId": order.ProviderID, + } + + err = storage.RedisClient.HSet(ctx, orderKey, orderRequestData).Err() + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "OrderKey": orderKey, + }).Errorf("Failed to map order to a provider in Redis") + return err + } + + metaKey := fmt.Sprintf("order_request_meta_%s", order.ID) + metaData := map[string]interface{}{ + "amount": orderRequestData["amount"], + "currency": orderRequestData["currency"], + "providerId": orderRequestData["providerId"], + } + err = storage.RedisClient.HSet(ctx, metaKey, metaData).Err() + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "MetaKey": metaKey, + }).Errorf("Failed to persist order request metadata in Redis") + _ = storage.RedisClient.Del(ctx, orderKey).Err() + return err + } + + err = storage.RedisClient.ExpireAt(ctx, orderKey, time.Now().Add(orderConf.OrderRequestValidity)).Err() + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderKey": orderKey, + }).Errorf("Failed to set TTL for order request") + cleanupErr := storage.RedisClient.Del(ctx, orderKey).Err() + if cleanupErr != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", cleanupErr), + "OrderKey": orderKey, + }).Errorf("Failed to cleanup orderKey after ExpireAt failure") + } + _ = storage.RedisClient.Del(ctx, metaKey).Err() + return err + } + + err = storage.RedisClient.ExpireAt(ctx, metaKey, time.Now().Add(orderConf.OrderRequestValidity*2)).Err() + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "MetaKey": metaKey, + }).Errorf("Failed to set TTL for order request metadata key") + _ = storage.RedisClient.Del(ctx, orderKey).Err() + _ = storage.RedisClient.Del(ctx, metaKey).Err() + return err + } + + if orderConf.FallbackProviderID == "" || order.ProviderID != orderConf.FallbackProviderID { + excludePsps, excludeErr := s.getExcludePsps(ctx) + if excludeErr != nil { + logger.WithFields(logger.Fields{ + "OrderID": order.ID.String(), + "Error": excludeErr.Error(), + }).Errorf("getExcludePsps failed, sending new_order without excludePsps") + } else if len(excludePsps) > 0 { + orderRequestData["excludePsps"] = excludePsps + } + } + + orderRequestData["orderId"] = order.ID.String() + + err = tx.Commit() + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + }).Errorf("Failed to commit order processing transaction") + _ = storage.RedisClient.Del(ctx, orderKey).Err() + _ = storage.RedisClient.Del(ctx, metaKey).Err() + return fmt.Errorf("failed to commit transaction: %w", err) + } + txCommitted = true + + err = s.notifyProvider(ctx, orderRequestData) + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + }).Errorf("Failed to notify provider") + if relErr := s.balanceService.ReleaseFiatBalance(ctx, order.ProviderID, currency, amount, nil); relErr != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", relErr), + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "Currency": currency, + "Amount": amount.String(), + }).Errorf("Failed to release fiat balance after notifyProvider failure") + } + cleanupErr := storage.RedisClient.Del(ctx, orderKey).Err() + if cleanupErr != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", cleanupErr), + "OrderKey": orderKey, + }).Errorf("Failed to cleanup orderKey after notifyProvider failure") + } + _ = storage.RedisClient.Del(ctx, metaKey).Err() + return err + } + + logger.WithFields(logger.Fields{ + "OrderID": order.ID.String(), + "ProviderID": order.ProviderID, + "Currency": currency, + "Amount": amount.String(), + }).Infof("Order processed successfully with balance reserved") + + return nil +} + +// notifyProvider sends an order request notification to a provider node via /new_order. +func (s *Service) notifyProvider(ctx context.Context, orderRequestData map[string]interface{}) error { + providerID := orderRequestData["providerId"].(string) + delete(orderRequestData, "providerId") + + data, err := utils.CallProviderWithHMAC(ctx, providerID, "POST", "/new_order", orderRequestData) + if err != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", err), + "ProviderID": providerID, + }).Errorf("failed to call provider /new_order endpoint") + return err + } + + logger.WithFields(logger.Fields{ + "ProviderID": providerID, + "Data": data, + }).Infof("successfully called provider /new_order endpoint") + + return nil +} diff --git a/services/assignment/assign_test.go b/services/assignment/assign_test.go new file mode 100644 index 000000000..328b49868 --- /dev/null +++ b/services/assignment/assign_test.go @@ -0,0 +1,186 @@ +package assignment + +import ( + "context" + "database/sql" + "net/http" + "net/http/httptest" + "testing" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/alicebob/miniredis/v2" + "github.com/paycrest/aggregator/ent" + "github.com/paycrest/aggregator/ent/fiatcurrency" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/providerbalances" + "github.com/paycrest/aggregator/ent/providerprofile" + tokenEnt "github.com/paycrest/aggregator/ent/token" + userEnt "github.com/paycrest/aggregator/ent/user" + svc "github.com/paycrest/aggregator/services" + db "github.com/paycrest/aggregator/storage" + "github.com/paycrest/aggregator/types" + "github.com/paycrest/aggregator/utils/test" + "github.com/redis/go-redis/v9" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAssignPaymentOrder_DBOnlyPublicProvider(t *testing.T) { + dbConn, err := sql.Open("sqlite3", "file:ent_pq?mode=memory&cache=shared&_fk=1&_busy_timeout=5000") + require.NoError(t, err) + dbConn.SetMaxOpenConns(2) + + drv := entsql.OpenDB(dialect.SQLite, dbConn) + client := ent.NewClient(ent.Driver(drv)) + + origClient, origSQLDB, origRedis := db.Client, db.DB, db.RedisClient + db.Client = client + db.DB = dbConn + require.NoError(t, client.Schema.Create(context.Background())) + + mr, err := miniredis.Run() + require.NoError(t, err) + rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + db.RedisClient = rdb + + t.Cleanup(func() { + _ = rdb.Close() + mr.Close() + _ = dbConn.Close() + _ = client.Close() + db.Client = origClient + db.DB = origSQLDB + db.RedisClient = origRedis + }) + + ctx := context.Background() + + netw, err := client.Network.Create(). + SetIdentifier("localhost"). + SetChainID(56). + SetRPCEndpoint("ws://localhost:8545"). + SetBlockTime(decimal.NewFromFloat(3)). + SetFee(decimal.NewFromFloat(0.1)). + SetIsTestnet(true). + Save(ctx) + require.NoError(t, err) + networkID := netw.ID + + tok, err := client.Token.Create(). + SetSymbol("TST"). + SetContractAddress("0xd4E96eF8eee8678dBFf4d535E033Ed1a4F7605b7"). + SetDecimals(6). + SetNetworkID(networkID). + SetIsEnabled(true). + SetBaseCurrency("KES"). + Save(ctx) + require.NoError(t, err) + tok, err = client.Token.Query().Where(tokenEnt.IDEQ(tok.ID)).WithNetwork().Only(ctx) + require.NoError(t, err) + + cur, err := test.CreateTestFiatCurrency(map[string]interface{}{ + "code": "KES", "short_name": "Shilling", "decimals": 2, "symbol": "KSh", + "name": "Kenyan Shilling", "market_rate": 550.0, + }) + require.NoError(t, err) + + _, err = client.FiatCurrency.UpdateOneID(cur.ID). + SetMarketBuyRate(decimal.NewFromFloat(550)). + SetMarketSellRate(decimal.NewFromFloat(550)). + Save(ctx) + require.NoError(t, err) + + _, err = client.Institution.Create(). + SetCode("PQTESTBANK"). + SetName("PQ Test Bank"). + SetFiatCurrencyID(cur.ID). + Save(ctx) + require.NoError(t, err) + + u, err := test.CreateTestUser(map[string]interface{}{"scope": "provider", "email": "pqpub@test.com"}) + require.NoError(t, err) + prov, err := test.CreateTestProviderProfile(map[string]interface{}{ + "user_id": u.ID, "currency_id": cur.ID, "host_identifier": "https://example.com", + }) + require.NoError(t, err) + _, err = client.ProviderProfile.UpdateOneID(prov.ID).SetIsActive(true).Save(ctx) + require.NoError(t, err) + _, err = client.User.UpdateOneID(u.ID).SetKybVerificationStatus(userEnt.KybVerificationStatusApproved).Save(ctx) + require.NoError(t, err) + + apiKeySvc := svc.NewAPIKeyService() + _, _, err = apiKeySvc.GenerateAPIKey(ctx, nil, nil, prov) + require.NoError(t, err) + + _, err = test.AddProviderOrderTokenToProvider(map[string]interface{}{ + "provider": prov, + "currency_id": cur.ID, + "token_id": tok.ID, + "network": tok.Edges.Network.Identifier, + "fixed_buy_rate": decimal.NewFromFloat(100), + "fixed_sell_rate": decimal.NewFromFloat(100), + "max_order_amount": decimal.NewFromFloat(10000), + "min_order_amount": decimal.NewFromFloat(1), + }) + require.NoError(t, err) + + _, err = client.ProviderBalances.Update(). + Where(providerbalances.HasProviderWith(providerprofile.IDEQ(prov.ID))). + Where(providerbalances.HasFiatCurrencyWith(fiatcurrency.IDEQ(cur.ID))). + SetAvailableBalance(decimal.NewFromFloat(1_000_000)). + SetTotalBalance(decimal.NewFromFloat(1_000_000)). + SetIsAvailable(true). + Save(ctx) + require.NoError(t, err) + + mockSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"status":"success","message":"ok"}`)) + })) + t.Cleanup(mockSrv.Close) + _, err = client.ProviderProfile.Update().SetHostIdentifier(mockSrv.URL).Save(ctx) + require.NoError(t, err) + + order, err := client.PaymentOrder.Create(). + SetAmount(decimal.NewFromFloat(100.5)). + SetAmountInUsd(decimal.NewFromFloat(100.5)). + SetRate(decimal.NewFromFloat(100)). + SetStatus(paymentorder.StatusPending). + SetInstitution("PQTESTBANK"). + SetAccountIdentifier("1234567890"). + SetAccountName("Test Account"). + SetMemo("pq test"). + SetToken(tok). + SetGatewayID("gw-pq-dbonly-1"). + SetBlockNumber(1). + Save(ctx) + require.NoError(t, err) + + s := New() + + fields := types.PaymentOrderFields{ + ID: order.ID, + OrderType: string(paymentorder.OrderTypeRegular), + GatewayID: order.GatewayID, + Amount: order.Amount, + Rate: order.Rate, + BlockNumber: order.BlockNumber, + Institution: order.Institution, + AccountIdentifier: order.AccountIdentifier, + AccountName: order.AccountName, + Memo: order.Memo, + Token: tok, + Network: tok.Edges.Network, + } + + require.NoError(t, s.AssignPaymentOrder(ctx, fields)) + + key := "order_request_" + order.ID.String() + n, err := rdb.Exists(ctx, key).Result() + require.NoError(t, err) + assert.Equal(t, int64(1), n) + pid, err := rdb.HGet(ctx, key, "providerId").Result() + require.NoError(t, err) + assert.Equal(t, prov.ID, pid) +} diff --git a/services/assignment/constants.go b/services/assignment/constants.go new file mode 100644 index 000000000..cfb5eeebd --- /dev/null +++ b/services/assignment/constants.go @@ -0,0 +1,79 @@ +package assignment + +import ( + "time" + + "github.com/shopspring/decimal" +) + +// Provider selection and scoring constants (hardcoded per product; not env-configured). + +const ( + // Score deltas (applied via ProviderOrderTokenScoreHistory + score update). + RewardFulfilledValidated = 1.0 + PenaltyCancelInsufficientFunds = -1.5 + PenaltyCancelProviderFault = -1.0 + PenaltyValidationFailed = -2.0 + PenaltyOrderRequestExpired = -0.5 +) + +// RecentVolumeWindow is the lookback for recent_successful_fiat_volume_24h ordering. +var RecentVolumeWindow = 24 * time.Hour + +// assignPaymentOrderTimeout bounds DB/Redis work for one assignment invocation. +const assignPaymentOrderTimeout = 2 * time.Minute + +// recordAssignmentRunTimeout bounds audit persistence so it is not cut off by assignPaymentOrderTimeout. +const recordAssignmentRunTimeout = 10 * time.Second + +// orderAssignLockTTL is Redis TTL for order_assign_lock_{orderID} (exclusive assign / sendOrderRequest). +const orderAssignLockTTL = 5 * time.Minute + +// assignmentMarketRateRelTol: refresh persisted assignment market snapshot when fiat rates drift beyond this relative delta. +var assignmentMarketRateRelTol = decimal.NewFromFloat(0.0005) // 0.05% + +// ProviderFaultCancelReasons is the allow-list of cancel reasons that count as provider fault +// (-1.0). Each entry indicates the provider accepted an order their PSP or account configuration +// cannot process — i.e. the provider is responsible, not external infrastructure. +// +// Matching is case-insensitive prefix so PSPs can append context without breaking the match +// (e.g. "Amount exceeds maximum allowed (GHS 5000)" matches "Amount exceeds maximum allowed"). +// +// Excluded intentionally (not provider fault): +// - "Gateway timeout" — external infrastructure delay. +// - "Transaction data not found", "transactionId is missing from the response", +// "Invalid transfer response" — PSP response parsing bugs. +// - "Disbursement failed", "Transaction failed", "Order processing incomplete" — catch-all +// fallbacks too ambiguous to attribute to the provider. +var ProviderFaultCancelReasons = []string{ + "Amount exceeds maximum allowed", + "Amount is less than minimum allowed", + "Invalid amount", + "Unsupported channel", + "Payment failed", +} + +// ScoreHistoryEventType values for idempotent score application (unique per payment_order_id + event_type). +const ( + ScoreEventFulfilledValidated = "fulfilled_validated" + ScoreEventCancelInsufficientFunds = "cancel_insufficient_funds" + ScoreEventCancelProviderFault = "cancel_provider_fault" + ScoreEventValidationFailed = "validation_failed" + ScoreEventOrderRequestExpired = "order_request_expired" +) + +// AssignmentRunResult values for ProviderAssignmentRun.result. +const ( + AssignmentRunResultAssigned = "assigned" + AssignmentRunResultFallback = "fallback" + AssignmentRunResultNoProvider = "no_provider" + AssignmentRunResultSkipped = "skipped" + AssignmentRunResultError = "error" +) + +// AssignmentRunTrigger values for ProviderAssignmentRun.trigger. +const ( + AssignmentTriggerInitial = "initial" + AssignmentTriggerReassignStale = "reassign_stale" + AssignmentTriggerStaleOps = "stale_ops" +) diff --git a/services/assignment/scoring.go b/services/assignment/scoring.go new file mode 100644 index 000000000..fbd217dd2 --- /dev/null +++ b/services/assignment/scoring.go @@ -0,0 +1,149 @@ +package assignment + +import ( + "context" + "fmt" + "strings" + + "github.com/google/uuid" + "github.com/paycrest/aggregator/config" + "github.com/paycrest/aggregator/ent" + "github.com/paycrest/aggregator/ent/fiatcurrency" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerprofile" + "github.com/paycrest/aggregator/ent/token" + "github.com/paycrest/aggregator/storage" + "github.com/paycrest/aggregator/utils" + "github.com/paycrest/aggregator/utils/logger" + "github.com/shopspring/decimal" +) + +// IsProviderFaultCancelReason returns true if reason starts with any entry in +// ProviderFaultCancelReasons (case-insensitive, trimmed). Prefix matching lets +// PSP-appended context like "(GHS 5000)" in "Amount exceeds maximum allowed (GHS 5000)" +// still match the base phrase "Amount exceeds maximum allowed". +func IsProviderFaultCancelReason(reason string) bool { + r := strings.ToLower(strings.TrimSpace(reason)) + if r == "" { + return false + } + for _, allowed := range ProviderFaultCancelReasons { + if strings.HasPrefix(r, strings.ToLower(strings.TrimSpace(allowed))) { + return true + } + } + return false +} + +// ApplyProviderScoreChange applies delta to the provider_order_token for this order's assigned +// provider, if score-eligible. Idempotent via unique (payment_order_id, event_type) on +// provider_order_token_score_histories. +func ApplyProviderScoreChange(ctx context.Context, orderID uuid.UUID, eventType string, delta decimal.Decimal) error { + order, err := storage.Client.PaymentOrder.Query(). + Where(paymentorder.IDEQ(orderID)). + WithProvider(). + WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() }). + Only(ctx) + if err != nil { + if ent.IsNotFound(err) { + return nil + } + return fmt.Errorf("score: load order: %w", err) + } + if order.Edges.Provider == nil { + return nil + } + return applyScoreForProvider(ctx, order, order.Edges.Provider, eventType, delta) +} + +// ApplyProviderScoreChangeForProvider applies a score change for a specific provider +// (e.g. stale order_request meta) tied to orderID for idempotency. +func ApplyProviderScoreChangeForProvider(ctx context.Context, orderID uuid.UUID, providerID string, eventType string, delta decimal.Decimal) error { + if providerID == "" { + return nil + } + order, err := storage.Client.PaymentOrder.Query(). + Where(paymentorder.IDEQ(orderID)). + WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() }). + Only(ctx) + if err != nil { + if ent.IsNotFound(err) { + return nil + } + return fmt.Errorf("score: load order: %w", err) + } + prov, err := storage.Client.ProviderProfile.Get(ctx, providerID) + if err != nil { + if ent.IsNotFound(err) { + return nil + } + return fmt.Errorf("score: load provider: %w", err) + } + return applyScoreForProvider(ctx, order, prov, eventType, delta) +} + +func applyScoreForProvider(ctx context.Context, order *ent.PaymentOrder, prov *ent.ProviderProfile, eventType string, delta decimal.Decimal) error { + if prov == nil { + return nil + } + providerID := prov.ID + fb := config.OrderConfig().FallbackProviderID + if fb != "" && providerID == fb { + return nil + } + if prov.VisibilityMode != providerprofile.VisibilityModePublic { + return nil + } + + if order.Edges.Token == nil || order.Edges.Token.Edges.Network == nil { + return fmt.Errorf("score: order token/network required") + } + inst, err := utils.GetInstitutionByCode(ctx, order.Institution, true) + if err != nil || inst == nil || inst.Edges.FiatCurrency == nil { + logger.WithFields(logger.Fields{"OrderID": order.ID.String()}).Warnf("score: skip — institution currency not resolved") + return nil + } + fc := inst.Edges.FiatCurrency + + pot, err := storage.Client.ProviderOrderToken.Query(). + Where( + providerordertoken.HasProviderWith(providerprofile.IDEQ(providerID)), + providerordertoken.HasTokenWith(token.IDEQ(order.Edges.Token.ID)), + providerordertoken.NetworkEQ(order.Edges.Token.Edges.Network.Identifier), + providerordertoken.HasCurrencyWith(fiatcurrency.IDEQ(fc.ID)), + ). + Only(ctx) + if err != nil { + if ent.IsNotFound(err) { + return nil + } + return fmt.Errorf("score: resolve pot: %w", err) + } + + tx, err := storage.Client.Tx(ctx) + if err != nil { + return fmt.Errorf("score: begin tx: %w", err) + } + _, err = tx.ProviderOrderTokenScoreHistory.Create(). + SetPaymentOrderID(order.ID). + SetProviderOrderTokenID(pot.ID). + SetEventType(eventType). + SetDelta(delta). + Save(ctx) + if err != nil { + _ = tx.Rollback() + if ent.IsConstraintError(err) { + return nil + } + return fmt.Errorf("score: history insert: %w", err) + } + if err := tx.ProviderOrderToken.UpdateOneID(pot.ID).AddScore(delta).Exec(ctx); err != nil { + _ = tx.Rollback() + return fmt.Errorf("score: update pot: %w", err) + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("score: commit: %w", err) + } + return nil +} diff --git a/services/assignment/scoring_test.go b/services/assignment/scoring_test.go new file mode 100644 index 000000000..a700f8ea9 --- /dev/null +++ b/services/assignment/scoring_test.go @@ -0,0 +1,390 @@ +package assignment + +import ( + "context" + "database/sql" + "fmt" + "testing" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/alicebob/miniredis/v2" + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerprofile" + tokenEnt "github.com/paycrest/aggregator/ent/token" + userEnt "github.com/paycrest/aggregator/ent/user" + db "github.com/paycrest/aggregator/storage" + "github.com/paycrest/aggregator/utils/test" + "github.com/redis/go-redis/v9" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + _ "github.com/mattn/go-sqlite3" +) + +// newTestDB opens a fresh named in-memory SQLite database, wires it into the +// global storage singletons, and registers cleanup via t.Cleanup. Each call +// must use a unique name to avoid cross-test contamination. +func newTestDB(t *testing.T, name string) { + t.Helper() + + prevClient := db.Client + prevDB := db.DB + prevRedis := db.RedisClient + + dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1&_busy_timeout=5000", name) + dbConn, err := sql.Open("sqlite3", dsn) + require.NoError(t, err) + dbConn.SetMaxOpenConns(2) + + drv := entsql.OpenDB(dialect.SQLite, dbConn) + client := ent.NewClient(ent.Driver(drv)) + require.NoError(t, client.Schema.Create(context.Background())) + + mr, err := miniredis.Run() + require.NoError(t, err) + rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + + db.Client = client + db.DB = dbConn + db.RedisClient = rdb + + t.Cleanup(func() { + _ = rdb.Close() + mr.Close() + _ = client.Close() + _ = dbConn.Close() + db.Client = prevClient + db.DB = prevDB + db.RedisClient = prevRedis + }) +} + +// TestIsProviderFaultCancelReason validates the prefix-based allow-list check. +func TestIsProviderFaultCancelReason(t *testing.T) { + cases := []struct { + reason string + want bool + desc string + }{ + // ── PSP-generated: exact base string ─────────────────────────────────── + {"Amount exceeds maximum allowed", true, "PSP: exact base phrase"}, + {"Amount is less than minimum allowed", true, "PSP: exact base phrase"}, + {"Invalid amount", true, "PSP: exact base phrase"}, + {"Unsupported channel", true, "PSP: exact base phrase"}, + {"Payment failed", true, "PSP: Transfero exact phrase"}, + + // ── PSP-generated: base phrase with appended context (prefix match) ──── + {"Amount exceeds maximum allowed (GHS 5000)", true, "PSP: BoltPay with currency suffix"}, + {"Amount exceeds maximum allowed (NGN 10000)", true, "PSP: hypothetical currency suffix"}, + {"Amount is less than minimum allowed (GHS 10)", true, "PSP: BoltPay min with suffix"}, + {"Unsupported channel type", true, "PSP: BoltPay 'unsupported channel type' starts with 'Unsupported channel'"}, + + // ── Case-insensitive variants ─────────────────────────────────────────── + {"amount exceeds maximum allowed", true, "lowercase PSP phrase"}, + {"PAYMENT FAILED", true, "uppercase PSP phrase"}, + + // ── Whitespace tolerance ──────────────────────────────────────────────── + {" Amount exceeds maximum allowed ", true, "PSP phrase with whitespace"}, + + // ── NOT provider fault: should NOT match ─────────────────────────────── + {"Insufficient funds", false, "handled by separate penalty, not in this list"}, + {"Gateway timeout", false, "external infrastructure, not provider fault"}, + {"Transaction failed", false, "ambiguous catch-all, not provider fault"}, + {"Disbursement failed", false, "generic catch-all, not provider fault"}, + {"Order processing incomplete", false, "system error, not provider fault"}, + {"Transaction data not found", false, "PSP response bug, not provider fault"}, + {"Invalid transfer response", false, "PSP response bug, not provider fault"}, + {"Invalid recipient bank details", false, "customer data issue, handled separately"}, + {"Network error", false, "external infrastructure"}, + + // ── Empty / blank ─────────────────────────────────────────────────────── + {"", false, "empty string"}, + {" ", false, "whitespace-only string"}, + } + + for _, tc := range cases { + got := IsProviderFaultCancelReason(tc.reason) + assert.Equal(t, tc.want, got, "[%s] reason=%q", tc.desc, tc.reason) + } +} + +// scoringCtx holds the shared DB fixtures used across TestProviderScoring subtests. +type scoringCtx struct { + ctx context.Context + client *ent.Client + currency *ent.FiatCurrency + tok *ent.Token // loaded with WithNetwork() +} + +// newScoringCtx creates the shared network/token/currency fixtures for scoring tests. +func newScoringCtx(t *testing.T) scoringCtx { + t.Helper() + ctx := context.Background() + client := db.Client + + netw, err := client.Network.Create(). + SetIdentifier("score-net"). + SetChainID(56). + SetRPCEndpoint("ws://localhost:8545"). + SetBlockTime(decimal.NewFromFloat(3)). + SetFee(decimal.NewFromFloat(0.1)). + SetIsTestnet(true). + Save(ctx) + require.NoError(t, err) + + tok, err := client.Token.Create(). + SetSymbol("SCRTOK"). + SetContractAddress("0x1111111111111111111111111111111111111111"). + SetDecimals(6). + SetNetworkID(netw.ID). + SetIsEnabled(true). + SetBaseCurrency("NGN"). + Save(ctx) + require.NoError(t, err) + tok, err = client.Token.Query().Where(tokenEnt.IDEQ(tok.ID)).WithNetwork().Only(ctx) + require.NoError(t, err) + + cur, err := test.CreateTestFiatCurrency(map[string]interface{}{ + "code": "NGN", "short_name": "Naira", "decimals": 2, + "symbol": "₦", "name": "Nigerian Naira", "market_rate": 1500.0, + }) + require.NoError(t, err) + _, err = client.FiatCurrency.UpdateOneID(cur.ID). + SetMarketBuyRate(decimal.NewFromFloat(1500)). + SetMarketSellRate(decimal.NewFromFloat(1500)). + Save(ctx) + require.NoError(t, err) + + return scoringCtx{ctx: ctx, client: client, currency: cur, tok: tok} +} + +// makeScoringProvider creates a public+active provider and a matching POT. +func makeScoringProvider(t *testing.T, sc scoringCtx, email, visibility string) (*ent.ProviderProfile, *ent.ProviderOrderToken) { + t.Helper() + ctx := sc.ctx + client := sc.client + + u, err := test.CreateTestUser(map[string]interface{}{"scope": "provider", "email": email}) + require.NoError(t, err) + + prov, err := test.CreateTestProviderProfile(map[string]interface{}{ + "user_id": u.ID, + "currency_id": sc.currency.ID, + "visibility_mode": visibility, + }) + require.NoError(t, err) + + _, err = client.ProviderProfile.UpdateOneID(prov.ID).SetIsActive(true).Save(ctx) + require.NoError(t, err) + _, err = client.User.UpdateOneID(u.ID). + SetKybVerificationStatus(userEnt.KybVerificationStatusApproved). + Save(ctx) + require.NoError(t, err) + + pot, err := test.AddProviderOrderTokenToProvider(map[string]interface{}{ + "provider": prov, + "currency_id": sc.currency.ID, + "token_id": sc.tok.ID, + "network": sc.tok.Edges.Network.Identifier, + "fixed_sell_rate": decimal.NewFromFloat(1500), + "max_order_amount": decimal.NewFromFloat(10000), + "min_order_amount": decimal.NewFromFloat(1), + }) + require.NoError(t, err) + + return prov, pot +} + +// makeScoringOrder creates a payment order assigned to the given provider. +func makeScoringOrder(t *testing.T, sc scoringCtx, prov *ent.ProviderProfile) *ent.PaymentOrder { + t.Helper() + order, err := sc.client.PaymentOrder.Create(). + SetAmount(decimal.NewFromFloat(10)). + SetAmountInUsd(decimal.NewFromFloat(10)). + SetRate(decimal.NewFromFloat(1500)). + SetStatus(paymentorder.StatusFulfilled). + SetInstitution("ABNGNGLA"). + SetAccountIdentifier("0000000001"). + SetAccountName("Scorer Account"). + SetMemo("scoring test"). + SetToken(sc.tok). + SetGatewayID(uuid.New().String()). + SetBlockNumber(1). + SetProvider(prov). + Save(sc.ctx) + require.NoError(t, err) + return order +} + +// TestProviderScoring tests the ApplyProviderScoreChange logic end-to-end. +func TestProviderScoring(t *testing.T) { + newTestDB(t, "scoring_tests") + sc := newScoringCtx(t) + + t.Run("applies_delta_and_creates_history", func(t *testing.T) { + prov, pot := makeScoringProvider(t, sc, "score_apply@test.com", "public") + order := makeScoringOrder(t, sc, prov) + + err := ApplyProviderScoreChange(sc.ctx, order.ID, ScoreEventFulfilledValidated, decimal.NewFromFloat(RewardFulfilledValidated)) + require.NoError(t, err) + + updated, err := sc.client.ProviderOrderToken.Get(sc.ctx, pot.ID) + require.NoError(t, err) + assert.Equal(t, decimal.NewFromFloat(1.0).String(), updated.Score.String()) + + count, err := sc.client.ProviderOrderTokenScoreHistory.Query().Count(sc.ctx) + require.NoError(t, err) + assert.Equal(t, 1, count, "one history row should be created") + }) + + t.Run("idempotent_same_event", func(t *testing.T) { + prov, pot := makeScoringProvider(t, sc, "score_idem@test.com", "public") + order := makeScoringOrder(t, sc, prov) + + delta := decimal.NewFromFloat(1.0) + event := ScoreEventFulfilledValidated + + require.NoError(t, ApplyProviderScoreChange(sc.ctx, order.ID, event, delta)) + + updated1, err := sc.client.ProviderOrderToken.Get(sc.ctx, pot.ID) + require.NoError(t, err) + scoreAfterFirst := updated1.Score + + require.NoError(t, ApplyProviderScoreChange(sc.ctx, order.ID, event, delta)) + + updated2, err := sc.client.ProviderOrderToken.Get(sc.ctx, pot.ID) + require.NoError(t, err) + assert.Equal(t, scoreAfterFirst.String(), updated2.Score.String(), + "score must not change on duplicate event") + }) + + t.Run("different_event_types_both_applied", func(t *testing.T) { + prov, pot := makeScoringProvider(t, sc, "score_multi@test.com", "public") + order := makeScoringOrder(t, sc, prov) + + require.NoError(t, ApplyProviderScoreChange(sc.ctx, order.ID, ScoreEventFulfilledValidated, decimal.NewFromFloat(1.0))) + require.NoError(t, ApplyProviderScoreChange(sc.ctx, order.ID, ScoreEventValidationFailed, decimal.NewFromFloat(-2.0))) + + pot2, err := sc.client.ProviderOrderToken.Get(sc.ctx, pot.ID) + require.NoError(t, err) + assert.Equal(t, decimal.NewFromFloat(-1.0).String(), pot2.Score.String()) + }) + + t.Run("skips_private_provider", func(t *testing.T) { + prov, pot := makeScoringProvider(t, sc, "score_priv@test.com", "private") + order := makeScoringOrder(t, sc, prov) + + err := ApplyProviderScoreChange(sc.ctx, order.ID, ScoreEventFulfilledValidated, decimal.NewFromFloat(1.0)) + require.NoError(t, err) + + unchanged, err := sc.client.ProviderOrderToken.Get(sc.ctx, pot.ID) + require.NoError(t, err) + assert.Equal(t, decimal.Zero.String(), unchanged.Score.String(), + "private provider score must not change") + }) + + t.Run("skips_order_with_no_assigned_provider", func(t *testing.T) { + order, err := sc.client.PaymentOrder.Create(). + SetAmount(decimal.NewFromFloat(5)). + SetAmountInUsd(decimal.NewFromFloat(5)). + SetRate(decimal.NewFromFloat(1500)). + SetStatus(paymentorder.StatusPending). + SetInstitution("ABNGNGLA"). + SetAccountIdentifier("0000000002"). + SetAccountName("No Provider"). + SetMemo("no provider test"). + SetToken(sc.tok). + SetGatewayID(uuid.New().String()). + SetBlockNumber(1). + Save(sc.ctx) + require.NoError(t, err) + + err = ApplyProviderScoreChange(sc.ctx, order.ID, ScoreEventFulfilledValidated, decimal.NewFromFloat(1.0)) + assert.NoError(t, err) + }) + + t.Run("skips_nonexistent_order", func(t *testing.T) { + fakeID := uuid.New() + err := ApplyProviderScoreChange(sc.ctx, fakeID, ScoreEventFulfilledValidated, decimal.NewFromFloat(1.0)) + assert.NoError(t, err, "missing order must return nil, not an error") + }) + + t.Run("penalty_cancel_insufficient_funds", func(t *testing.T) { + prov, pot := makeScoringProvider(t, sc, "score_insuf@test.com", "public") + order := makeScoringOrder(t, sc, prov) + + err := ApplyProviderScoreChange(sc.ctx, order.ID, + ScoreEventCancelInsufficientFunds, + decimal.NewFromFloat(PenaltyCancelInsufficientFunds)) + require.NoError(t, err) + + updated, err := sc.client.ProviderOrderToken.Get(sc.ctx, pot.ID) + require.NoError(t, err) + assert.Equal(t, decimal.NewFromFloat(PenaltyCancelInsufficientFunds).String(), updated.Score.String()) + }) + + t.Run("penalty_provider_fault_cancel", func(t *testing.T) { + prov, pot := makeScoringProvider(t, sc, "score_fault@test.com", "public") + order := makeScoringOrder(t, sc, prov) + + err := ApplyProviderScoreChange(sc.ctx, order.ID, + ScoreEventCancelProviderFault, + decimal.NewFromFloat(PenaltyCancelProviderFault)) + require.NoError(t, err) + + updated, err := sc.client.ProviderOrderToken.Get(sc.ctx, pot.ID) + require.NoError(t, err) + assert.Equal(t, decimal.NewFromFloat(PenaltyCancelProviderFault).String(), updated.Score.String()) + }) + + t.Run("apply_for_specific_provider_by_id", func(t *testing.T) { + prov, pot := makeScoringProvider(t, sc, "score_byprovid@test.com", "public") + order := makeScoringOrder(t, sc, prov) + + err := ApplyProviderScoreChangeForProvider(sc.ctx, order.ID, prov.ID, + ScoreEventOrderRequestExpired, + decimal.NewFromFloat(PenaltyOrderRequestExpired)) + require.NoError(t, err) + + updated, err := sc.client.ProviderOrderToken.Get(sc.ctx, pot.ID) + require.NoError(t, err) + assert.Equal(t, decimal.NewFromFloat(PenaltyOrderRequestExpired).String(), updated.Score.String()) + }) + + t.Run("apply_for_specific_provider_idempotent", func(t *testing.T) { + prov, pot := makeScoringProvider(t, sc, "score_byprovid_idem@test.com", "public") + order := makeScoringOrder(t, sc, prov) + + require.NoError(t, ApplyProviderScoreChangeForProvider(sc.ctx, order.ID, prov.ID, + ScoreEventOrderRequestExpired, decimal.NewFromFloat(-0.5))) + require.NoError(t, ApplyProviderScoreChangeForProvider(sc.ctx, order.ID, prov.ID, + ScoreEventOrderRequestExpired, decimal.NewFromFloat(-0.5))) + + updated, err := sc.client.ProviderOrderToken.Get(sc.ctx, pot.ID) + require.NoError(t, err) + assert.Equal(t, decimal.NewFromFloat(-0.5).String(), updated.Score.String()) + }) + + t.Run("skips_empty_provider_id_for_specific_provider", func(t *testing.T) { + order := makeScoringOrder(t, sc, func() *ent.ProviderProfile { + prov, _ := makeScoringProvider(t, sc, "score_emptyid@test.com", "public") + return prov + }()) + err := ApplyProviderScoreChangeForProvider(sc.ctx, order.ID, "", ScoreEventFulfilledValidated, decimal.NewFromFloat(1.0)) + assert.NoError(t, err) + }) +} + +func getProviderPOT(t *testing.T, ctx context.Context, provID string) *ent.ProviderOrderToken { + t.Helper() + pot, err := db.Client.ProviderOrderToken.Query(). + Where(providerordertoken.HasProviderWith(providerprofile.IDEQ(provID))). + Only(ctx) + require.NoError(t, err) + return pot +} diff --git a/services/assignment/select.go b/services/assignment/select.go new file mode 100644 index 000000000..d7b96c6c0 --- /dev/null +++ b/services/assignment/select.go @@ -0,0 +1,526 @@ +package assignment + +import ( + "context" + "errors" + "fmt" + "slices" + "time" + + "github.com/google/uuid" + "github.com/paycrest/aggregator/config" + "github.com/paycrest/aggregator/ent" + "github.com/paycrest/aggregator/ent/fiatcurrency" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/providerbalances" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerprofile" + "github.com/paycrest/aggregator/ent/token" + "github.com/paycrest/aggregator/storage" + "github.com/paycrest/aggregator/types" + "github.com/paycrest/aggregator/utils" + "github.com/paycrest/aggregator/utils/logger" + "github.com/shopspring/decimal" +) + +// AssignPaymentOrderWithTrigger assigns using DB-only candidate ranking +// (score DESC, 24h volume ASC, last_order_assigned_at ASC NULLS FIRST, id ASC). +func (s *Service) AssignPaymentOrderWithTrigger(ctx context.Context, order types.PaymentOrderFields, trigger string) error { + ctx, cancel := context.WithTimeout(ctx, assignPaymentOrderTimeout) + defer cancel() + + if trigger == "" { + trigger = AssignmentTriggerInitial + } + orderConf := config.OrderConfig() + maxRetryAttempts := orderConf.ProviderMaxRetryAttempts + if maxRetryAttempts < 1 { + maxRetryAttempts = 1 + } + + var assignmentLockHeld bool + currentOrder, err := storage.Client.PaymentOrder.Get(ctx, order.ID) + if err == nil { + if currentOrder.Status != paymentorder.StatusPending { + logger.WithFields(logger.Fields{"OrderID": order.ID.String(), "Status": currentOrder.Status}).Errorf("AssignPaymentOrder: Order is not in pending state, skipping assignment") + s.recordAssignmentRun(ctx, order.ID, trigger, AssignmentRunResultSkipped, nil, nil, false, nil, nil, fmt.Errorf("AssignPaymentOrder: Order is not in pending state (status=%s)", currentOrder.Status)) + return nil + } + orderKey := fmt.Sprintf("order_request_%s", order.ID) + releaseAssignLock, lockErr := acquireOrderAssignmentLock(ctx, order.ID) + if lockErr != nil { + if errors.Is(lockErr, ErrAssignmentLockHeld) { + rerr := resolveConcurrentAssignmentStart(ctx, order, orderKey) + if rerr != nil { + s.recordAssignmentRun(ctx, order.ID, trigger, AssignmentRunResultError, nil, nil, false, nil, nil, rerr) + } else { + s.recordAssignmentRun(ctx, order.ID, trigger, AssignmentRunResultSkipped, nil, nil, false, nil, nil, fmt.Errorf("AssignPaymentOrder: skipped concurrent assignment (order_request present or resolved)")) + } + return rerr + } + s.recordAssignmentRun(ctx, order.ID, trigger, AssignmentRunResultError, nil, nil, false, nil, nil, fmt.Errorf("redis assignment lock: %w", lockErr)) + return lockErr + } + defer releaseAssignLock() + assignmentLockHeld = true + exists, rerr := storage.RedisClient.Exists(ctx, orderKey).Result() + if rerr == nil && exists > 0 { + logger.WithFields(logger.Fields{"OrderID": order.ID.String()}).Errorf("AssignPaymentOrder: Order request already exists, skipping duplicate assignment") + s.recordAssignmentRun(ctx, order.ID, trigger, AssignmentRunResultSkipped, nil, nil, false, nil, nil, fmt.Errorf("AssignPaymentOrder: Order request already exists in Redis; skipping duplicate assignment")) + return nil + } + } else if !ent.IsNotFound(err) { + logger.WithFields(logger.Fields{"Error": fmt.Sprintf("%v", err), "OrderID": order.ID.String()}).Errorf("AssignPaymentOrder: Failed to check order status") + s.recordAssignmentRun(ctx, order.ID, trigger, AssignmentRunResultError, nil, nil, false, nil, nil, fmt.Errorf("AssignPaymentOrder: failed to check order status: %w", err)) + return err + } + + excludeList, err := storage.RedisClient.LRange(ctx, fmt.Sprintf("order_exclude_list_%s", order.ID), 0, -1).Result() + if err != nil { + logger.WithFields(logger.Fields{"Error": fmt.Sprintf("%v", err), "OrderID": order.ID.String()}).Errorf("failed to get exclude list") + s.recordAssignmentRun(ctx, order.ID, trigger, AssignmentRunResultError, nil, nil, false, nil, nil, fmt.Errorf("failed to get exclude list: %w", err)) + return err + } + + orderEnt, err := storage.Client.PaymentOrder.Query(). + Where(paymentorder.IDEQ(order.ID)). + WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() }). + WithProvider(). + Only(ctx) + if err != nil { + s.recordAssignmentRun(ctx, order.ID, trigger, AssignmentRunResultError, nil, nil, false, nil, nil, fmt.Errorf("load order: %w", err)) + return fmt.Errorf("assign: load order: %w", err) + } + + workOrder, err := paymentOrderFieldsFromEnt(orderEnt) + if err != nil { + s.recordAssignmentRun(ctx, order.ID, trigger, AssignmentRunResultError, nil, nil, false, nil, nil, err) + return fmt.Errorf("assign: build order fields: %w", err) + } + + var rateSide RateSide + switch orderEnt.Direction { + case paymentorder.DirectionOnramp: + rateSide = RateSideBuy + default: + rateSide = RateSideSell + } + + if workOrder.ProviderID != "" { + excludeCount := s.countProviderInExcludeList(excludeList, workOrder.ProviderID) + shouldSkip := false + if workOrder.OrderType == "otc" { + shouldSkip = excludeCount > 0 + } else { + shouldSkip = excludeCount >= maxRetryAttempts + } + if !shouldSkip { + if workOrder.OrderType != "otc" && orderConf.ProviderStuckFulfillmentThreshold > 0 { + stuckCount, errStuck := utils.GetProviderStuckOrderCount(ctx, workOrder.ProviderID) + if errStuck == nil && stuckCount >= orderConf.ProviderStuckFulfillmentThreshold { + logger.WithFields(logger.Fields{ + "OrderID": workOrder.ID.String(), + "ProviderID": workOrder.ProviderID, + "StuckCount": stuckCount, + "Threshold": orderConf.ProviderStuckFulfillmentThreshold, + }).Warnf("assign: pre-set provider skipped (stuck threshold); using public selection") + exclKey := fmt.Sprintf("order_exclude_list_%s", workOrder.ID) + if pushErr := storage.RedisClient.RPush(ctx, exclKey, workOrder.ProviderID).Err(); pushErr != nil { + logger.WithFields(logger.Fields{"OrderID": workOrder.ID.String(), "Error": pushErr.Error()}).Warnf("assign: failed to push pre-set provider to exclude list after stuck skip") + } else { + excludeList = append(excludeList, workOrder.ProviderID) + } + } else { + if errStuck != nil { + logger.WithFields(logger.Fields{"Error": fmt.Sprintf("%v", errStuck), "OrderID": workOrder.ID.String()}).Errorf("failed to get stuck order count for pre-set provider") + } + assigned, provider, presetErr := s.tryUsePreSetProvider(ctx, workOrder, assignmentLockHeld) + if presetErr != nil { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultError, strPtr(workOrder.ProviderID), nil, false, nil, nil, presetErr) + return fmt.Errorf("assign: pre-set provider: %w", presetErr) + } + if assigned { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultAssigned, strPtr(workOrder.ProviderID), nil, false, nil, nil, nil) + return nil + } + if provider != nil && provider.VisibilityMode == providerprofile.VisibilityModePrivate { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultSkipped, strPtr(workOrder.ProviderID), nil, false, nil, nil, nil) + return nil + } + } + } else { + assigned, provider, presetErr := s.tryUsePreSetProvider(ctx, workOrder, assignmentLockHeld) + if presetErr != nil { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultError, strPtr(workOrder.ProviderID), nil, false, nil, nil, presetErr) + return fmt.Errorf("assign: pre-set provider: %w", presetErr) + } + if assigned { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultAssigned, strPtr(workOrder.ProviderID), nil, false, nil, nil, nil) + return nil + } + if provider != nil && provider.VisibilityMode == providerprofile.VisibilityModePrivate { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultSkipped, strPtr(workOrder.ProviderID), nil, false, nil, nil, nil) + return nil + } + } + } + } + + inst, err := utils.GetInstitutionByCode(ctx, workOrder.Institution, true) + if err != nil || inst == nil || inst.Edges.FiatCurrency == nil { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultError, nil, nil, false, nil, nil, fmt.Errorf("resolve institution currency")) + return fmt.Errorf("assign: institution or fiat currency not found for %q", workOrder.Institution) + } + fiatCurrency := inst.Edges.FiatCurrency + + orderNet := resolveOrderNetwork(workOrder) + if workOrder.Token == nil || orderNet == nil { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultError, nil, nil, false, nil, nil, fmt.Errorf("order token/network not loaded from DB")) + return fmt.Errorf("assign: token/network required on payment order") + } + networkID := orderNet.Identifier + + buySnap, sellSnap, err := s.ensureAssignmentMarketSnapshot(ctx, orderEnt, fiatCurrency) + if err != nil { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultError, nil, nil, false, nil, nil, err) + return fmt.Errorf("assign: market snapshot: %w", err) + } + + isOTC := orderEnt.OrderType == paymentorder.OrderTypeOtc + fiatNeed := workOrder.Amount.Mul(workOrder.Rate).RoundBank(0) + + pq := storage.Client.ProviderOrderToken.Query(). + Where( + providerordertoken.HasCurrencyWith(fiatcurrency.IDEQ(fiatCurrency.ID)), + providerordertoken.HasTokenWith(token.IDEQ(workOrder.Token.ID)), + providerordertoken.NetworkEQ(networkID), + providerordertoken.SettlementAddressNEQ(""), + providerordertoken.HasProviderWith( + providerprofile.IsActive(true), + providerprofile.VisibilityModeEQ(providerprofile.VisibilityModePublic), + providerprofile.HasProviderBalancesWith( + providerbalances.HasFiatCurrencyWith(fiatcurrency.IDEQ(fiatCurrency.ID)), + providerbalances.IsAvailableEQ(true), + providerbalances.AvailableBalanceGTE(fiatNeed), + ), + ), + ) + if orderConf.FallbackProviderID != "" { + pq = pq.Where(providerordertoken.HasProviderWith(providerprofile.IDNEQ(orderConf.FallbackProviderID))) + } + pots, err := pq.WithProvider().WithCurrency().All(ctx) + if err != nil { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultError, nil, nil, false, &buySnap, &sellSnap, err) + return fmt.Errorf("assign: query candidates: %w", err) + } + + var candidates []*ent.ProviderOrderToken + for _, pot := range pots { + if !amountInRangeForOrder(pot, workOrder.Amount, isOTC) { + continue + } + candidates = append(candidates, pot) + } + + if len(candidates) == 0 { + if !isOTC { + if fbErr := s.TryFallbackAssignment(ctx, orderEnt, assignmentLockHeld); fbErr == nil { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultFallback, strPtr(orderConf.FallbackProviderID), nil, true, &buySnap, &sellSnap, nil) + return nil + } + } + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultNoProvider, nil, nil, false, &buySnap, &sellSnap, nil) + return fmt.Errorf("no provider matched for order") + } + + provIDs := make([]string, 0, len(candidates)) + seen := map[string]struct{}{} + for _, pot := range candidates { + pid := pot.Edges.Provider.ID + if _, ok := seen[pid]; ok { + continue + } + seen[pid] = struct{}{} + provIDs = append(provIDs, pid) + } + volMap, err := recentFiatVolumeByProvider(ctx, provIDs) + if err != nil { + logger.WithFields(logger.Fields{"Error": err.Error()}).Warnf("assign: recent volume query failed; using zero volume") + volMap = map[string]decimal.Decimal{} + } + + var stuckCountByProvider map[string]int + if !isOTC && orderConf.ProviderStuckFulfillmentThreshold > 0 && len(provIDs) > 0 { + stuckCountByProvider, err = utils.StuckOrderCountsByProviderIDs(ctx, provIDs) + if err != nil { + logger.WithFields(logger.Fields{"Error": err.Error()}).Warnf("assign: stuck-order count query failed; treating stuck count as zero") + stuckCountByProvider = map[string]int{} + } + } + + slices.SortStableFunc(candidates, func(a, b *ent.ProviderOrderToken) int { + if c := b.Score.Cmp(a.Score); c != 0 { + return c + } + va := volMap[a.Edges.Provider.ID] + vb := volMap[b.Edges.Provider.ID] + if c := va.Cmp(vb); c != 0 { + return c + } + if c := cmpLastAssigned(a, b); c != 0 { + return c + } + if a.ID < b.ID { + return -1 + } + if a.ID > b.ID { + return 1 + } + return 0 + }) + + for _, pot := range candidates { + pid := pot.Edges.Provider.ID + if orderConf.FallbackProviderID != "" && pid == orderConf.FallbackProviderID { + continue + } + exc := s.countProviderInExcludeList(excludeList, pid) + if isOTC { + if exc > 0 { + continue + } + } else { + if exc >= maxRetryAttempts { + continue + } + } + if !isOTC && orderConf.ProviderStuckFulfillmentThreshold > 0 { + stuck := stuckCountByProvider[pid] + if stuck >= orderConf.ProviderStuckFulfillmentThreshold { + continue + } + } + + provRate := providerRateForAssignment(pot, rateSide, buySnap, sellSnap) + if provRate.IsZero() { + continue + } + allowed := workOrder.Rate.Mul(pot.RateSlippage.Div(decimal.NewFromInt(100))) + if provRate.Sub(workOrder.Rate).Abs().GreaterThan(allowed) { + continue + } + + bal, berr := s.balanceService.GetProviderFiatBalance(ctx, pid, fiatCurrency.Code) + if berr != nil || !s.balanceService.CheckBalanceSufficiency(bal, fiatNeed) { + continue + } + + assignOrder := workOrder + assignOrder.ProviderID = pid + var assignErr error + if isOTC { + assignErr = s.assignOtcOrder(ctx, assignOrder, assignmentLockHeld) + } else { + assignErr = s.sendOrderRequest(ctx, assignOrder, assignmentLockHeld) + } + if assignErr != nil { + if errors.Is(assignErr, ErrAssignmentLockHeld) { + logger.WithFields(logger.Fields{"OrderID": workOrder.ID.String(), "ProviderID": pid}).Warnf("assign: concurrent assignment for order; stopping candidate loop") + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultError, &pid, &pot.ID, false, &buySnap, &sellSnap, assignErr) + return assignErr + } + logger.WithFields(logger.Fields{"OrderID": workOrder.ID.String(), "ProviderID": pid, "Error": assignErr.Error()}).Errorf("assign: failed to assign to candidate") + continue + } + + now := time.Now() + if _, uerr := storage.Client.ProviderOrderToken.UpdateOneID(pot.ID).SetLastOrderAssignedAt(now).Save(ctx); uerr != nil { + logger.WithFields(logger.Fields{ + "OrderID": workOrder.ID.String(), + "ProviderID": pid, + "ProviderOrderTokenID": pot.ID, + "Error": uerr.Error(), + }).Warnf("assign: failed to update last_order_assigned_at") + } + + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultAssigned, &pid, &pot.ID, false, &buySnap, &sellSnap, nil) + return nil + } + + if !isOTC { + if fbErr := s.TryFallbackAssignment(ctx, orderEnt, assignmentLockHeld); fbErr == nil { + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultFallback, strPtr(orderConf.FallbackProviderID), nil, true, &buySnap, &sellSnap, nil) + return nil + } + } + s.recordAssignmentRun(ctx, workOrder.ID, trigger, AssignmentRunResultNoProvider, nil, nil, false, &buySnap, &sellSnap, nil) + return fmt.Errorf("no provider matched for order") +} + +func strPtr(s string) *string { return &s } + +// resolveOrderNetwork returns the network for assignment using PaymentOrderFields.Network when set, +// otherwise Token.Edges.Network (kept in sync by paymentOrderFieldsFromEnt). +func resolveOrderNetwork(f types.PaymentOrderFields) *ent.Network { + if f.Network != nil { + return f.Network + } + if f.Token != nil { + return f.Token.Edges.Network + } + return nil +} + +// paymentOrderFieldsFromEnt builds assignment input from the persisted order and loaded edges (token+network+provider). +func paymentOrderFieldsFromEnt(po *ent.PaymentOrder) (types.PaymentOrderFields, error) { + if po.Edges.Token == nil { + return types.PaymentOrderFields{}, fmt.Errorf("payment order %s has no token loaded", po.ID) + } + tok := po.Edges.Token + var net *ent.Network + if tok.Edges.Network != nil { + net = tok.Edges.Network + } + fields := types.PaymentOrderFields{ + ID: po.ID, + OrderType: po.OrderType.String(), + Token: tok, + Network: net, + GatewayID: po.GatewayID, + Amount: po.Amount, + Rate: po.Rate, + ProtocolFee: po.ProtocolFee, + AmountInUSD: po.AmountInUsd, + BlockNumber: po.BlockNumber, + TxHash: po.TxHash, + Institution: po.Institution, + AccountIdentifier: po.AccountIdentifier, + AccountName: po.AccountName, + Sender: po.Sender, + MessageHash: po.MessageHash, + Memo: po.Memo, + Metadata: po.Metadata, + UpdatedAt: po.UpdatedAt, + CreatedAt: po.CreatedAt, + } + if po.Edges.Provider != nil { + fields.ProviderID = po.Edges.Provider.ID + } + // Keep top-level Network and Token.Edges.Network aligned for downstream checks and future loaders. + if fields.Network != nil && fields.Token != nil && fields.Token.Edges.Network == nil { + fields.Token.Edges.Network = fields.Network + } else if fields.Token != nil && fields.Token.Edges.Network != nil && fields.Network == nil { + fields.Network = fields.Token.Edges.Network + } + return fields, nil +} + +func cmpLastAssigned(a, b *ent.ProviderOrderToken) int { + la, lb := a.LastOrderAssignedAt, b.LastOrderAssignedAt + switch { + case la == nil && lb == nil: + return 0 + case la == nil: + return -1 + case lb == nil: + return 1 + default: + return la.Compare(*lb) + } +} + +func amountInRangeForOrder(pot *ent.ProviderOrderToken, amount decimal.Decimal, isOTC bool) bool { + if isOTC { + return !amount.LessThan(pot.MinOrderAmountOtc) && !amount.GreaterThan(pot.MaxOrderAmountOtc) + } + // Regular orders: only regular min/max; do not admit via OTC bounds (would mismatch assignOtcOrder vs sendOrderRequest). + return !amount.LessThan(pot.MinOrderAmount) && !amount.GreaterThan(pot.MaxOrderAmount) +} + +func providerRateForAssignment(pot *ent.ProviderOrderToken, side RateSide, buySnap, sellSnap decimal.Decimal) decimal.Decimal { + switch side { + case RateSideBuy: + if !pot.FixedBuyRate.IsZero() { + return pot.FixedBuyRate + } + if !buySnap.IsZero() { + return buySnap.Add(pot.FloatingBuyDelta).RoundBank(2) + } + case RateSideSell: + if !pot.FixedSellRate.IsZero() { + return pot.FixedSellRate + } + if !sellSnap.IsZero() { + return sellSnap.Add(pot.FloatingSellDelta).RoundBank(2) + } + } + return decimal.Zero +} + +func assignmentMarketRatesMatchFiat(storedBuy, storedSell, fcBuy, fcSell decimal.Decimal) bool { + return rateCloseEnoughForAssignment(storedBuy, fcBuy) && rateCloseEnoughForAssignment(storedSell, fcSell) +} + +func rateCloseEnoughForAssignment(a, b decimal.Decimal) bool { + if a.IsZero() && b.IsZero() { + return true + } + diff := a.Sub(b).Abs() + maxAbs := a.Abs() + if b.Abs().GreaterThan(maxAbs) { + maxAbs = b.Abs() + } + if maxAbs.IsZero() { + return diff.IsZero() + } + return diff.Div(maxAbs).LessThan(assignmentMarketRateRelTol) +} + +func (s *Service) ensureAssignmentMarketSnapshot(ctx context.Context, po *ent.PaymentOrder, fc *ent.FiatCurrency) (buy, sell decimal.Decimal, err error) { + if po.AssignmentMarketBuyRate != nil && po.AssignmentMarketSellRate != nil { + stBuy, stSell := *po.AssignmentMarketBuyRate, *po.AssignmentMarketSellRate + if assignmentMarketRatesMatchFiat(stBuy, stSell, fc.MarketBuyRate, fc.MarketSellRate) { + return stBuy, stSell, nil + } + } + buy = fc.MarketBuyRate + sell = fc.MarketSellRate + _, err = storage.Client.PaymentOrder.UpdateOneID(po.ID). + SetAssignmentMarketBuyRate(buy). + SetAssignmentMarketSellRate(sell). + Save(ctx) + if err != nil { + return decimal.Zero, decimal.Zero, err + } + return buy, sell, nil +} + +func recentFiatVolumeByProvider(ctx context.Context, providerIDs []string) (map[string]decimal.Decimal, error) { + since := time.Now().Add(-RecentVolumeWindow) + return utils.RecentFiatVolumeByProvider(ctx, since, providerIDs) +} + +func (s *Service) recordAssignmentRun(ctx context.Context, orderID uuid.UUID, trigger, result string, provID *string, potID *int, usedFallback bool, buy, sell *decimal.Decimal, runErr error) { + auditCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), recordAssignmentRunTimeout) + defer cancel() + + b := storage.Client.ProviderAssignmentRun.Create().SetPaymentOrderID(orderID).SetTrigger(trigger).SetResult(result).SetUsedFallback(usedFallback) + if provID != nil { + b.SetAssignedProviderID(*provID) + } + if potID != nil { + b.SetProviderOrderTokenID(*potID) + } + if buy != nil { + b.SetMarketBuyRateSnapshot(*buy) + } + if sell != nil { + b.SetMarketSellRateSnapshot(*sell) + } + if runErr != nil { + b.SetErrorMessage(runErr.Error()) + } + if _, err := b.Save(auditCtx); err != nil { + logger.WithFields(logger.Fields{"OrderID": orderID.String(), "Error": err.Error()}).Errorf("recordAssignmentRun: failed to persist") + } +} diff --git a/services/assignment/select_test.go b/services/assignment/select_test.go new file mode 100644 index 000000000..1f782bfd8 --- /dev/null +++ b/services/assignment/select_test.go @@ -0,0 +1,541 @@ +package assignment + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/google/uuid" + "github.com/paycrest/aggregator/ent" + "github.com/paycrest/aggregator/ent/fiatcurrency" + "github.com/paycrest/aggregator/ent/paymentorder" + "github.com/paycrest/aggregator/ent/providerassignmentrun" + "github.com/paycrest/aggregator/ent/providerbalances" + "github.com/paycrest/aggregator/ent/providerprofile" + tokenEnt "github.com/paycrest/aggregator/ent/token" + userEnt "github.com/paycrest/aggregator/ent/user" + svc "github.com/paycrest/aggregator/services" + db "github.com/paycrest/aggregator/storage" + "github.com/paycrest/aggregator/types" + "github.com/paycrest/aggregator/utils/test" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// assignCtx holds only the shared (across all subtests) fixtures: network, token, mock HTTP server. +type assignCtx struct { + ctx context.Context + client *ent.Client + tok *ent.Token // loaded with WithNetwork() + mockURL string // mock HTTP server URL every provider will use +} + +// subEnv provides per-subtest isolation: a unique FiatCurrency + Institution pair. +// The DB candidate query filters by currency ID, so providers from other subtests +// are invisible to a subtest using a different subEnv. +type subEnv struct { + cur *ent.FiatCurrency + instCode string +} + +// newAssignCtx creates the shared network/token/mock-server fixtures. +func newAssignCtx(t *testing.T) assignCtx { + t.Helper() + ctx := context.Background() + client := db.Client + + netw, err := client.Network.Create(). + SetIdentifier("assign-net"). + SetChainID(56). + SetRPCEndpoint("ws://localhost:8545"). + SetBlockTime(decimal.NewFromFloat(3)). + SetFee(decimal.NewFromFloat(0.1)). + SetIsTestnet(true). + Save(ctx) + require.NoError(t, err) + + tok, err := client.Token.Create(). + SetSymbol("ASNTOK"). + SetContractAddress("0x2222222222222222222222222222222222222222"). + SetDecimals(6). + SetNetworkID(netw.ID). + SetIsEnabled(true). + SetBaseCurrency("A01"). + Save(ctx) + require.NoError(t, err) + tok, err = client.Token.Query().Where(tokenEnt.IDEQ(tok.ID)).WithNetwork().Only(ctx) + require.NoError(t, err) + + mockSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"status":"success","message":"ok"}`)) + })) + t.Cleanup(mockSrv.Close) + + return assignCtx{ctx: ctx, client: client, tok: tok, mockURL: mockSrv.URL} +} + +// newSubEnv creates a unique FiatCurrency + Institution for a single subtest. +// code must be unique across all subtests (e.g. "A01", "A02", …). +func newSubEnv(t *testing.T, ac assignCtx, code string) subEnv { + t.Helper() + cur, err := ac.client.FiatCurrency.Create(). + SetCode(code). + SetShortName(code). + SetSymbol(code). + SetName(code + " Test Currency"). + SetDecimals(2). + SetIsEnabled(true). + SetMarketBuyRate(decimal.NewFromFloat(1500)). + SetMarketSellRate(decimal.NewFromFloat(1500)). + Save(ac.ctx) + require.NoError(t, err) + + instCode := code + "BNK" + _, err = ac.client.Institution.Create(). + SetCode(instCode). + SetName(instCode + " Institution"). + SetFiatCurrencyID(cur.ID). + Save(ac.ctx) + require.NoError(t, err) + + return subEnv{cur: cur, instCode: instCode} +} + +// makeAssignProvider creates a fully eligible public provider scoped to se's currency. +func makeAssignProvider(t *testing.T, ac assignCtx, se subEnv, email string, rate, score, balance float64) *ent.ProviderProfile { + t.Helper() + ctx := ac.ctx + client := ac.client + + u, err := test.CreateTestUser(map[string]interface{}{"scope": "provider", "email": email}) + require.NoError(t, err) + + prov, err := test.CreateTestProviderProfile(map[string]interface{}{ + "user_id": u.ID, + "currency_id": se.cur.ID, + "visibility_mode": "public", + }) + require.NoError(t, err) + + _, err = client.ProviderProfile.UpdateOneID(prov.ID). + SetIsActive(true). + SetHostIdentifier(ac.mockURL). + Save(ctx) + require.NoError(t, err) + + _, err = client.User.UpdateOneID(u.ID). + SetKybVerificationStatus(userEnt.KybVerificationStatusApproved). + Save(ctx) + require.NoError(t, err) + + apiKeySvc := svc.NewAPIKeyService() + _, _, err = apiKeySvc.GenerateAPIKey(ctx, nil, nil, prov) + require.NoError(t, err) + + pot, err := test.AddProviderOrderTokenToProvider(map[string]interface{}{ + "provider": prov, + "currency_id": se.cur.ID, + "token_id": ac.tok.ID, + "network": ac.tok.Edges.Network.Identifier, + "fixed_sell_rate": decimal.NewFromFloat(rate), + "max_order_amount": decimal.NewFromFloat(10_000), + "min_order_amount": decimal.NewFromFloat(1), + "max_order_amount_otc": decimal.NewFromFloat(10_000), + "min_order_amount_otc": decimal.NewFromFloat(100), + }) + require.NoError(t, err) + + if score != 0 { + _, err = client.ProviderOrderToken.UpdateOneID(pot.ID). + SetScore(decimal.NewFromFloat(score)). + Save(ctx) + require.NoError(t, err) + } + + _, err = client.ProviderBalances.Update(). + Where(providerbalances.HasProviderWith(providerprofile.IDEQ(prov.ID))). + Where(providerbalances.HasFiatCurrencyWith(fiatcurrency.IDEQ(se.cur.ID))). + SetAvailableBalance(decimal.NewFromFloat(balance)). + SetTotalBalance(decimal.NewFromFloat(balance)). + SetIsAvailable(true). + Save(ctx) + require.NoError(t, err) + + return prov +} + +// makeAssignOrder creates a pending payment order referencing se's institution. +func makeAssignOrder(t *testing.T, ac assignCtx, se subEnv, amount, rate float64) *ent.PaymentOrder { + t.Helper() + order, err := ac.client.PaymentOrder.Create(). + SetAmount(decimal.NewFromFloat(amount)). + SetAmountInUsd(decimal.NewFromFloat(amount)). + SetRate(decimal.NewFromFloat(rate)). + SetStatus(paymentorder.StatusPending). + SetInstitution(se.instCode). + SetAccountIdentifier("9876543210"). + SetAccountName("Assign Test Account"). + SetMemo("assignment test"). + SetToken(ac.tok). + SetGatewayID(uuid.New().String()). + SetBlockNumber(1). + Save(ac.ctx) + require.NoError(t, err) + return order +} + +// orderFields converts a PaymentOrder into the types.PaymentOrderFields the assignment service expects. +func orderFields(order *ent.PaymentOrder, tok *ent.Token, orderType string) types.PaymentOrderFields { + if orderType == "" { + orderType = string(paymentorder.OrderTypeRegular) + } + return types.PaymentOrderFields{ + ID: order.ID, + OrderType: orderType, + GatewayID: order.GatewayID, + Amount: order.Amount, + Rate: order.Rate, + BlockNumber: order.BlockNumber, + Institution: order.Institution, + AccountIdentifier: order.AccountIdentifier, + AccountName: order.AccountName, + Memo: order.Memo, + Token: tok, + Network: tok.Edges.Network, + } +} + +// assignedProviderID reads the providerId stored in the Redis order_request hash. +func assignedProviderID(t *testing.T, orderID uuid.UUID) string { + t.Helper() + key := fmt.Sprintf("order_request_%s", orderID) + pid, err := db.RedisClient.HGet(context.Background(), key, "providerId").Result() + require.NoError(t, err, "order_request key should exist after successful assignment") + return pid +} + +// TestAssignment exercises the DB-only provider selection engine. +// Each subtest creates its own FiatCurrency (via newSubEnv) so that the +// candidate DB query only sees that subtest's providers. +func TestAssignment(t *testing.T) { + newTestDB(t, "assign_tests") + ac := newAssignCtx(t) + s := New() + + t.Run("score_ordering_higher_score_wins", func(t *testing.T) { + se := newSubEnv(t, ac, "A01") + pLow := makeAssignProvider(t, ac, se, "a01_low@t.com", 1500, 1.0, 1_000_000) + pHigh := makeAssignProvider(t, ac, se, "a01_high@t.com", 1500, 5.0, 1_000_000) + order := makeAssignOrder(t, ac, se, 10, 1500) + + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + assert.Equal(t, pHigh.ID, assignedProviderID(t, order.ID), + "provider with higher score should be assigned first") + _ = pLow + }) + + t.Run("last_assigned_at_tiebreak_nil_wins", func(t *testing.T) { + se := newSubEnv(t, ac, "A02") + pRecent := makeAssignProvider(t, ac, se, "a02_recent@t.com", 1500, 0, 1_000_000) + pNever := makeAssignProvider(t, ac, se, "a02_never@t.com", 1500, 0, 1_000_000) + + recentPot := getProviderPOT(t, ac.ctx, pRecent.ID) + _, err := ac.client.ProviderOrderToken.UpdateOneID(recentPot.ID). + SetLastOrderAssignedAt(time.Now().Add(-10 * time.Second)). + Save(ac.ctx) + require.NoError(t, err) + + order := makeAssignOrder(t, ac, se, 10, 1500) + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + assert.Equal(t, pNever.ID, assignedProviderID(t, order.ID), + "provider with nil last_order_assigned_at should win over recently assigned one") + _ = pRecent + }) + + t.Run("insufficient_balance_skipped", func(t *testing.T) { + se := newSubEnv(t, ac, "A03") + pPoor := makeAssignProvider(t, ac, se, "a03_poor@t.com", 1500, 0, 100) + pRich := makeAssignProvider(t, ac, se, "a03_rich@t.com", 1500, 0, 1_000_000) + + _, err := ac.client.ProviderOrderToken.UpdateOneID( + getProviderPOT(t, ac.ctx, pPoor.ID).ID, + ).SetScore(decimal.NewFromFloat(10)).Save(ac.ctx) + require.NoError(t, err) + + order := makeAssignOrder(t, ac, se, 100, 1500) + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + assert.Equal(t, pRich.ID, assignedProviderID(t, order.ID), + "provider with insufficient balance must be skipped") + _ = pPoor + }) + + t.Run("amount_out_of_range_skipped", func(t *testing.T) { + se := newSubEnv(t, ac, "A04") + pSmall := makeAssignProvider(t, ac, se, "a04_small@t.com", 1500, 10, 1_000_000) + pAny := makeAssignProvider(t, ac, se, "a04_any@t.com", 1500, 0, 1_000_000) + + _, err := ac.client.ProviderOrderToken.UpdateOneID( + getProviderPOT(t, ac.ctx, pSmall.ID).ID, + ).SetMaxOrderAmount(decimal.NewFromFloat(5)). + SetMinOrderAmount(decimal.NewFromFloat(1)). + Save(ac.ctx) + require.NoError(t, err) + + order := makeAssignOrder(t, ac, se, 50, 1500) + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + assert.Equal(t, pAny.ID, assignedProviderID(t, order.ID), + "provider with amount outside their min/max range must be skipped") + _ = pSmall + }) + + t.Run("rate_mismatch_skipped", func(t *testing.T) { + se := newSubEnv(t, ac, "A05") + pBad := makeAssignProvider(t, ac, se, "a05_bad@t.com", 2000, 10, 1_000_000) + pGood := makeAssignProvider(t, ac, se, "a05_good@t.com", 1500, 0, 1_000_000) + + order := makeAssignOrder(t, ac, se, 10, 1500) + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + assert.Equal(t, pGood.ID, assignedProviderID(t, order.ID), + "provider with rate outside slippage tolerance must be skipped") + _ = pBad + }) + + t.Run("exclude_list_regular_skips_after_max_retries", func(t *testing.T) { + se := newSubEnv(t, ac, "A06") + pExcl := makeAssignProvider(t, ac, se, "a06_excl@t.com", 1500, 10, 1_000_000) + pFall := makeAssignProvider(t, ac, se, "a06_fall@t.com", 1500, 0, 1_000_000) + + order := makeAssignOrder(t, ac, se, 10, 1500) + + excludeKey := fmt.Sprintf("order_exclude_list_%s", order.ID) + for i := 0; i < 3; i++ { + require.NoError(t, db.RedisClient.RPush(ac.ctx, excludeKey, pExcl.ID).Err()) + } + + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + assert.Equal(t, pFall.ID, assignedProviderID(t, order.ID), + "provider appearing 3× in exclude list must be skipped for regular order") + _ = pExcl + }) + + t.Run("exclude_list_otc_skips_after_one_appearance", func(t *testing.T) { + se := newSubEnv(t, ac, "A07") + pExcl := makeAssignProvider(t, ac, se, "a07_excl@t.com", 1500, 10, 1_000_000) + pFall := makeAssignProvider(t, ac, se, "a07_fall@t.com", 1500, 0, 1_000_000) + + order, err := ac.client.PaymentOrder.Create(). + SetAmount(decimal.NewFromFloat(200)). + SetAmountInUsd(decimal.NewFromFloat(200)). + SetRate(decimal.NewFromFloat(1500)). + SetStatus(paymentorder.StatusPending). + SetInstitution(se.instCode). + SetAccountIdentifier("1111111111"). + SetAccountName("OTC Account"). + SetMemo("otc test"). + SetToken(ac.tok). + SetOrderType(paymentorder.OrderTypeOtc). + SetGatewayID(uuid.New().String()). + SetBlockNumber(1). + Save(ac.ctx) + require.NoError(t, err) + + excludeKey := fmt.Sprintf("order_exclude_list_%s", order.ID) + require.NoError(t, db.RedisClient.RPush(ac.ctx, excludeKey, pExcl.ID).Err()) + + fields := orderFields(order, ac.tok, "otc") + require.NoError(t, s.AssignPaymentOrder(ac.ctx, fields)) + + got := assignedProviderID(t, order.ID) + assert.Equal(t, pFall.ID, got, + "OTC provider appearing once in exclude list must be skipped") + _ = pExcl + }) + + t.Run("market_rate_snapshot_persisted_on_first_run", func(t *testing.T) { + se := newSubEnv(t, ac, "A08") + makeAssignProvider(t, ac, se, "a08_prov@t.com", 1500, 0, 1_000_000) + order := makeAssignOrder(t, ac, se, 10, 1500) + + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + updated, err := ac.client.PaymentOrder.Get(ac.ctx, order.ID) + require.NoError(t, err) + require.NotNil(t, updated.AssignmentMarketBuyRate) + require.NotNil(t, updated.AssignmentMarketSellRate) + assert.Equal(t, decimal.NewFromFloat(1500).String(), updated.AssignmentMarketBuyRate.String()) + assert.Equal(t, decimal.NewFromFloat(1500).String(), updated.AssignmentMarketSellRate.String()) + }) + + t.Run("market_rate_snapshot_reused_on_retry", func(t *testing.T) { + se := newSubEnv(t, ac, "A09") + makeAssignProvider(t, ac, se, "a09_prov@t.com", 1500, 0, 1_000_000) + order := makeAssignOrder(t, ac, se, 10, 1500) + + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + // Drift within assignmentMarketRateRelTol so persisted snapshot stays valid for floating-rate determinism. + slight := decimal.NewFromFloat(1500.5) + _, err := ac.client.FiatCurrency.UpdateOneID(se.cur.ID). + SetMarketBuyRate(slight). + SetMarketSellRate(slight). + Save(ac.ctx) + require.NoError(t, err) + + _ = db.RedisClient.Del(ac.ctx, fmt.Sprintf("order_request_%s", order.ID)) + _, err = ac.client.PaymentOrder.UpdateOneID(order.ID). + SetStatus(paymentorder.StatusPending). + Save(ac.ctx) + require.NoError(t, err) + + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + reloaded, err := ac.client.PaymentOrder.Get(ac.ctx, order.ID) + require.NoError(t, err) + assert.Equal(t, decimal.NewFromFloat(1500).String(), + reloaded.AssignmentMarketBuyRate.String(), + "snapshot must be reused from first run when fiat market drift is within relative tolerance") + }) + + t.Run("audit_run_recorded_on_successful_assignment", func(t *testing.T) { + se := newSubEnv(t, ac, "A10") + prov := makeAssignProvider(t, ac, se, "a10_prov@t.com", 1500, 0, 1_000_000) + order := makeAssignOrder(t, ac, se, 10, 1500) + + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + runs, err := ac.client.ProviderAssignmentRun.Query(). + Where(providerassignmentrun.HasPaymentOrderWith(paymentorder.IDEQ(order.ID))). + All(ac.ctx) + require.NoError(t, err) + require.Len(t, runs, 1, "one ProviderAssignmentRun should be created") + + run := runs[0] + assert.Equal(t, AssignmentRunResultAssigned, run.Result) + assert.Equal(t, AssignmentTriggerInitial, run.Trigger) + require.NotNil(t, run.AssignedProviderID) + assert.Equal(t, prov.ID, *run.AssignedProviderID) + }) + + t.Run("audit_run_recorded_when_no_provider_matches", func(t *testing.T) { + se := newSubEnv(t, ac, "A11") + prov := makeAssignProvider(t, ac, se, "a11_noprov@t.com", 1500, 0, 0) + _, err := ac.client.ProviderBalances.Update(). + Where(providerbalances.HasProviderWith(providerprofile.IDEQ(prov.ID))). + Where(providerbalances.HasFiatCurrencyWith(fiatcurrency.IDEQ(se.cur.ID))). + SetAvailableBalance(decimal.Zero). + SetIsAvailable(false). + Save(ac.ctx) + require.NoError(t, err) + + order := makeAssignOrder(t, ac, se, 10, 1500) + err = s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, "")) + require.Error(t, err, "should return error when no provider matches") + assert.Contains(t, err.Error(), "no provider matched") + + runs, err := ac.client.ProviderAssignmentRun.Query(). + Where(providerassignmentrun.HasPaymentOrderWith(paymentorder.IDEQ(order.ID))). + All(ac.ctx) + require.NoError(t, err) + require.Len(t, runs, 1) + assert.Equal(t, AssignmentRunResultNoProvider, runs[0].Result) + }) + + t.Run("duplicate_assignment_skipped_when_redis_key_exists", func(t *testing.T) { + se := newSubEnv(t, ac, "A12") + makeAssignProvider(t, ac, se, "a12_prov@t.com", 1500, 0, 1_000_000) + order := makeAssignOrder(t, ac, se, 10, 1500) + + orderKey := fmt.Sprintf("order_request_%s", order.ID) + require.NoError(t, db.RedisClient.HSet(ac.ctx, orderKey, map[string]interface{}{ + "providerId": "pre-existing-provider", + "institution": se.instCode, + }).Err()) + + assert.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, "")), + "duplicate assignment must return nil, not an error") + + pid, _ := db.RedisClient.HGet(ac.ctx, orderKey, "providerId").Result() + assert.Equal(t, "pre-existing-provider", pid, + "pre-seeded provider must not be overwritten by duplicate assignment") + }) + + t.Run("non_pending_order_is_skipped", func(t *testing.T) { + se := newSubEnv(t, ac, "A13") + makeAssignProvider(t, ac, se, "a13_prov@t.com", 1500, 0, 1_000_000) + + order, err := ac.client.PaymentOrder.Create(). + SetAmount(decimal.NewFromFloat(10)). + SetAmountInUsd(decimal.NewFromFloat(10)). + SetRate(decimal.NewFromFloat(1500)). + SetStatus(paymentorder.StatusFulfilled). + SetInstitution(se.instCode). + SetAccountIdentifier("5555555555"). + SetAccountName("Fulfilled Account"). + SetMemo("fulfilled test"). + SetToken(ac.tok). + SetGatewayID(uuid.New().String()). + SetBlockNumber(1). + Save(ac.ctx) + require.NoError(t, err) + + assert.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, "")), + "assignment of non-pending order must return nil") + + orderKey := fmt.Sprintf("order_request_%s", order.ID) + exists, _ := db.RedisClient.Exists(ac.ctx, orderKey).Result() + assert.Equal(t, int64(0), exists, + "no order_request key must be created for a non-pending order") + }) + + t.Run("last_order_assigned_at_updated_after_assignment", func(t *testing.T) { + se := newSubEnv(t, ac, "A14") + prov := makeAssignProvider(t, ac, se, "a14_prov@t.com", 1500, 0, 1_000_000) + pot := getProviderPOT(t, ac.ctx, prov.ID) + assert.Nil(t, pot.LastOrderAssignedAt, + "last_order_assigned_at must be nil before any assignment") + + beforeAssign := time.Now() + order := makeAssignOrder(t, ac, se, 10, 1500) + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + pot2, err := ac.client.ProviderOrderToken.Get(ac.ctx, pot.ID) + require.NoError(t, err) + require.NotNil(t, pot2.LastOrderAssignedAt) + assert.True(t, !pot2.LastOrderAssignedAt.Before(beforeAssign)) + }) + + t.Run("round_robin_via_last_assigned_at", func(t *testing.T) { + se := newSubEnv(t, ac, "A15") + pOld := makeAssignProvider(t, ac, se, "a15_old@t.com", 1500, 0, 1_000_000) + pNew := makeAssignProvider(t, ac, se, "a15_new@t.com", 1500, 0, 1_000_000) + + oldPot := getProviderPOT(t, ac.ctx, pOld.ID) + newPot := getProviderPOT(t, ac.ctx, pNew.ID) + + _, err := ac.client.ProviderOrderToken.UpdateOneID(oldPot.ID). + SetLastOrderAssignedAt(time.Now().Add(-2 * time.Hour)). + Save(ac.ctx) + require.NoError(t, err) + _, err = ac.client.ProviderOrderToken.UpdateOneID(newPot.ID). + SetLastOrderAssignedAt(time.Now().Add(-1 * time.Second)). + Save(ac.ctx) + require.NoError(t, err) + + order := makeAssignOrder(t, ac, se, 10, 1500) + require.NoError(t, s.AssignPaymentOrder(ac.ctx, orderFields(order, ac.tok, ""))) + + assert.Equal(t, pOld.ID, assignedProviderID(t, order.ID), + "provider with the oldest last_order_assigned_at should be selected (round-robin)") + _ = pNew + }) +} diff --git a/services/assignment/service.go b/services/assignment/service.go new file mode 100644 index 000000000..4376cee49 --- /dev/null +++ b/services/assignment/service.go @@ -0,0 +1,74 @@ +package assignment + +import ( + "context" + "fmt" + + "github.com/paycrest/aggregator/ent" + "github.com/paycrest/aggregator/ent/fiatcurrency" + "github.com/paycrest/aggregator/ent/providerordertoken" + "github.com/paycrest/aggregator/ent/providerprofile" + "github.com/paycrest/aggregator/ent/token" + "github.com/paycrest/aggregator/services/balance" + "github.com/shopspring/decimal" +) + +// RateSide represents the direction of the rate (buy for onramp, sell for offramp). +type RateSide string + +const ( + RateSideBuy RateSide = "buy" // Onramp: fiat per 1 token the sender pays to buy crypto + RateSideSell RateSide = "sell" // Offramp: fiat per 1 token the sender receives when selling crypto +) + +// Service coordinates provider assignment, selection, and scoring. +type Service struct { + balanceService *balance.Service +} + +// New creates a new assignment Service. +func New() *Service { + return &Service{ + balanceService: balance.New(), + } +} + +// GetProviderRate returns the effective rate for a provider based on side (buy or sell). +func (s *Service) GetProviderRate(ctx context.Context, provider *ent.ProviderProfile, tokenSymbol string, currency string, side RateSide) (decimal.Decimal, error) { + tokenConfig, err := provider.QueryOrderTokens(). + Where( + providerordertoken.HasProviderWith(providerprofile.IDEQ(provider.ID)), + providerordertoken.HasTokenWith(token.SymbolEQ(tokenSymbol)), + providerordertoken.HasCurrencyWith(fiatcurrency.CodeEQ(currency)), + ). + WithProvider(). + WithCurrency(). + First(ctx) + if err != nil { + return decimal.Decimal{}, err + } + + var rate decimal.Decimal + switch side { + case RateSideBuy: + if !tokenConfig.FixedBuyRate.IsZero() { + rate = tokenConfig.FixedBuyRate + } else if !tokenConfig.Edges.Currency.MarketBuyRate.IsZero() { + rate = tokenConfig.Edges.Currency.MarketBuyRate.Add(tokenConfig.FloatingBuyDelta).RoundBank(2) + } + case RateSideSell: + if !tokenConfig.FixedSellRate.IsZero() { + rate = tokenConfig.FixedSellRate + } else if !tokenConfig.Edges.Currency.MarketSellRate.IsZero() { + rate = tokenConfig.Edges.Currency.MarketSellRate.Add(tokenConfig.FloatingSellDelta).RoundBank(2) + } + default: + return decimal.Decimal{}, fmt.Errorf("no effective rate for side=%v token=%s: unsupported side", side, tokenSymbol) + } + + if rate.IsZero() { + return decimal.Decimal{}, fmt.Errorf("no effective rate for side=%v token=%s", side, tokenSymbol) + } + + return rate, nil +} diff --git a/services/common/indexer.go b/services/common/indexer.go index ccc538a62..dc70d543f 100644 --- a/services/common/indexer.go +++ b/services/common/indexer.go @@ -18,7 +18,7 @@ import ( "github.com/paycrest/aggregator/ent/providerprofile" tokenent "github.com/paycrest/aggregator/ent/token" "github.com/paycrest/aggregator/ent/transactionlog" - "github.com/paycrest/aggregator/services" + "github.com/paycrest/aggregator/services/assignment" "github.com/paycrest/aggregator/storage" db "github.com/paycrest/aggregator/storage" "github.com/paycrest/aggregator/types" @@ -32,7 +32,7 @@ import ( func ProcessTransfers( ctx context.Context, orderService types.OrderService, - priorityQueueService *services.PriorityQueueService, + priorityQueueService *assignment.Service, unknownAddresses []string, addressToEvent map[string]*types.TokenTransferEvent, ) error { @@ -77,7 +77,7 @@ func ProcessTransfers( _, err := UpdateReceiveAddressStatus(ctx, order, transferEvent, orderService.CreateOrder, func(ctx context.Context, providerProfile *ent.ProviderProfile, tokenSymbol string, currency string) (decimal.Decimal, error) { // Offramp context: use sell side rates - return priorityQueueService.GetProviderRate(ctx, providerProfile, tokenSymbol, currency, services.RateSideSell) + return priorityQueueService.GetProviderRate(ctx, providerProfile, tokenSymbol, currency, assignment.RateSideSell) }) if err != nil { if !strings.Contains(fmt.Sprintf("%v", err), "Duplicate payment order") && !strings.Contains(fmt.Sprintf("%v", err), "Receive address not found") { @@ -101,7 +101,7 @@ func ProcessCreatedOrders( orderIds []string, orderIdToEvent map[string]*types.OrderCreatedEvent, orderService types.OrderService, - priorityQueueService *services.PriorityQueueService, + priorityQueueService *assignment.Service, ) error { var wg sync.WaitGroup @@ -503,13 +503,21 @@ func GetProviderAddressFromOrder(ctx context.Context, order *ent.PaymentOrder) ( if order.Edges.Provider == nil { return "", fmt.Errorf("payment order has no provider") } - - // Get the currency from the provision bucket - if order.Edges.ProvisionBucket == nil { - return "", fmt.Errorf("payment order has no provision bucket") + if order.Edges.Token == nil { + return "", fmt.Errorf("payment order has no token") } - currencyCode := order.Edges.ProvisionBucket.Edges.Currency.Code + if order.Institution == "" { + return "", fmt.Errorf("payment order has no institution for currency resolution") + } + inst, ierr := utils.GetInstitutionByCode(ctx, order.Institution, true) + if ierr != nil || inst == nil || inst.Edges.FiatCurrency == nil { + if ierr != nil { + return "", fmt.Errorf("institution or fiat currency: %w", ierr) + } + return "", fmt.Errorf("institution or fiat currency not found") + } + currencyCode := inst.Edges.FiatCurrency.Code // Get provider order token for this provider, token, and currency providerOrderToken, err := storage.Client.ProviderOrderToken. diff --git a/services/common/order.go b/services/common/order.go index ef9f0fa5a..79a1c15af 100644 --- a/services/common/order.go +++ b/services/common/order.go @@ -4,7 +4,6 @@ import ( "context" "encoding/hex" "encoding/json" - "errors" "fmt" "strings" "time" @@ -23,7 +22,6 @@ import ( "github.com/paycrest/aggregator/ent/providerbalances" "github.com/paycrest/aggregator/ent/providerordertoken" "github.com/paycrest/aggregator/ent/providerprofile" - "github.com/paycrest/aggregator/ent/provisionbucket" tokenent "github.com/paycrest/aggregator/ent/token" "github.com/paycrest/aggregator/ent/transactionlog" "github.com/paycrest/aggregator/ent/user" @@ -54,9 +52,6 @@ func normalizeGatewayID(orderID string) string { return strings.ToLower(s) } -// ErrNoProvisionBucketForAmount is returned when the amount falls in a gap between tier ranges (no bucket contains it). -var ErrNoProvisionBucketForAmount = errors.New("no provision bucket for this amount") - const ( CancellationReasonAML = "AML compliance check failed" ) @@ -140,7 +135,7 @@ func ProcessPaymentOrderFromBlockchain( } // Validate and prepare payment order data (pass existing order so it can be used if cancellation is needed) - paymentOrderFields, _, _, _, _, err := validateAndPreparePaymentOrderData(ctx, network, event, refundOrder, existingOrderWithMessageHash) + paymentOrderFields, _, _, _, err := validateAndPreparePaymentOrderData(ctx, network, event, refundOrder, existingOrderWithMessageHash) if err != nil { return err } @@ -181,11 +176,6 @@ func ProcessPaymentOrderFromBlockchain( updateBuilder = updateBuilder.SetSender(paymentOrderFields.Sender) } - // Update provision bucket if available (should always be set for regular orders) - if paymentOrderFields.ProvisionBucket != nil { - updateBuilder = updateBuilder.SetProvisionBucket(paymentOrderFields.ProvisionBucket) - } - _, err = updateBuilder.Save(ctx) if err != nil { _ = tx.Rollback() @@ -269,8 +259,8 @@ func ProcessPaymentOrderFromBlockchain( SetSender(paymentOrderFields.Sender). SetMessageHash(paymentOrderFields.MessageHash). SetMemo(paymentOrderFields.Memo). - SetMetadata(paymentOrderFields.Metadata). - SetProvisionBucket(paymentOrderFields.ProvisionBucket). + SetMetadata(paymentOrderFields.Metadata) + orderBuilder = orderBuilder. SetOrderType(paymentorder.OrderType(paymentOrderFields.OrderType)). SetStatus(paymentorder.StatusPending). SetIndexerCreatedAt(time.Now()) @@ -452,16 +442,10 @@ func UpdateOrderStatusRefunded(ctx context.Context, network *ent.Network, event ), ). WithProvider(). - WithProvisionBucket(func(pbq *ent.ProvisionBucketQuery) { - pbq.WithCurrency() - }). Only(ctx) if err == nil && paymentOrder != nil && paymentOrder.Edges.Provider != nil { currency := "" - if paymentOrder.Edges.ProvisionBucket != nil && paymentOrder.Edges.ProvisionBucket.Edges.Currency != nil { - currency = paymentOrder.Edges.ProvisionBucket.Edges.Currency.Code - } - if currency == "" && paymentOrder.Institution != "" { + if paymentOrder.Institution != "" { inst, instErr := utils.GetInstitutionByCode(ctx, paymentOrder.Institution, true) if instErr == nil && inst != nil && inst.Edges.FiatCurrency != nil { currency = inst.Edges.FiatCurrency.Code @@ -618,48 +602,41 @@ func UpdateOrderStatusSettleOut(ctx context.Context, network *ent.Network, event ), ). WithProvider(). - WithProvisionBucket(func(pbq *ent.ProvisionBucketQuery) { - pbq.WithCurrency() - }). Only(ctx) - if err == nil && paymentOrder != nil && paymentOrder.Edges.Provider != nil && paymentOrder.Edges.ProvisionBucket != nil && paymentOrder.Edges.ProvisionBucket.Edges.Currency != nil { - // Only attempt balance operations if we have the required edge data - // Create a new balance service instance for this transaction - balanceService := balance.New() - - providerID := paymentOrder.Edges.Provider.ID - currency := paymentOrder.Edges.ProvisionBucket.Edges.Currency.Code - amount := paymentOrder.Amount.Mul(paymentOrder.Rate).RoundBank(0) + if err == nil && paymentOrder != nil && paymentOrder.Edges.Provider != nil && paymentOrder.Institution != "" { + if inst, instErr := utils.GetInstitutionByCode(ctx, paymentOrder.Institution, true); instErr == nil && inst != nil && inst.Edges.FiatCurrency != nil { + balanceService := balance.New() + providerID := paymentOrder.Edges.Provider.ID + currency := inst.Edges.FiatCurrency.Code + amount := paymentOrder.Amount.Mul(paymentOrder.Rate).RoundBank(0) - currentBalance, err := balanceService.GetProviderFiatBalance(ctx, providerID, currency) - if err == nil && currentBalance != nil { - newReservedBalance := currentBalance.ReservedBalance.Sub(amount) - if newReservedBalance.LessThan(decimal.Zero) { - newReservedBalance = decimal.Zero - } - newTotalBalance := currentBalance.TotalBalance.Sub(amount) - if newTotalBalance.LessThan(decimal.Zero) { - newTotalBalance = decimal.Zero - } - // Ensure available doesn't exceed (total - reserved) after clamping - maxAvailable := newTotalBalance.Sub(newReservedBalance) - newAvailableBalance := currentBalance.AvailableBalance - if newAvailableBalance.GreaterThan(maxAvailable) { - newAvailableBalance = maxAvailable - } - if newAvailableBalance.LessThan(decimal.Zero) { - newAvailableBalance = decimal.Zero - } - err = balanceService.UpdateProviderFiatBalance(ctx, providerID, currency, newAvailableBalance, newTotalBalance, newReservedBalance) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": event.OrderId, - "ProviderID": providerID, - "Currency": currency, - "Amount": amount.String(), - }).Errorf("failed to update provider balance for settled order") - // Don't return error here as the order status is already updated + currentBalance, balErr := balanceService.GetProviderFiatBalance(ctx, providerID, currency) + if balErr == nil && currentBalance != nil { + newReservedBalance := currentBalance.ReservedBalance.Sub(amount) + if newReservedBalance.LessThan(decimal.Zero) { + newReservedBalance = decimal.Zero + } + newTotalBalance := currentBalance.TotalBalance.Sub(amount) + if newTotalBalance.LessThan(decimal.Zero) { + newTotalBalance = decimal.Zero + } + maxAvailable := newTotalBalance.Sub(newReservedBalance) + newAvailableBalance := currentBalance.AvailableBalance + if newAvailableBalance.GreaterThan(maxAvailable) { + newAvailableBalance = maxAvailable + } + if newAvailableBalance.LessThan(decimal.Zero) { + newAvailableBalance = decimal.Zero + } + if upErr := balanceService.UpdateProviderFiatBalance(ctx, providerID, currency, newAvailableBalance, newTotalBalance, newReservedBalance); upErr != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", upErr), + "OrderID": event.OrderId, + "ProviderID": providerID, + "Currency": currency, + "Amount": amount.String(), + }).Errorf("failed to update provider balance for settled order") + } } } } @@ -812,63 +789,6 @@ func UpdateOrderStatusSettleIn(ctx context.Context, network *ent.Network, event return nil } -// GetProvisionBucket gets a provision bucket for the given amount and currency. -func GetProvisionBucket(ctx context.Context, amount decimal.Decimal, currency *ent.FiatCurrency) (*ent.ProvisionBucket, bool, error) { - provisionBucket, err := db.Client.ProvisionBucket. - Query(). - Where( - provisionbucket.MaxAmountGTE(amount), - provisionbucket.MinAmountLTE(amount), - provisionbucket.HasCurrencyWith( - fiatcurrency.IDEQ(currency.ID), - ), - ). - WithCurrency(). - Order(ent.Asc(provisionbucket.FieldID)). - First(ctx) - if err != nil { - if ent.IsNotFound(err) { - // No bucket contains this amount: distinguish below min, above max, or gap between tiers - minBucket, minErr := db.Client.ProvisionBucket. - Query(). - Where( - provisionbucket.HasCurrencyWith( - fiatcurrency.IDEQ(currency.ID), - ), - ). - Order(ent.Asc(provisionbucket.FieldMinAmount)). - First(ctx) - if minErr != nil { - return nil, false, fmt.Errorf("failed to fetch minimum bucket: %w", minErr) - } - if amount.LessThan(minBucket.MinAmount) { - return nil, true, nil - } - maxBucket, maxErr := db.Client.ProvisionBucket. - Query(). - Where( - provisionbucket.HasCurrencyWith( - fiatcurrency.IDEQ(currency.ID), - ), - ). - Order(ent.Desc(provisionbucket.FieldMaxAmount)). - First(ctx) - if maxErr != nil { - return nil, false, fmt.Errorf("failed to fetch maximum bucket: %w", maxErr) - } - if amount.GreaterThan(maxBucket.MaxAmount) { - // Above highest tier: return nil bucket, no error; caller will cancel with "Amount is larger than the maximum bucket" - return nil, false, nil - } - // Amount is within [minBucket.MinAmount, maxBucket.MaxAmount] but no bucket contains it (gap between tiers) - return nil, false, ErrNoProvisionBucketForAmount - } - return nil, false, fmt.Errorf("failed to fetch provision bucket: %w", err) - } - - return provisionBucket, false, nil -} - // HandleCancellation handles the cancellation of a payment order. func HandleCancellation(ctx context.Context, createdPaymentOrder *ent.PaymentOrder, paymentOrderFields *types.PaymentOrderFields, cancellationReason string, refundOrder func(context.Context, *ent.Network, string) error) error { // paymentOrderFields and createdPaymentOrder are mutually exclusive @@ -904,11 +824,6 @@ func HandleCancellation(ctx context.Context, createdPaymentOrder *ent.PaymentOrd SetCancellationReasons([]string{cancellationReason}). SetStatus(paymentorder.StatusCancelled) - // Only set ProvisionBucket if it's not nil - if paymentOrderFields.ProvisionBucket != nil { - orderBuilder = orderBuilder.SetProvisionBucket(paymentOrderFields.ProvisionBucket) - } - // Set provider if ProviderID exists if paymentOrderFields.ProviderID != "" { provider, err := db.Client.ProviderProfile.Query().Where(providerprofile.IDEQ(paymentOrderFields.ProviderID)).Only(ctx) @@ -1300,29 +1215,7 @@ func processPaymentOrderPostCreation( } } - // Fill empty provision bucket so AssignPaymentOrder can run (same as stale_ops nil-bucket resolution) - if paymentOrderFields.ProvisionBucket == nil { - institution, instErr := utils.GetInstitutionByCode(ctx, paymentOrder.Institution, true) - if instErr == nil && institution != nil && institution.Edges.FiatCurrency != nil { - fiatAmount := paymentOrder.Amount.Mul(paymentOrder.Rate) - bucket, bErr := db.Client.ProvisionBucket. - Query(). - Where( - provisionbucket.MaxAmountGTE(fiatAmount), - provisionbucket.MinAmountLTE(fiatAmount), - provisionbucket.HasCurrencyWith(fiatcurrency.IDEQ(institution.Edges.FiatCurrency.ID)), - ). - WithCurrency(). - First(ctx) - if bErr == nil && bucket != nil { - if _, upErr := db.Client.PaymentOrder.UpdateOneID(paymentOrder.ID).SetProvisionBucket(bucket).Save(ctx); upErr == nil { - paymentOrderFields.ProvisionBucket = bucket - } - } - } - } - - // Assign when we have a bucket, or when order is private; private orders don't require buckets. + // DB-only assignment: institution + token are sufficient (no provision bucket). isPrivate := false if paymentOrderFields.ProviderID != "" { provider, pErr := db.Client.ProviderProfile.Query().Where(providerprofile.IDEQ(paymentOrderFields.ProviderID)).Only(ctx) @@ -1331,26 +1224,20 @@ func processPaymentOrderPostCreation( } } paymentOrderFields.ID = paymentOrder.ID - if paymentOrderFields.ProvisionBucket != nil || isPrivate { - // Run assignment in a goroutine with its own 60s timeout so one slow order doesn't - // consume the indexing task's context and cancel other work. + if (paymentOrderFields.Institution != "" && paymentOrderFields.Token != nil) || isPrivate { fieldsCopy := *paymentOrderFields go func() { assignCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() _ = assignPaymentOrder(assignCtx, fieldsCopy) }() - } else if paymentOrderFields.ProvisionBucket == nil { - logger.WithFields(logger.Fields{ - "OrderID": paymentOrder.ID.String(), - }).Errorf("processPaymentOrderPostCreation: could not resolve provision bucket for order; skipping provider assignment") } return nil } // validateAndPreparePaymentOrderData validates the blockchain event data and prepares payment order fields. -// Returns the prepared fields, token, institution, currency, provision bucket, and any error. +// Returns the prepared fields, token, institution, currency, and any error. // existingOrder is an optional existing payment order that should be used for cancellation instead of creating a new one. func validateAndPreparePaymentOrderData( ctx context.Context, @@ -1358,7 +1245,7 @@ func validateAndPreparePaymentOrderData( event *types.OrderCreatedEvent, refundOrder func(context.Context, *ent.Network, string) error, existingOrder *ent.PaymentOrder, -) (*types.PaymentOrderFields, *ent.Token, *ent.Institution, *ent.FiatCurrency, *ent.ProvisionBucket, error) { +) (*types.PaymentOrderFields, *ent.Token, *ent.Institution, *ent.FiatCurrency, error) { // Get token from db token, err := db.Client.Token. Query(). @@ -1382,16 +1269,16 @@ func validateAndPreparePaymentOrderData( }).Errorf("token lookup failed and refund failed") refundErr := refundOrder(ctx, network, event.OrderId) if refundErr != nil { - return nil, nil, nil, nil, nil, fmt.Errorf("token lookup failed and refund failed: %w", refundErr) + return nil, nil, nil, nil, fmt.Errorf("token lookup failed and refund failed: %w", refundErr) } } - return nil, nil, nil, nil, nil, nil + return nil, nil, nil, nil, nil } // Get order recipient from message hash recipient, err := cryptoUtils.GetOrderRecipientFromMessageHash(event.MessageHash) if err != nil { - return nil, nil, nil, nil, nil, createBasicPaymentOrderAndCancel(ctx, event, network, token, nil, fmt.Sprintf("Message hash decryption failed %v", err), refundOrder, existingOrder) + return nil, nil, nil, nil, createBasicPaymentOrderAndCancel(ctx, event, network, token, nil, fmt.Sprintf("Message hash decryption failed %v", err), refundOrder, existingOrder) } if recipient.Metadata != nil { @@ -1421,7 +1308,7 @@ func validateAndPreparePaymentOrderData( // Get institution institution, err := utils.GetInstitutionByCode(ctx, recipient.Institution, true) if err != nil { - return nil, nil, nil, nil, nil, createBasicPaymentOrderAndCancel(ctx, event, network, token, recipient, "Institution lookup failed", refundOrder, existingOrder) + return nil, nil, nil, nil, createBasicPaymentOrderAndCancel(ctx, event, network, token, recipient, "Institution lookup failed", refundOrder, existingOrder) } // Get currency @@ -1433,31 +1320,13 @@ func validateAndPreparePaymentOrderData( ). Only(ctx) if err != nil { - return nil, nil, nil, nil, nil, createBasicPaymentOrderAndCancel(ctx, event, network, token, recipient, "Currency lookup failed", refundOrder, existingOrder) + return nil, nil, nil, nil, createBasicPaymentOrderAndCancel(ctx, event, network, token, recipient, "Currency lookup failed", refundOrder, existingOrder) } // Adjust amounts for token decimals event.Amount = event.Amount.Div(decimal.NewFromInt(10).Pow(decimal.NewFromInt(int64(token.Decimals)))) event.ProtocolFee = event.ProtocolFee.Div(decimal.NewFromInt(10).Pow(decimal.NewFromInt(int64(token.Decimals)))) - // Get provision bucket - var provisionBucket *ent.ProvisionBucket - var isLessThanMin bool - provisionBucket, isLessThanMin, err = GetProvisionBucket(ctx, event.Amount.Mul(event.Rate), currency) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Amount": event.Amount, - "Currency": currency, - }).Errorf("failed to fetch provision bucket when creating payment order") - - cancellationReason := "Provision bucket lookup failed" - if errors.Is(err, ErrNoProvisionBucketForAmount) { - cancellationReason = "No provision bucket for this amount" - } - return nil, nil, nil, nil, nil, createBasicPaymentOrderAndCancel(ctx, event, network, token, recipient, cancellationReason, refundOrder, existingOrder) - } - // Normalize mobile money account identifier (same as sender API path) accountIdentifier := recipient.AccountIdentifier if institution.Type == institutionent.TypeMobileMoney && institution.Edges.FiatCurrency != nil { @@ -1483,18 +1352,9 @@ func validateAndPreparePaymentOrderData( Memo: recipient.Memo, MessageHash: event.MessageHash, Metadata: recipient.Metadata, - ProvisionBucket: provisionBucket, OrderType: "regular", } - if isLessThanMin { - err := HandleCancellation(ctx, existingOrder, nil, "Amount is less than the minimum bucket", refundOrder) - if err != nil { - return nil, nil, nil, nil, nil, fmt.Errorf("failed to handle cancellation: %w", err) - } - return nil, nil, nil, nil, nil, nil - } - // Validate rate rateResult, rateErr := utils.ValidateRate( ctx, @@ -1510,17 +1370,17 @@ func validateAndPreparePaymentOrderData( if rateErr != nil { err := handleCancellationForIndexedOrder(ctx, network, paymentOrderFields.GatewayID, existingOrder, paymentOrderFields, fmt.Sprintf("Rate validation failed: %s", rateErr.Error()), refundOrder) if err != nil { - return nil, nil, nil, nil, nil, fmt.Errorf("failed to handle cancellation: %w", err) + return nil, nil, nil, nil, fmt.Errorf("failed to handle cancellation: %w", err) } - return nil, nil, nil, nil, nil, nil + return nil, nil, nil, nil, nil } if rateResult.Rate == decimal.NewFromInt(1) && paymentOrderFields.Rate != decimal.NewFromInt(1) { err := handleCancellationForIndexedOrder(ctx, network, paymentOrderFields.GatewayID, existingOrder, paymentOrderFields, "Rate validation failed", refundOrder) if err != nil { - return nil, nil, nil, nil, nil, fmt.Errorf("failed to handle cancellation: %w", err) + return nil, nil, nil, nil, fmt.Errorf("failed to handle cancellation: %w", err) } - return nil, nil, nil, nil, nil, nil + return nil, nil, nil, nil, nil } // Check if event rate is within 0.1% tolerance of validated rate @@ -1530,9 +1390,9 @@ func validateAndPreparePaymentOrderData( if rateDiff.GreaterThan(tolerance) { err := handleCancellationForIndexedOrder(ctx, network, paymentOrderFields.GatewayID, existingOrder, paymentOrderFields, "Rate validation failed", refundOrder) if err != nil { - return nil, nil, nil, nil, nil, fmt.Errorf("failed to handle cancellation: %w", err) + return nil, nil, nil, nil, fmt.Errorf("failed to handle cancellation: %w", err) } - return nil, nil, nil, nil, nil, nil + return nil, nil, nil, nil, nil } // Use order type from ValidateRate result @@ -1543,10 +1403,8 @@ func validateAndPreparePaymentOrderData( paymentOrderFields.ProviderID = rateResult.ProviderID } - // Handle private order checks - isPrivate := false if paymentOrderFields.ProviderID != "" { - orderToken, err := db.Client.ProviderOrderToken. + _, err := db.Client.ProviderOrderToken. Query(). Where( providerordertoken.NetworkEQ(token.Edges.Network.Identifier), @@ -1575,29 +1433,15 @@ func validateAndPreparePaymentOrderData( // 4. Provider does not support the currency // 5. Provider have not configured a settlement address for the network if cErr := handleCancellationForIndexedOrder(ctx, network, paymentOrderFields.GatewayID, existingOrder, paymentOrderFields, "Provider not available", refundOrder); cErr != nil { - return nil, nil, nil, nil, nil, fmt.Errorf("%s - failed to handle cancellation: %w", paymentOrderFields.GatewayID, cErr) + return nil, nil, nil, nil, fmt.Errorf("%s - failed to handle cancellation: %w", paymentOrderFields.GatewayID, cErr) } - return nil, nil, nil, nil, nil, nil - } else { - return nil, nil, nil, nil, nil, fmt.Errorf("%s - failed to fetch provider: %w", paymentOrderFields.GatewayID, err) + return nil, nil, nil, nil, nil } + return nil, nil, nil, nil, fmt.Errorf("%s - failed to fetch provider: %w", paymentOrderFields.GatewayID, err) } - - // Check if provider is private - private orders don't require provision buckets - if orderToken != nil && orderToken.Edges.Provider != nil && orderToken.Edges.Provider.VisibilityMode == providerprofile.VisibilityModePrivate { - isPrivate = true - } - } - - if provisionBucket == nil && !isPrivate { - err := handleCancellationForIndexedOrder(ctx, network, paymentOrderFields.GatewayID, existingOrder, paymentOrderFields, "Amount is larger than the maximum bucket", refundOrder) - if err != nil { - return nil, nil, nil, nil, nil, fmt.Errorf("failed to handle cancellation: %w", err) - } - return nil, nil, nil, nil, nil, nil } - return paymentOrderFields, token, institution, currency, provisionBucket, nil + return paymentOrderFields, token, institution, currency, nil } // createBasicPaymentOrderAndCancel creates a basic payment order and cancels it with the given reason. diff --git a/services/indexer/evm.go b/services/indexer/evm.go index 07d8840fa..fd6d85bd7 100644 --- a/services/indexer/evm.go +++ b/services/indexer/evm.go @@ -9,6 +9,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/paycrest/aggregator/ent" "github.com/paycrest/aggregator/services" + "github.com/paycrest/aggregator/services/assignment" "github.com/paycrest/aggregator/services/common" explorer "github.com/paycrest/aggregator/services/explorer" "github.com/paycrest/aggregator/services/order" @@ -20,7 +21,7 @@ import ( // IndexerEVM performs blockchain to database extract, transform, load (ETL) operations. type IndexerEVM struct { - priorityQueue *services.PriorityQueueService + priorityQueue *assignment.Service order types.OrderService engineService *services.EngineService etherscanService *explorer.EtherscanService @@ -29,7 +30,6 @@ type IndexerEVM struct { // NewIndexerEVM creates a new instance of IndexerEVM. func NewIndexerEVM() (types.Indexer, error) { - priorityQueue := services.NewPriorityQueueService() orderService := order.NewOrderEVM() engineService := services.NewEngineService() etherscanService, err := explorer.NewEtherscanService() @@ -39,7 +39,7 @@ func NewIndexerEVM() (types.Indexer, error) { blockscoutService := explorer.NewBlockscoutService() return &IndexerEVM{ - priorityQueue: priorityQueue, + priorityQueue: assignment.New(), order: orderService, engineService: engineService, etherscanService: etherscanService, diff --git a/services/indexer/starknet.go b/services/indexer/starknet.go index bc87f290e..53ec44038 100644 --- a/services/indexer/starknet.go +++ b/services/indexer/starknet.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/paycrest/aggregator/ent" - "github.com/paycrest/aggregator/services" + "github.com/paycrest/aggregator/services/assignment" "github.com/paycrest/aggregator/services/common" explorer "github.com/paycrest/aggregator/services/explorer" "github.com/paycrest/aggregator/services/order" @@ -20,30 +20,26 @@ import ( // IndexerStarknet performs blockchain to database extract, transform, load (ETL) operations for Starknet type IndexerStarknet struct { - priorityQueue *services.PriorityQueueService + priorityQueue *assignment.Service order types.OrderService voyagerService *explorer.VoyagerService } // NewIndexerStarknet creates a new instance of IndexerStarknet func NewIndexerStarknet() (types.Indexer, error) { - // Create RPC client for order service (write operations) client, err := starknetService.NewClient() if err != nil { return nil, fmt.Errorf("failed to create starknet client: %w", err) } orderService := order.NewOrderStarknet(client) - // Create Voyager service for read operations (with RPC fallback) voyagerService, err := explorer.NewVoyagerService() if err != nil { return nil, fmt.Errorf("failed to create Voyager service: %w", err) } - priorityQueue := services.NewPriorityQueueService() - return &IndexerStarknet{ - priorityQueue: priorityQueue, + priorityQueue: assignment.New(), order: orderService, voyagerService: voyagerService, }, nil diff --git a/services/indexer/tron.go b/services/indexer/tron.go index 583cca4ea..1a95b1ebd 100644 --- a/services/indexer/tron.go +++ b/services/indexer/tron.go @@ -12,7 +12,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" fastshot "github.com/opus-domini/fast-shot" "github.com/paycrest/aggregator/ent" - "github.com/paycrest/aggregator/services" + "github.com/paycrest/aggregator/services/assignment" "github.com/paycrest/aggregator/services/common" "github.com/paycrest/aggregator/services/contracts" "github.com/paycrest/aggregator/services/order" @@ -23,18 +23,15 @@ import ( // IndexerTron performs blockchain to database extract, transform, load (ETL) operations. type IndexerTron struct { - priorityQueue *services.PriorityQueueService + priorityQueue *assignment.Service order types.OrderService } // NewIndexerTron creates a new instance of IndexerTron. func NewIndexerTron() types.Indexer { - priorityQueue := services.NewPriorityQueueService() - orderService := order.NewOrderTron() - return &IndexerTron{ - priorityQueue: priorityQueue, - order: orderService, + priorityQueue: assignment.New(), + order: order.NewOrderTron(), } } diff --git a/services/order/evm.go b/services/order/evm.go index eef7bf2aa..b22f85d97 100644 --- a/services/order/evm.go +++ b/services/order/evm.go @@ -13,6 +13,7 @@ import ( "github.com/paycrest/aggregator/config" "github.com/paycrest/aggregator/ent" "github.com/paycrest/aggregator/services" + "github.com/paycrest/aggregator/services/assignment" "github.com/paycrest/aggregator/services/contracts" db "github.com/paycrest/aggregator/storage" "github.com/shopspring/decimal" @@ -32,17 +33,15 @@ import ( // OrderEVM provides functionality related to onchain interactions for payment orders type OrderEVM struct { - priorityQueue *services.PriorityQueueService + priorityQueue *assignment.Service engineService *services.EngineService nativeService *services.NativeService } // NewOrderEVM creates a new instance of OrderEVM. func NewOrderEVM() types.OrderService { - priorityQueue := services.NewPriorityQueueService() - return &OrderEVM{ - priorityQueue: priorityQueue, + priorityQueue: assignment.New(), engineService: services.NewEngineService(), nativeService: services.NewNativeService(), } diff --git a/services/priority_queue.go b/services/priority_queue.go deleted file mode 100644 index 363e4513f..000000000 --- a/services/priority_queue.go +++ /dev/null @@ -1,1837 +0,0 @@ -package services - -import ( - "context" - "errors" - "fmt" - "math/rand" - "strings" - "time" - - "github.com/paycrest/aggregator/config" - "github.com/paycrest/aggregator/ent" - "github.com/paycrest/aggregator/ent/fiatcurrency" - "github.com/paycrest/aggregator/ent/paymentorder" - "github.com/paycrest/aggregator/ent/paymentorderfulfillment" - "github.com/paycrest/aggregator/ent/providerbalances" - "github.com/paycrest/aggregator/ent/providerordertoken" - "github.com/paycrest/aggregator/ent/providerprofile" - "github.com/paycrest/aggregator/ent/provisionbucket" - "github.com/paycrest/aggregator/ent/token" - "github.com/paycrest/aggregator/services/balance" - "github.com/paycrest/aggregator/storage" - "github.com/paycrest/aggregator/types" - "github.com/paycrest/aggregator/utils" - "github.com/paycrest/aggregator/utils/logger" - "github.com/shopspring/decimal" -) - -var ( - serverConf = config.ServerConfig() -) - -// RateSide represents the direction of the rate (buy for onramp, sell for offramp) -type RateSide string - -const ( - RateSideBuy RateSide = "buy" // Onramp: fiat per 1 token the sender pays to buy crypto - RateSideSell RateSide = "sell" // Offramp: fiat per 1 token the sender receives when selling crypto -) - -type PriorityQueueService struct { - balanceService *balance.Service -} - -// NewPriorityQueueService creates a new instance of PriorityQueueService -func NewPriorityQueueService() *PriorityQueueService { - return &PriorityQueueService{ - balanceService: balance.New(), - } -} - -// ProcessBucketQueues creates a priority queue for each bucket and saves it to redis -func (s *PriorityQueueService) ProcessBucketQueues() error { - // ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) - // defer cancel() - ctx := context.Background() - - buckets, err := s.GetProvisionBuckets(ctx) - if err != nil { - return fmt.Errorf("ProcessBucketQueues.GetProvisionBuckets: %w", err) - } - - for _, bucket := range buckets { - go s.CreatePriorityQueueForBucket(ctx, bucket) - } - - return nil -} - -// GetProvisionBuckets returns a list of buckets with their providers -func (s *PriorityQueueService) GetProvisionBuckets(ctx context.Context) ([]*ent.ProvisionBucket, error) { - buckets, err := storage.Client.ProvisionBucket.Query().WithCurrency().All(ctx) - if err != nil { - return nil, err - } - - // Filter providers by currency availability and balance for each bucket. - // Always reconcile provider-bucket links from order tokens (overlap rule, same as profile) - // so missing links are fixed on each run without waiting for profile updates. - for _, bucket := range buckets { - // 1. Reconcile links: find providers whose order tokens overlap this bucket (in bucket currency) - // and add missing links; optionally remove links for providers who no longer qualify. - orderTokens, err := storage.Client.ProviderOrderToken.Query(). - Where( - providerordertoken.HasCurrencyWith(fiatcurrency.IDEQ(bucket.Edges.Currency.ID)), - providerordertoken.HasProviderWith(providerprofile.IsActive(true)), - ). - WithProvider(). - WithCurrency(). - All(ctx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "BucketMinAmount": bucket.MinAmount, - "BucketMaxAmount": bucket.MaxAmount, - "Currency": bucket.Edges.Currency.Code, - }).Errorf("Failed to get order tokens for bucket reconciliation") - continue - } - - shouldBeLinkedProviderIDs := make(map[string]bool) - // TODO: this could be done in batch and processed in parallel for better performance - for _, orderToken := range orderTokens { - providerID := orderToken.Edges.Provider.ID - overlaps := false - for _, side := range []RateSide{RateSideBuy, RateSideSell} { - rate := s.tokenRateForBucket(orderToken, side) - if rate.IsZero() { - continue - } - convertedMin := orderToken.MinOrderAmount.Mul(rate) - convertedMax := orderToken.MaxOrderAmount.Mul(rate) - // Overlap: bucket [Min, Max] overlaps provider [convertedMin, convertedMax] for this side - if bucket.MinAmount.LessThanOrEqual(convertedMax) && bucket.MaxAmount.GreaterThanOrEqual(convertedMin) { - overlaps = true - break - } - } - if !overlaps { - rateBuy := s.tokenRateForBucket(orderToken, RateSideBuy) - rateSell := s.tokenRateForBucket(orderToken, RateSideSell) - if rateBuy.IsZero() && rateSell.IsZero() { - // Cannot compute overlap for either side; log so operators see data/loading issues. - logger.WithFields(logger.Fields{ - "ProviderID": providerID, - "BucketID": bucket.ID, - "BucketCurrency": bucket.Edges.Currency.Code, - "OrderTokenID": orderToken.ID, - }).Errorf("Skipping overlap check: token rate is zero for both sides (currency edge missing or not loaded for order token)") - } - continue - } - { - // Overlap on at least one side: link provider to bucket (buy and/or sell queue will include them as appropriate in buildQueueForSide) - shouldBeLinkedProviderIDs[providerID] = true - exists, err := orderToken.Edges.Provider.QueryProvisionBuckets(). - Where(provisionbucket.IDEQ(bucket.ID)). - Exist(ctx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "ProviderID": providerID, - "BucketCurrency": bucket.Edges.Currency.Code, - }).Errorf("Failed to check existing bucket for provider") - continue - } - if exists { - continue - } - _, err = storage.Client.ProviderProfile.Update(). - Where(providerprofile.IDEQ(providerID)). - AddProvisionBuckets(bucket). - Save(ctx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "ProviderID": providerID, - "BucketCurrency": bucket.Edges.Currency.Code, - "BucketMinAmount": bucket.MinAmount, - "BucketMaxAmount": bucket.MaxAmount, - }).Errorf("Failed to add provision bucket to provider") - } - } - } - - // 2. Remove stale links: providers linked to this bucket but no longer having an overlapping token. - linkedProviders, err := bucket.QueryProviderProfiles().All(ctx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Bucket": bucket.ID, - }).Errorf("Failed to get linked providers for bucket") - } else { - for _, p := range linkedProviders { - if !shouldBeLinkedProviderIDs[p.ID] { - _, err = storage.Client.ProviderProfile.Update(). - Where(providerprofile.IDEQ(p.ID)). - RemoveProvisionBuckets(bucket). - Save(ctx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "ProviderID": p.ID, - "BucketID": bucket.ID, - }).Errorf("Failed to remove stale provision bucket link") - } - } - } - } - - // 3. Get available providers (linked + balance + active); requery so newly linked are included. - availableProviders, err := bucket.QueryProviderProfiles(). - Where( - providerprofile.IsActive(true), - providerprofile.VisibilityModeEQ(providerprofile.VisibilityModePublic), - providerprofile.HasProviderBalancesWith( - providerbalances.HasFiatCurrencyWith(fiatcurrency.IDEQ(bucket.Edges.Currency.ID)), - providerbalances.AvailableBalanceGT(bucket.MinAmount), - providerbalances.IsAvailableEQ(true), - ), - ). - All(ctx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "BucketMinAmount": bucket.MinAmount, - "BucketMaxAmount": bucket.MaxAmount, - "Currency": bucket.Edges.Currency.Code, - }).Errorf("Failed to get available providers for bucket") - continue - } - - bucket.Edges.ProviderProfiles = availableProviders - - // If no providers are eligible for this bucket, log balance health for a small sample of - // candidate providers to aid ops debugging (no new endpoints). - if len(bucket.Edges.ProviderProfiles) == 0 { - logger.WithFields(logger.Fields{ - "BucketMinAmount": bucket.MinAmount, - "BucketMaxAmount": bucket.MaxAmount, - "Currency": bucket.Edges.Currency.Code, - }).Warnf("No eligible providers found for bucket") - - // Sample a few providers linked to this bucket (best effort; avoid heavy DB reads). - candidates, candErr := bucket.QueryProviderProfiles(). - Where( - providerprofile.IsActive(true), - providerprofile.VisibilityModeEQ(providerprofile.VisibilityModePublic), - ). - Limit(3). - All(ctx) - if candErr != nil { - continue - } - - for _, p := range candidates { - bals, balErr := s.balanceService.GetProviderBalances(ctx, p.ID) - if balErr != nil { - logger.WithFields(logger.Fields{ - "ProviderID": p.ID, - "Currency": bucket.Edges.Currency.Code, - "Error": fmt.Sprintf("%v", balErr), - }).Errorf("Balance health check: failed to load provider balances") - continue - } - - for _, b := range bals { - // Only inspect the relevant fiat currency for this bucket. - if b.Edges.FiatCurrency == nil || !b.IsAvailable || b.Edges.FiatCurrency.Code != bucket.Edges.Currency.Code { - continue - } - report := s.balanceService.CheckBalanceHealth(b) - if report == nil || report.Status == "HEALTHY" { - continue - } - logger.WithFields(logger.Fields{ - "ProviderID": report.ProviderID, - "CurrencyCode": report.CurrencyCode, - "Status": report.Status, - "Severity": report.Severity, - "AvailableBalance": report.AvailableBalance.String(), - "ReservedBalance": report.ReservedBalance.String(), - "TotalBalance": report.TotalBalance.String(), - "IsAvailable": b.IsAvailable, - "Issues": report.Issues, - "Recommendations": report.Recommendations, - "BucketMinAmount": bucket.MinAmount, - "BucketMaxAmount": bucket.MaxAmount, - }).Errorf("Bucket provider candidate has unhealthy balance") - } - } - } - } - - return buckets, nil -} - -// tokenRateForBucket returns the fiat rate for the order token (token amount -> bucket currency) for the given side. -// Buy: onramp rate (fiat per token when buying). Sell: offramp rate (fiat per token when selling). -// The token must be loaded with WithCurrency(). Returns decimal.Zero when the currency edge is missing or rate cannot be computed; callers must treat zero as "cannot compute overlap". -func (s *PriorityQueueService) tokenRateForBucket(orderToken *ent.ProviderOrderToken, side RateSide) decimal.Decimal { - if orderToken.Edges.Currency == nil { - return decimal.Zero - } - if side == RateSideBuy { - if !orderToken.FixedBuyRate.IsZero() { - return orderToken.FixedBuyRate - } - if !orderToken.Edges.Currency.MarketBuyRate.IsZero() { - return orderToken.Edges.Currency.MarketBuyRate.Add(orderToken.FloatingBuyDelta).RoundBank(2) - } - return decimal.Zero - } - // RateSideSell - if !orderToken.FixedSellRate.IsZero() { - return orderToken.FixedSellRate - } - if !orderToken.Edges.Currency.MarketSellRate.IsZero() { - return orderToken.Edges.Currency.MarketSellRate.Add(orderToken.FloatingSellDelta).RoundBank(2) - } - return decimal.Zero -} - -// GetProviderRate returns the rate for a provider based on the side (buy or sell) -func (s *PriorityQueueService) GetProviderRate(ctx context.Context, provider *ent.ProviderProfile, tokenSymbol string, currency string, side RateSide) (decimal.Decimal, error) { - // Fetch the token config for the provider - tokenConfig, err := provider.QueryOrderTokens(). - Where( - providerordertoken.HasProviderWith(providerprofile.IDEQ(provider.ID)), - providerordertoken.HasTokenWith(token.SymbolEQ(tokenSymbol)), - providerordertoken.HasCurrencyWith(fiatcurrency.CodeEQ(currency)), - ). - WithProvider(). - WithCurrency(). - First(ctx) - if err != nil { - return decimal.Decimal{}, err - } - - var rate decimal.Decimal - - // Two-sided rate calculation based on side - switch side { - case RateSideBuy: - if !tokenConfig.FixedBuyRate.IsZero() { - rate = tokenConfig.FixedBuyRate - } else if !tokenConfig.Edges.Currency.MarketBuyRate.IsZero() { - // Floating buy rate: market_buy_rate + floating_buy_delta (delta may be zero) - rate = tokenConfig.Edges.Currency.MarketBuyRate.Add(tokenConfig.FloatingBuyDelta).RoundBank(2) - } - case RateSideSell: - if !tokenConfig.FixedSellRate.IsZero() { - rate = tokenConfig.FixedSellRate - } else if !tokenConfig.Edges.Currency.MarketSellRate.IsZero() { - // Floating sell rate: market_sell_rate + floating_sell_delta (delta may be zero) - rate = tokenConfig.Edges.Currency.MarketSellRate.Add(tokenConfig.FloatingSellDelta).RoundBank(2) - } - } - - return rate, nil -} - -// deleteQueue deletes existing circular queue -func (s *PriorityQueueService) deleteQueue(ctx context.Context, key string) error { - _, err := storage.RedisClient.Del(ctx, key).Result() - if err != nil { - return err - } - - return nil -} - -// buildQueueForSide builds a priority queue for a specific side (buy or sell) and saves it to redis -func (s *PriorityQueueService) buildQueueForSide(ctx context.Context, bucket *ent.ProvisionBucket, providers []*ent.ProviderProfile, side RateSide) { - baseRedisKey := fmt.Sprintf("bucket_%s_%s_%s", bucket.Edges.Currency.Code, bucket.MinAmount, bucket.MaxAmount) - redisKey := baseRedisKey + "_" + string(side) - prevRedisKey := redisKey + "_prev" - tempRedisKey := redisKey + "_temp" - orderConf := config.OrderConfig() - - // Copy the current queue to the previous queue (backup before rebuilding) - prevData, err := storage.RedisClient.LRange(ctx, redisKey, 0, -1).Result() - if err != nil && err != context.Canceled { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Key": redisKey, - }).Errorf("failed to fetch provider rates") - // If we can't read current queue, abort to prevent data loss - return - } - - // Convert []string to []interface{} - prevValues := make([]interface{}, len(prevData)) - for i, v := range prevData { - prevValues[i] = v - } - - // Delete the previous queue before backing up - err = s.deleteQueue(ctx, prevRedisKey) - if err != nil && err != context.Canceled { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Key": prevRedisKey, - }).Errorf("failed to delete previous provider queue") - } - - // Update the previous queue with current queue data (backup) - if len(prevValues) > 0 { - err = storage.RedisClient.RPush(ctx, prevRedisKey, prevValues...).Err() - if err != nil && err != context.Canceled { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Key": prevRedisKey, - "Values": prevValues, - }).Errorf("failed to store previous provider rates") - // If backup fails, abort to prevent data loss - return - } - } - - // Delete the temporary queue if it exists (from a previous failed build) - err = s.deleteQueue(ctx, tempRedisKey) - if err != nil && err != context.Canceled { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Key": tempRedisKey, - }).Errorf("failed to delete temporary provider queue") - } - - // TODO: add also the checks for all the currencies that a provider has - - // Build entries per provider first (provider ID -> list of queue entry strings) for equal slots with cap - providerEntries := make(map[string][]string) - for _, provider := range providers { - if orderConf.FallbackProviderID != "" && provider.ID == orderConf.FallbackProviderID { - continue - } - exists, err := provider.QueryProviderBalances(). - Where(providerbalances.HasFiatCurrencyWith(fiatcurrency.IDEQ(bucket.Edges.Currency.ID))). - Exist(ctx) - if err != nil || !exists { - continue - } - orderTokens, err := storage.Client.ProviderOrderToken. - Query(). - Where( - providerordertoken.HasProviderWith(providerprofile.IDEQ(provider.ID)), - providerordertoken.HasCurrencyWith(fiatcurrency.CodeEQ(bucket.Edges.Currency.Code)), - providerordertoken.SettlementAddressNEQ(""), - ). - WithToken(). - WithCurrency(). - All(ctx) - if err != nil { - if err != context.Canceled { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "ProviderID": provider.ID, - "Currency": bucket.Edges.Currency.Code, - }).Errorf("failed to get tokens for provider") - } - continue - } - - // Use map to deduplicate by symbol:network combination - // This allows same token symbol on different networks (e.g., USDT on Ethereum vs Tron) - tokenKeys := make(map[string]bool) - var entries []string - for _, orderToken := range orderTokens { - // Create a unique key combining symbol and network - tokenKey := fmt.Sprintf("%s:%s", orderToken.Edges.Token.Symbol, orderToken.Network) - if tokenKeys[tokenKey] { - continue - } - tokenKeys[tokenKey] = true - - rate, err := s.GetProviderRate(ctx, provider, orderToken.Edges.Token.Symbol, bucket.Edges.Currency.Code, side) - if err != nil { - if err != context.Canceled { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "ProviderID": provider.ID, - "Token": orderToken.Edges.Token.Symbol, - "Currency": bucket.Edges.Currency.Code, - "Side": string(side), - }).Errorf("failed to get rate for provider") - } - continue - } - - if rate.IsZero() { - continue - } - - // Check provider's rate against the market rate to ensure it's not too far off - var marketRate decimal.Decimal - if side == RateSideBuy { - marketRate = bucket.Edges.Currency.MarketBuyRate - } else { - marketRate = bucket.Edges.Currency.MarketSellRate - } - - percentDeviation := utils.AbsPercentageDeviation(marketRate, rate) - - isLocalStablecoin := strings.Contains(orderToken.Edges.Token.Symbol, bucket.Edges.Currency.Code) - if serverConf.Environment == "production" && percentDeviation.GreaterThan(orderConf.PercentDeviationFromMarketRate) && !isLocalStablecoin { - // Skip this provider if the rate is too far off - // TODO: add a logic to notify the provider(s) to update his rate since it's stale. could be a cron job - continue - } - - // Serialize the provider ID, token, network, rate, min and max order amount into a single string - data := fmt.Sprintf("%s:%s:%s:%s:%s:%s", provider.ID, orderToken.Edges.Token.Symbol, orderToken.Network, rate, orderToken.MinOrderAmount, orderToken.MaxOrderAmount) - entries = append(entries, data) - } - if len(entries) > 0 { - providerEntries[provider.ID] = entries - } - } - - // Normalize so each provider has the same number of slots (fair distribution: one turn per slot). - // Cap each provider at maxProviderSlots to bound queue size and keep matchRate fast. - const maxProviderSlots = 20 - var maxLen int - for _, entries := range providerEntries { - if n := len(entries); n > maxLen { - maxLen = n - } - } - if maxLen > maxProviderSlots { - maxLen = maxProviderSlots - } - var normalized []string - for _, entries := range providerEntries { - if maxLen == 0 { - break - } - for i := 0; i < maxLen; i++ { - normalized = append(normalized, entries[i%len(entries)]) - } - } - rand.Shuffle(len(normalized), func(i, j int) { normalized[i], normalized[j] = normalized[j], normalized[i] }) - - newQueueEntries := len(normalized) - for _, data := range normalized { - err = storage.RedisClient.RPush(ctx, tempRedisKey, data).Err() - if err != nil && err != context.Canceled { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Key": tempRedisKey, - "Data": data, - }).Errorf("failed to enqueue provider data to circular queue") - break - } - } - - // Only swap queues if new queue has entries, otherwise keep the old queue - if newQueueEntries > 0 { - // Delete the current queue - err = s.deleteQueue(ctx, redisKey) - if err != nil && err != context.Canceled { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Key": redisKey, - }).Errorf("failed to delete existing circular queue") - // Clean up temp queue if deletion failed - _ = s.deleteQueue(ctx, tempRedisKey) - return - } - - // Rename temp queue to current queue (atomic operation) - // Since Redis doesn't have RENAME for lists, we copy and delete - tempData, err := storage.RedisClient.LRange(ctx, tempRedisKey, 0, -1).Result() - if err != nil && err != context.Canceled { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Key": tempRedisKey, - }).Errorf("failed to read temporary queue for swap") - // Clean up temp queue - _ = s.deleteQueue(ctx, tempRedisKey) - return - } - - // Copy temp queue to current queue - if len(tempData) > 0 { - tempValues := make([]interface{}, len(tempData)) - for i, v := range tempData { - tempValues[i] = v - } - err = storage.RedisClient.RPush(ctx, redisKey, tempValues...).Err() - if err != nil && err != context.Canceled { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Key": redisKey, - }).Errorf("failed to copy temporary queue to current queue") - // Clean up temp queue - _ = s.deleteQueue(ctx, tempRedisKey) - return - } - } - - // Delete temporary queue after successful swap - err = s.deleteQueue(ctx, tempRedisKey) - if err != nil && err != context.Canceled { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Key": tempRedisKey, - }).Errorf("failed to delete temporary queue after swap (non-critical)") - } - } else { - // New queue is empty, keep the old queue and clean up temp - _ = s.deleteQueue(ctx, tempRedisKey) - // Sanitize retained queue: remove fallback provider entries when config dictates - if orderConf.FallbackProviderID != "" { - oldData, err := storage.RedisClient.LRange(ctx, redisKey, 0, -1).Result() - if err == nil && len(oldData) > 0 { - var filtered []interface{} - for _, entry := range oldData { - parts := strings.SplitN(entry, ":", 2) - if len(parts) >= 1 && parts[0] != orderConf.FallbackProviderID { - filtered = append(filtered, entry) - } - } - if len(filtered) < len(oldData) { - _ = s.deleteQueue(ctx, redisKey) - if len(filtered) > 0 { - _ = storage.RedisClient.RPush(ctx, redisKey, filtered...).Err() - } - } - } - } - } -} - -// CreatePriorityQueueForBucket creates priority queues for a bucket (both buy and sell sides) and saves them to redis -func (s *PriorityQueueService) CreatePriorityQueueForBucket(ctx context.Context, bucket *ent.ProvisionBucket) { - providers := bucket.Edges.ProviderProfiles - - // Randomize the order of providers - rand.Shuffle(len(providers), func(i, j int) { - providers[i], providers[j] = providers[j], providers[i] - }) - - // Build queues for both buy and sell sides - s.buildQueueForSide(ctx, bucket, providers, RateSideBuy) - s.buildQueueForSide(ctx, bucket, providers, RateSideSell) -} - -// tryUsePreSetProvider fetches the provider by order.ProviderID, optionally refreshes rate, then assigns (OTC or sendOrderRequest). -// Returns (true, provider, nil) if assignment succeeded; (false, provider, err) otherwise. Caller uses provider to decide private early-return. -func (s *PriorityQueueService) tryUsePreSetProvider(ctx context.Context, order types.PaymentOrderFields) (assigned bool, provider *ent.ProviderProfile, err error) { - provider, err = storage.Client.ProviderProfile. - Query(). - Where(providerprofile.IDEQ(order.ProviderID)). - Only(ctx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("failed to get provider") - return false, nil, err - } - - if !order.UpdatedAt.IsZero() && order.UpdatedAt.Before(time.Now().Add(-10*time.Minute)) { - currencyCode := "" - if order.ProvisionBucket != nil && order.ProvisionBucket.Edges.Currency != nil { - currencyCode = order.ProvisionBucket.Edges.Currency.Code - } - if currencyCode == "" && order.Institution != "" { - institution, instErr := utils.GetInstitutionByCode(ctx, order.Institution, true) - if instErr == nil && institution != nil && institution.Edges.FiatCurrency != nil { - currencyCode = institution.Edges.FiatCurrency.Code - } - } - if currencyCode != "" { - // PaymentOrderFields does not have Direction; use sell rate for pre-set provider refresh (payout is common) - order.Rate, err = s.GetProviderRate(ctx, provider, order.Token.Symbol, currencyCode, RateSideSell) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("failed to get rate for provider") - } else { - _, err = storage.Client.PaymentOrder. - Update(). - Where(paymentorder.MessageHashEQ(order.MessageHash)). - SetRate(order.Rate). - Save(ctx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("failed to update rate for provider") - } - } - } - } - - if order.OrderType == "otc" { - if err := s.assignOtcOrder(ctx, order); err != nil { - return false, provider, err - } - return true, provider, nil - } - err = s.sendOrderRequest(ctx, order) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("failed to send order request to specific provider") - return false, provider, err - } - return true, provider, nil -} - -// AssignPaymentOrder assigns payment orders to providers -func (s *PriorityQueueService) AssignPaymentOrder(ctx context.Context, order types.PaymentOrderFields) error { - orderIDPrefix := strings.Split(order.ID.String(), "-")[0] - orderConf := config.OrderConfig() - - // Both regular and OTC orders must have a provision bucket, unless order has a pre-set private provider (private orders don't require buckets). - allowNilBucketForPrivate := false - if order.ProvisionBucket == nil { - if order.ProviderID != "" { - providerForCheck, pErr := storage.Client.ProviderProfile.Query().Where(providerprofile.IDEQ(order.ProviderID)).Only(ctx) - if pErr == nil && providerForCheck != nil && providerForCheck.VisibilityMode == providerprofile.VisibilityModePrivate { - allowNilBucketForPrivate = true - } - } - if !allowNilBucketForPrivate { - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "OrderType": order.OrderType, - "Reason": "internal: Order missing provision bucket", - }).Errorf("AssignPaymentOrder.MissingProvisionBucket") - return fmt.Errorf("order %s (type: %s) is missing provision bucket", order.ID.String(), order.OrderType) - } - } else if order.ProvisionBucket.Edges.Currency == nil { - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "OrderType": order.OrderType, - "Reason": "internal: Provision bucket missing currency", - }).Errorf("AssignPaymentOrder.MissingCurrency") - return fmt.Errorf("provision bucket for order %s (type: %s) is missing currency", order.ID.String(), order.OrderType) - } - - // Defensive check: Verify order is in a valid state for assignment - // This prevents duplicate assignments from concurrent sources - currentOrder, err := storage.Client.PaymentOrder.Get(ctx, order.ID) - if err == nil { - // Order exists - check if it's in a state that allows assignment - if currentOrder.Status != paymentorder.StatusPending { - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "Status": currentOrder.Status, - }).Errorf("AssignPaymentOrder: Order is not in pending state, skipping assignment") - return nil // Not an error, just skip - } - - // Check if order request already exists in Redis (idempotency check) - orderKey := fmt.Sprintf("order_request_%s", order.ID) - exists, err := storage.RedisClient.Exists(ctx, orderKey).Result() - if err == nil && exists > 0 { - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "Status": currentOrder.Status, - }).Errorf("AssignPaymentOrder: Order request already exists, skipping duplicate assignment") - return nil // Not an error, already assigned - } - } else if !ent.IsNotFound(err) { - // Error fetching order (other than not found) - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - }).Errorf("AssignPaymentOrder: Failed to check order status") - // Continue anyway - might be a new order - } - - excludeList, err := storage.RedisClient.LRange(ctx, fmt.Sprintf("order_exclude_list_%s", order.ID), 0, -1).Result() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("failed to get exclude list") - return err - } - - // Compute rate side once from order direction (currentOrder if in DB, else default buy) for rate refresh and queue key - var rateSide RateSide - if currentOrder != nil { - switch currentOrder.Direction { - case paymentorder.DirectionOnramp: - rateSide = RateSideBuy - case paymentorder.DirectionOfframp: - rateSide = RateSideSell - default: - rateSide = RateSideBuy - } - } else { - rateSide = RateSideBuy // default when order not yet in DB (e.g. new order) - } - - // Sends order directly to the specified provider in order. - // Incase of failure, do nothing. The order will eventually refund - // For OTC orders: skip if provider appears in exclude list at all - // For regular orders: only skip if provider has exceeded max retry attempts - if order.ProviderID != "" { - excludeCount := s.countProviderInExcludeList(excludeList, order.ProviderID) - shouldSkip := false - if order.OrderType == "otc" { - // OTC orders skip immediately if provider is in exclude list - shouldSkip = excludeCount > 0 - } else { - // Regular orders allow up to max retry attempts - shouldSkip = excludeCount >= orderConf.ProviderMaxRetryAttempts - } - if shouldSkip { - // Provider should be skipped, continue to queue matching - } else if order.OrderType != "otc" && orderConf.ProviderStuckFulfillmentThreshold > 0 { - // Regular orders: skip pre-set provider only when stuck count is at or over threshold - stuckCount, errStuck := utils.GetProviderStuckOrderCount(ctx, order.ProviderID) - if errStuck == nil && stuckCount >= orderConf.ProviderStuckFulfillmentThreshold { - // Fall through to queue matching - } else { - if errStuck != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", errStuck), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("failed to get stuck order count for pre-set provider") - } - assigned, provider, _ := s.tryUsePreSetProvider(ctx, order) - if assigned { - return nil - } - if provider != nil && provider.VisibilityMode == providerprofile.VisibilityModePrivate { - return nil - } - } - } else { - // OTC or threshold 0: use pre-set provider without stuck check - assigned, provider, _ := s.tryUsePreSetProvider(ctx, order) - if assigned { - return nil - } - if provider != nil && provider.VisibilityMode == providerprofile.VisibilityModePrivate { - return nil - } - } - } - - // Private orders with nil bucket only use the pre-set path above; do not run queue matching. - if order.ProvisionBucket == nil { - return nil - } - - // Use same side-suffixed key as buildQueueForSide so reads/writes use identical keys (rateSide computed above) - baseRedisKey := fmt.Sprintf("bucket_%s_%s_%s", order.ProvisionBucket.Edges.Currency.Code, order.ProvisionBucket.MinAmount, order.ProvisionBucket.MaxAmount) - redisKey := baseRedisKey + "_" + string(rateSide) - - err = s.matchRate(ctx, redisKey, orderIDPrefix, order, excludeList) - if err != nil { - prevRedisKey := redisKey + "_prev" - err = s.matchRate(ctx, prevRedisKey, orderIDPrefix, order, excludeList) - if err != nil { - // Both matchRate attempts failed; try fallback once for regular orders - matchRateErr := err - if order.OrderType != "otc" { - orderEnt, loadErr := storage.Client.PaymentOrder.Query(). - Where(paymentorder.IDEQ(order.ID)). - WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() }). - Only(ctx) - if loadErr == nil { - if fallbackErr := s.TryFallbackAssignment(ctx, orderEnt); fallbackErr == nil { - return nil - } else { - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "Error": fallbackErr.Error(), - }).Errorf("AssignPaymentOrder: TryFallbackAssignment failed after no provider in queue") - var errStuck *types.ErrNoProviderDueToStuck - if errors.As(fallbackErr, &errStuck) { - return fallbackErr - } - } - } - } - return fmt.Errorf("no provider matched for order: %w", matchRateErr) - } - } - - return nil -} - -// TryFallbackAssignment attempts to assign the order to the configured fallback provider using only rate and balance checks. -// It accepts *ent.PaymentOrder and converts to the internal assignment type; callers do not need to build PaymentOrderFields. -// Slippage is taken from the fallback provider's ProviderOrderToken (rate_slippage). Returns a clear error if fallback -// was attempted but order rate is outside the fallback provider's acceptable slippage. -func (s *PriorityQueueService) TryFallbackAssignment(ctx context.Context, order *ent.PaymentOrder) error { - orderConf := config.OrderConfig() - fallbackID := orderConf.FallbackProviderID - if fallbackID == "" { - return fmt.Errorf("fallback provider not configured") - } - if order.OrderType == paymentorder.OrderTypeOtc { - return fmt.Errorf("fallback is only for regular orders, not OTC") - } - - // Check idempotency first (before any DB state check) to avoid race: another process may assign between state check and assignment. - orderKey := fmt.Sprintf("order_request_%s", order.ID) - exists, err := storage.RedisClient.Exists(ctx, orderKey).Result() - if err != nil { - return fmt.Errorf("fallback: failed to check order_request: %w", err) - } - if exists > 0 { - return fmt.Errorf("fallback: order %s already has an active order_request", order.ID) - } - - // Verify order is still in a state that allows assignment; DB-level idempotency for fallback. - // Eagerly load ProvisionBucket+Currency so we never need a separate fallback query for them. - currentOrder, err := storage.Client.PaymentOrder.Query(). - Where(paymentorder.IDEQ(order.ID)). - WithProvisionBucket(func(pb *ent.ProvisionBucketQuery) { - pb.WithCurrency() - }). - Only(ctx) - if err != nil { - return fmt.Errorf("fallback: failed to load order: %w", err) - } - if !currentOrder.FallbackTriedAt.IsZero() { - return fmt.Errorf("fallback: order %s already had fallback assignment tried", order.ID) - } - assignable := currentOrder.Status == paymentorder.StatusPending || currentOrder.Status == paymentorder.StatusCancelled - if currentOrder.Status == paymentorder.StatusFulfilled { - tx, txErr := storage.Client.Tx(ctx) - if txErr != nil { - return fmt.Errorf("fallback: failed to start transaction for order %s: %w", order.ID, txErr) - } - deleted, delErr := tx.PaymentOrderFulfillment.Delete(). - Where( - paymentorderfulfillment.HasOrderWith(paymentorder.IDEQ(order.ID)), - paymentorderfulfillment.ValidationStatusEQ(paymentorderfulfillment.ValidationStatusFailed), - ).Exec(ctx) - if delErr != nil { - _ = tx.Rollback() - return fmt.Errorf("fallback: failed to delete fulfillments for order %s: %w", order.ID, delErr) - } - if deleted == 0 { - _ = tx.Rollback() - return fmt.Errorf("fallback: order %s is fulfilled with no failed fulfillments, not assignable", order.ID) - } - if _, updErr := tx.PaymentOrder.UpdateOneID(order.ID). - ClearProvider(). - SetStatus(paymentorder.StatusPending). - Save(ctx); updErr != nil { - _ = tx.Rollback() - return fmt.Errorf("fallback: failed to reset order %s to Pending after deleting fulfillments: %w", order.ID, updErr) - } - if commitErr := tx.Commit(); commitErr != nil { - return fmt.Errorf("fallback: failed to commit transaction for order %s: %w", order.ID, commitErr) - } - assignable = true - } - if !assignable { - return fmt.Errorf("fallback: order %s is in state %s, not assignable", order.ID, currentOrder.Status) - } - - // Convert ent order to PaymentOrderFields for the rest of the fallback logic - if order.AccountIdentifier == "" || order.Institution == "" || order.AccountName == "" { - return fmt.Errorf("fallback: order %s has no recipient information", order.ID.String()) - } - fields := types.PaymentOrderFields{ - ID: order.ID, - OrderType: order.OrderType.String(), - Token: order.Edges.Token, - Network: nil, - GatewayID: order.GatewayID, - Amount: order.Amount, - Rate: order.Rate, - Institution: order.Institution, - AccountIdentifier: order.AccountIdentifier, - AccountName: order.AccountName, - ProviderID: "", - ProvisionBucket: currentOrder.Edges.ProvisionBucket, - MessageHash: order.MessageHash, - Memo: order.Memo, - UpdatedAt: order.UpdatedAt, - CreatedAt: order.CreatedAt, - } - if order.Edges.Token != nil && order.Edges.Token.Edges.Network != nil { - fields.Network = order.Edges.Token.Edges.Network - } - - if fields.Token == nil { - return fmt.Errorf("fallback: order %s has no token", order.ID.String()) - } - - // If order has no bucket yet, resolve one from institution currency + fiat amount. - if fields.ProvisionBucket == nil { - institution, instErr := utils.GetInstitutionByCode(ctx, order.Institution, true) - if instErr != nil { - return fmt.Errorf("fallback: cannot resolve bucket for order %s: institution lookup failed: %w", fields.ID.String(), instErr) - } - if institution.Edges.FiatCurrency == nil { - return fmt.Errorf("fallback: cannot resolve bucket for order %s: institution %s has no fiat currency", fields.ID.String(), order.Institution) - } - fiatAmount := order.Amount.Mul(order.Rate) - bucket, bErr := storage.Client.ProvisionBucket. - Query(). - Where( - provisionbucket.MaxAmountGTE(fiatAmount), - provisionbucket.MinAmountLTE(fiatAmount), - provisionbucket.HasCurrencyWith(fiatcurrency.IDEQ(institution.Edges.FiatCurrency.ID)), - ). - WithCurrency(). - Only(ctx) - if bErr != nil { - return fmt.Errorf("fallback: no matching provision bucket for order %s (fiat %s %s): %w", - fields.ID.String(), fiatAmount.String(), institution.Edges.FiatCurrency.Code, bErr) - } - fields.ProvisionBucket = bucket - // Persist so later flows (e.g. FulfillOrder) see the bucket and do not panic on nil ProvisionBucket - if _, upErr := storage.Client.PaymentOrder.UpdateOneID(fields.ID).SetProvisionBucket(bucket).Save(ctx); upErr != nil { - return fmt.Errorf("fallback: failed to set provision bucket on order %s: %w", fields.ID.String(), upErr) - } - } - - bucketCurrency := fields.ProvisionBucket.Edges.Currency - if bucketCurrency == nil { - return fmt.Errorf("fallback: provision bucket %d missing currency", fields.ProvisionBucket.ID) - } - - // Skip fallback provider if at or over stuck fulfillment threshold - if orderConf.ProviderStuckFulfillmentThreshold > 0 { - stuckCount, errStuck := utils.GetProviderStuckOrderCount(ctx, fallbackID) - if errStuck == nil && stuckCount >= orderConf.ProviderStuckFulfillmentThreshold { - return &types.ErrNoProviderDueToStuck{CurrencyCode: bucketCurrency.Code} - } - if errStuck != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", errStuck), - "FallbackID": fallbackID, - "Currency": bucketCurrency.Code, - }).Errorf("fallback: failed to get stuck order count, proceeding with assignment (fail-open)") - } - } - - // Resolve fallback provider - provider, err := storage.Client.ProviderProfile.Get(ctx, fallbackID) - if err != nil { - if ent.IsNotFound(err) { - return fmt.Errorf("fallback provider %s not found", fallbackID) - } - return fmt.Errorf("failed to get fallback provider: %w", err) - } - - network := fields.Token.Edges.Network - if network == nil { - var nErr error - network, nErr = fields.Token.QueryNetwork().Only(ctx) - if nErr != nil { - return fmt.Errorf("fallback: token missing network: %w", nErr) - } - } - - // ProviderOrderToken for fallback (token, network, currency) – same pattern as matchRate, carries provider-configured rate_slippage. - // IsAvailableEQ(true) is intentional: fallback is only used when it has available balance for the currency, same as regular queue. - providerToken, err := storage.Client.ProviderOrderToken. - Query(). - Where( - providerordertoken.NetworkEQ(network.Identifier), - providerordertoken.HasProviderWith( - providerprofile.IDEQ(fallbackID), - providerprofile.HasProviderBalancesWith( - providerbalances.HasFiatCurrencyWith(fiatcurrency.CodeEQ(bucketCurrency.Code)), - providerbalances.IsAvailableEQ(true), - ), - ), - providerordertoken.HasTokenWith(token.IDEQ(fields.Token.ID)), - providerordertoken.HasCurrencyWith(fiatcurrency.CodeEQ(bucketCurrency.Code)), - providerordertoken.SettlementAddressNEQ(""), - ). - First(ctx) - if err != nil { - if ent.IsNotFound(err) { - return fmt.Errorf("fallback provider %s has no order token for %s/%s/%s", fallbackID, fields.Token.Symbol, network.Identifier, bucketCurrency.Code) - } - return fmt.Errorf("fallback: failed to get provider order token: %w", err) - } - - // Rate check: must match what fallback provider can take (use token's rate_slippage) - providerRate, err := s.GetProviderRate(ctx, provider, fields.Token.Symbol, bucketCurrency.Code, RateSideSell) - if err != nil { - return fmt.Errorf("fallback: failed to get provider rate: %w", err) - } - allowedDeviation := fields.Rate.Mul(providerToken.RateSlippage.Div(decimal.NewFromInt(100))) - if providerRate.Sub(fields.Rate).Abs().GreaterThan(allowedDeviation) { - logger.WithFields(logger.Fields{ - "OrderID": fields.ID.String(), - "FallbackID": fallbackID, - "OrderRate": fields.Rate.String(), - "ProviderRate": providerRate.String(), - "SlippagePct": providerToken.RateSlippage.String(), - }).Errorf("[FALLBACK_ASSIGNMENT] fallback assignment attempted but order rate is too far from what fallback node can fulfill") - return fmt.Errorf("fallback assignment attempted for order %s but order rate is too far from what fallback provider %s can fulfill (provider rate %s, order rate %s, allowed slippage %s%%)", - fields.ID.String(), fallbackID, providerRate.String(), fields.Rate.String(), providerToken.RateSlippage.String()) - } - - // Balance check (same as matchRate) - bal, err := s.balanceService.GetProviderFiatBalance(ctx, fallbackID, bucketCurrency.Code) - if err != nil { - return fmt.Errorf("fallback: failed to get provider balance: %w", err) - } - if !s.balanceService.CheckBalanceSufficiency(bal, fields.Amount.Mul(fields.Rate).RoundBank(0)) { - return fmt.Errorf("fallback provider %s has insufficient balance for order %s", fallbackID, fields.ID.String()) - } - - // Assign to fallback (regular orders only; OTC excluded above) - fields.ProviderID = fallbackID - - if err := s.sendOrderRequest(ctx, fields); err != nil { - return fmt.Errorf("fallback: send order request: %w", err) - } - if _, setErr := storage.Client.PaymentOrder.UpdateOneID(fields.ID). - SetFallbackTriedAt(time.Now()). - SetOrderPercent(decimal.NewFromInt(100)). - Save(ctx); setErr != nil { - logger.WithFields(logger.Fields{"OrderID": fields.ID.String(), "Error": setErr}).Errorf("[FALLBACK_ASSIGNMENT] failed to set fallback_tried_at on order") - return fmt.Errorf("fallback: failed to set fallback_tried_at (idempotency): %w", setErr) - } - logger.WithFields(logger.Fields{"OrderID": fields.ID.String(), "FallbackID": fallbackID}).Infof("[FALLBACK_ASSIGNMENT] successful fallback assignment") - return nil -} - -// assignOtcOrder assigns an OTC order to a provider and creates a Redis key for reassignment. -// DB updates are committed first; Redis operations run afterward to avoid mixing transaction scope with Redis. -func (s *PriorityQueueService) assignOtcOrder(ctx context.Context, order types.PaymentOrderFields) error { - orderConf := config.OrderConfig() - tx, err := storage.Client.Tx(ctx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("Failed to start transaction for OTC order assignment") - return fmt.Errorf("failed to start transaction: %w", err) - } - defer func() { - if err != nil { - _ = tx.Rollback() - } - }() - - // DB only: assign OTC order to provider (no balance reservation, no provision node request) - if order.ProviderID != "" { - provider, qErr := tx.ProviderProfile.Query().Where(providerprofile.IDEQ(order.ProviderID)).Only(ctx) - if qErr != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", qErr), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("failed to get provider for OTC order assignment") - return fmt.Errorf("failed to get provider: %w", qErr) - } - if provider != nil { - _, err = tx.PaymentOrder. - Update(). - Where(paymentorder.IDEQ(order.ID)). - SetProvider(provider). - Save(ctx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("failed to assign OTC order to provider") - return fmt.Errorf("failed to assign OTC order: %w", err) - } - } - } - - if err = tx.Commit(); err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("Failed to commit OTC order assignment transaction") - return fmt.Errorf("failed to commit transaction: %w", err) - } - - // Redis operations after DB commit to avoid mixing transaction scope with Redis - orderKey := fmt.Sprintf("order_request_%s", order.ID) - exists, err := storage.RedisClient.Exists(ctx, orderKey).Result() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "OrderKey": orderKey, - }).Errorf("Failed to check if OTC order request exists in Redis") - return fmt.Errorf("failed to check order_request in Redis: %w", err) - } - if exists > 0 { - // Verify provider matches to avoid DB/Redis inconsistency (same as sendOrderRequest). - existingProviderID, hgetErr := storage.RedisClient.HGet(ctx, orderKey, "providerId").Result() - if hgetErr == nil && existingProviderID == order.ProviderID { - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "OrderKey": orderKey, - }).Warnf("OTC order request already exists in Redis for same provider - skipping duplicate creation") - return nil - } - if hgetErr == nil && existingProviderID != order.ProviderID { - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "ExistingProviderID": existingProviderID, - "OrderKey": orderKey, - }).Errorf("OTC order request exists for different provider - DB/Redis consistency issue") - return fmt.Errorf("order_request exists for different provider (redis=%s, current=%s)", existingProviderID, order.ProviderID) - } - // HGet failed or key has no providerId - treat as inconsistency - verifyErr := hgetErr - if verifyErr == nil { - verifyErr = fmt.Errorf("providerId missing in Redis hash") - } - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "OrderKey": orderKey, - "Error": verifyErr, - }).Errorf("OTC order request exists but could not verify provider - skipping to avoid inconsistency") - return fmt.Errorf("order_request exists but provider could not be verified: %w", verifyErr) - } - - orderRequestData := map[string]interface{}{ - "type": "otc", - "providerId": order.ProviderID, - } - if err = storage.RedisClient.HSet(ctx, orderKey, orderRequestData).Err(); err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "OrderKey": orderKey, - }).Errorf("Failed to create Redis key for OTC order") - return fmt.Errorf("failed to create order_request in Redis: %w", err) - } - if err = storage.RedisClient.ExpireAt(ctx, orderKey, time.Now().Add(orderConf.OrderRequestValidityOtc)).Err(); err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "OrderKey": orderKey, - }).Errorf("Failed to set TTL for OTC order request") - _ = storage.RedisClient.Del(ctx, orderKey).Err() - return fmt.Errorf("failed to set TTL for order_request: %w", err) - } - - return nil -} - -// countProviderInExcludeList counts how many times a provider appears in the exclude list -func (s *PriorityQueueService) countProviderInExcludeList(excludeList []string, providerID string) int { - count := 0 - for _, id := range excludeList { - if id == providerID { - count++ - } - } - return count -} - -// getExcludePsps returns PSP names to exclude for a new_order based only on the global failure-rate threshold -// PSPs that have high failure rate in the last M minutes. Per-order exclusion is not used so the -// same order can retry a PSP after a transient failure. -func (s *PriorityQueueService) getExcludePsps(ctx context.Context) ([]string, error) { - orderConf := config.OrderConfig() - excluded := make(map[string]struct{}) - - // PSPs with high failure rate in the last M minutes (any failed fulfillment after disbursement trial) - window := time.Duration(orderConf.PspExcludeWindowMinutes) * time.Minute - if window <= 0 { - window = 120 * time.Minute - } - since := time.Now().Add(-window) - - fulfillments, err := storage.Client.PaymentOrderFulfillment.Query(). - Where(paymentorderfulfillment.UpdatedAtGTE(since)). - Select( - paymentorderfulfillment.FieldPsp, - paymentorderfulfillment.FieldValidationStatus, - ). - All(ctx) - if err != nil { - return nil, fmt.Errorf("global exclude PSPs: %w", err) - } - - // Group by PSP: attempts = count, failures = count where status failed (any error) - type stats struct{ attempts, failures int } - byPsp := make(map[string]*stats) - for _, f := range fulfillments { - psp := strings.TrimSpace(f.Psp) - if psp == "" { - continue - } - if byPsp[psp] == nil { - byPsp[psp] = &stats{} - } - byPsp[psp].attempts++ - if f.ValidationStatus == paymentorderfulfillment.ValidationStatusFailed { - byPsp[psp].failures++ - } - } - - minAttempts := orderConf.PspExcludeMinAttempts - if minAttempts < 1 { - minAttempts = 5 - } - minFailures := orderConf.PspExcludeMinFailures - if minFailures < 1 { - minFailures = 3 - } - minPercent := orderConf.PspExcludeMinFailurePercent - if minPercent <= 0 { - minPercent = 30 - } - minRate := float64(minPercent) / 100 - - for psp, st := range byPsp { - if st.attempts < minAttempts || st.failures < minFailures { - continue - } - rate := float64(st.failures) / float64(st.attempts) - if rate >= minRate { - excluded[psp] = struct{}{} - } - } - - out := make([]string, 0, len(excluded)) - for p := range excluded { - out = append(out, p) - } - return out, nil -} - -// addProviderToExcludeList adds a provider to the order exclude list with TTL -// This is a best-effort operation - errors are logged but don't fail the operation -func (s *PriorityQueueService) addProviderToExcludeList(ctx context.Context, orderID string, providerID string, ttl time.Duration) { - orderKey := fmt.Sprintf("order_exclude_list_%s", orderID) - _, err := storage.RedisClient.RPush(ctx, orderKey, providerID).Result() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": orderID, - "ProviderID": providerID, - }).Errorf("failed to push provider to order exclude list") - return - } - - // Set TTL for the exclude list - err = storage.RedisClient.ExpireAt(ctx, orderKey, time.Now().Add(ttl)).Err() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderKey": orderKey, - }).Errorf("failed to set TTL for order exclude list") - } -} - -// sendOrderRequest sends an order request to a provider -func (s *PriorityQueueService) sendOrderRequest(ctx context.Context, order types.PaymentOrderFields) error { - orderConf := config.OrderConfig() - // Reserve balance for this order - currency := order.ProvisionBucket.Edges.Currency.Code - amount := order.Amount.Mul(order.Rate).RoundBank(0) - - // Start a transaction for the entire operation - tx, err := storage.Client.Tx(ctx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "Currency": currency, - "Amount": amount.String(), - }).Errorf("Failed to start transaction for order processing") - return fmt.Errorf("failed to start transaction: %w", err) - } - defer func() { - if err != nil { - _ = tx.Rollback() - } - }() - - // Reserve balance within the transaction - err = s.balanceService.ReserveFiatBalance(ctx, order.ProviderID, currency, amount, tx) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "Currency": currency, - "Amount": amount.String(), - }).Errorf("Failed to reserve balance for order") - return err - } - - // Assign the order to the provider and save it to Redis - orderKey := fmt.Sprintf("order_request_%s", order.ID) - - // Check if order request already exists to prevent duplicate notifications - exists, err := storage.RedisClient.Exists(ctx, orderKey).Result() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "OrderKey": orderKey, - }).Errorf("Failed to check if order request exists in Redis") - return err - } - if exists > 0 { - // Order request already exists - this prevents double processing - // Verify it's for the same provider to avoid provider mismatch issues - existingProviderID, err := storage.RedisClient.HGet(ctx, orderKey, "providerId").Result() - if err == nil && existingProviderID == order.ProviderID { - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "OrderKey": orderKey, - }).Errorf("Order request already exists in Redis - skipping duplicate notification") - // Order request already sent, commit transaction and return success - err = tx.Commit() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("Failed to commit transaction for existing order request") - return fmt.Errorf("failed to commit transaction: %w", err) - } - return nil - } else if err == nil && existingProviderID != order.ProviderID { - // Different provider - this shouldn't happen but log it - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "ExistingProviderID": existingProviderID, - "OrderKey": orderKey, - }).Errorf("Order request exists for different provider - potential race condition") - _ = tx.Rollback() - return fmt.Errorf("order request exists for different provider") - } - } - - // TODO: Now we need to add currency - orderRequestData := map[string]interface{}{ - "amount": order.Amount.Mul(order.Rate).RoundBank(0).String(), - "institution": order.Institution, - "currency": order.ProvisionBucket.Edges.Currency.Code, - "providerId": order.ProviderID, - } - - err = storage.RedisClient.HSet(ctx, orderKey, orderRequestData).Err() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "OrderKey": orderKey, - }).Errorf("Failed to map order to a provider in Redis") - return err - } - - // Persist order request metadata in a separate key so we can recover provider/currency/amount - // after the main order_request key expires (Redis expiry events fire after deletion). - metaKey := fmt.Sprintf("order_request_meta_%s", order.ID) - metaData := map[string]interface{}{ - "amount": orderRequestData["amount"], - "currency": orderRequestData["currency"], - "providerId": orderRequestData["providerId"], - } - err = storage.RedisClient.HSet(ctx, metaKey, metaData).Err() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "MetaKey": metaKey, - }).Errorf("Failed to persist order request metadata in Redis") - // Cleanup: delete the orphaned order request key before returning - _ = storage.RedisClient.Del(ctx, orderKey).Err() - return err - } - - // Set a TTL for the order request - err = storage.RedisClient.ExpireAt(ctx, orderKey, time.Now().Add(orderConf.OrderRequestValidity)).Err() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderKey": orderKey, - }).Errorf("Failed to set TTL for order request") - // Cleanup: delete the orphaned keys before returning - cleanupErr := storage.RedisClient.Del(ctx, orderKey).Err() - if cleanupErr != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", cleanupErr), - "OrderKey": orderKey, - }).Errorf("Failed to cleanup orderKey after ExpireAt failure") - } - _ = storage.RedisClient.Del(ctx, metaKey).Err() - return err - } - - // Set TTL for metadata key longer than the order request key to ensure it exists during expiry handling. - err = storage.RedisClient.ExpireAt(ctx, metaKey, time.Now().Add(orderConf.OrderRequestValidity*2)).Err() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "MetaKey": metaKey, - }).Errorf("Failed to set TTL for order request metadata key") - // Cleanup: delete keys before returning - _ = storage.RedisClient.Del(ctx, orderKey).Err() - _ = storage.RedisClient.Del(ctx, metaKey).Err() - return err - } - - // Exclude PSPs: global high failure-rate only (same order can retry a PSP after transient failure). - // Do not apply excludePsps for the fallback provider so it can try all PSPs. - if orderConf.FallbackProviderID == "" || order.ProviderID != orderConf.FallbackProviderID { - excludePsps, excludeErr := s.getExcludePsps(ctx) - if excludeErr != nil { - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "Error": excludeErr.Error(), - }).Errorf("getExcludePsps failed, sending new_order without excludePsps") - } else if len(excludePsps) > 0 { - orderRequestData["excludePsps"] = excludePsps - } - } - - // Notify provider - orderRequestData["orderId"] = order.ID.String() - err = s.notifyProvider(ctx, orderRequestData) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("Failed to notify provider") - // Cleanup: delete the orphaned keys before returning - cleanupErr := storage.RedisClient.Del(ctx, orderKey).Err() - if cleanupErr != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", cleanupErr), - "OrderKey": orderKey, - }).Errorf("Failed to cleanup orderKey after notifyProvider failure") - } - _ = storage.RedisClient.Del(ctx, metaKey).Err() - return err - } - - // Commit the transaction if everything succeeded - err = tx.Commit() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("Failed to commit order processing transaction") - // Cleanup Redis keys since DB transaction failed - _ = storage.RedisClient.Del(ctx, orderKey).Err() - _ = storage.RedisClient.Del(ctx, metaKey).Err() - return fmt.Errorf("failed to commit transaction: %w", err) - } - - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "Currency": currency, - "Amount": amount.String(), - }).Infof("Order processed successfully with balance reserved") - - return nil -} - -// notifyProvider sends an order request notification to a provider -// TODO: ideally notifications should be moved to a notification service -func (s *PriorityQueueService) notifyProvider(ctx context.Context, orderRequestData map[string]interface{}) error { - // TODO: can we add mode and host identifier to redis during priority queue creation? - providerID := orderRequestData["providerId"].(string) - delete(orderRequestData, "providerId") - - // Call provider /new_order endpoint using utility function - data, err := utils.CallProviderWithHMAC(ctx, providerID, "POST", "/new_order", orderRequestData) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "ProviderID": providerID, - }).Errorf("failed to call provider /new_order endpoint") - return err - } - - // Log successful response data for debugging - logger.WithFields(logger.Fields{ - "ProviderID": providerID, - "Data": data, - }).Infof("successfully called provider /new_order endpoint") - - return nil -} - -// matchRate matches order rate with a provider rate -func (s *PriorityQueueService) matchRate(ctx context.Context, redisKey string, orderIDPrefix string, order types.PaymentOrderFields, excludeList []string) error { - orderConf := config.OrderConfig() - var considered, skippedDueToStuck int - for index := 0; ; index++ { - providerData, err := storage.RedisClient.LIndex(ctx, redisKey, int64(index)).Result() - if err != nil { - if considered > 0 && skippedDueToStuck == considered { - currencyCode := "" - if order.ProvisionBucket != nil && order.ProvisionBucket.Edges.Currency != nil { - currencyCode = order.ProvisionBucket.Edges.Currency.Code - } - return &types.ErrNoProviderDueToStuck{CurrencyCode: currencyCode} - } - return err - } - - // if providerData == "" { - // // Reached the end of the queue - // logger.Errorf("%s - rate didn't match a provider, finding a partner provider", orderIDPrefix) - - // if len(partnerProviders) == 0 { - // logger.Errorf("%s - no partner providers found", orderIDPrefix) - // return nil - // } - - // // Pick a random partner provider - // randomIndex := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(partnerProviders)) - // providerData = partnerProviders[randomIndex] - // } - - // Extract the rate from the data (format "providerID:token:network:rate:minAmount:maxAmount") - parts := strings.Split(providerData, ":") - if len(parts) != 6 { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "ProviderData": providerData, - }).Errorf("invalid data format at index %d when matching rate", index) - continue // Skip this entry due to invalid format - } - - order.ProviderID = parts[0] - - // Skip entry based on order type and exclude list count - excludeCount := s.countProviderInExcludeList(excludeList, order.ProviderID) - shouldSkip := false - if order.OrderType == "otc" { - // OTC orders skip immediately if provider is in exclude list - shouldSkip = excludeCount > 0 - } else { - // Regular orders allow up to max retry attempts - shouldSkip = excludeCount >= orderConf.ProviderMaxRetryAttempts - } - if shouldSkip { - continue - } - - // Skip entry if token doesn't match - if parts[1] != order.Token.Symbol { - continue - } - - // Skip entry if network doesn't match - network := order.Token.Edges.Network - if network == nil { - network, err = order.Token.QueryNetwork().Only(ctx) - if err != nil { - continue - } - } - if parts[2] != network.Identifier { - continue - } - - // Parse min/max order amounts and validate against order amount - minOrderAmount, err := decimal.NewFromString(parts[4]) - if err != nil { - continue - } - maxOrderAmount, err := decimal.NewFromString(parts[5]) - if err != nil { - continue - } - - // Check if order amount is within provider's min/max order amount limits - if order.Amount.LessThan(minOrderAmount) { - // Order amount is below provider's minimum - skip this provider - continue - } - - rate, err := decimal.NewFromString(parts[3]) - if err != nil { - continue - } - - // Fetch ProviderOrderToken for rate slippage and OTC limit checks - bucketCurrency := order.ProvisionBucket.Edges.Currency - if bucketCurrency == nil { - bucketCurrency, err = order.ProvisionBucket.QueryCurrency().Only(ctx) - if err != nil { - continue - } - } - - providerToken, err := storage.Client.ProviderOrderToken. - Query(). - Where( - providerordertoken.NetworkEQ(network.Identifier), - providerordertoken.HasProviderWith( - providerprofile.IDEQ(order.ProviderID), - providerprofile.HasProviderBalancesWith( - providerbalances.HasFiatCurrencyWith(fiatcurrency.CodeEQ(bucketCurrency.Code)), - providerbalances.IsAvailableEQ(true), - ), - ), - providerordertoken.HasTokenWith(token.IDEQ(order.Token.ID)), - providerordertoken.HasCurrencyWith( - fiatcurrency.CodeEQ(bucketCurrency.Code), - ), - providerordertoken.SettlementAddressNEQ(""), - ). - First(ctx) - if err != nil { - continue - } - - // Check if order amount exceeds provider's max order amount - if order.Amount.GreaterThan(maxOrderAmount) { - // Amount exceeds regular max - check OTC limits as fallback - if providerToken.MinOrderAmountOtc.IsZero() || providerToken.MaxOrderAmountOtc.IsZero() { - // OTC limits not configured - skip this provider - continue - } - if order.Amount.LessThan(providerToken.MinOrderAmountOtc) || order.Amount.GreaterThan(providerToken.MaxOrderAmountOtc) { - // Amount outside OTC limits - skip this provider - continue - } - } - - // Calculate allowed deviation based on slippage - allowedDeviation := order.Rate.Mul(providerToken.RateSlippage.Div(decimal.NewFromInt(100))) - - if rate.Sub(order.Rate).Abs().LessThanOrEqual(allowedDeviation) { - considered++ - // Regular orders: skip provider if at or over stuck fulfillment threshold - if order.OrderType != "otc" && orderConf.ProviderStuckFulfillmentThreshold > 0 { - stuckCount, errStuck := utils.GetProviderStuckOrderCount(ctx, order.ProviderID) - if errStuck == nil && stuckCount >= orderConf.ProviderStuckFulfillmentThreshold { - skippedDueToStuck++ - continue - } - } - - // Found a match for the rate - handle index pop once (common for both OTC and regular) - if index == 0 { - // Match found at index 0, perform LPOP to dequeue - data, err := storage.RedisClient.LPop(ctx, redisKey).Result() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "redisKey": redisKey, - "orderIDPrefix": orderIDPrefix, - }).Errorf("failed to dequeue from circular queue when matching rate") - return err - } - - // Enqueue data to the end of the queue - err = storage.RedisClient.RPush(ctx, redisKey, data).Err() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "redisKey": redisKey, - "orderIDPrefix": orderIDPrefix, - }).Errorf("failed to enqueue to circular queue when matching rate") - return err - } - } - - // For OTC orders, skip balance check and assign order to provider - if order.OrderType == "otc" { - if err := s.assignOtcOrder(ctx, order); err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("failed to assign OTC order to provider when matching rate") - - // Add provider to exclude list before continuing to next provider - s.addProviderToExcludeList(ctx, order.ID.String(), order.ProviderID, orderConf.OrderRequestValidityOtc*2) - continue - } - break - } else { - // Regular order - check balance sufficiency - bal, err := s.balanceService.GetProviderFiatBalance(ctx, order.ProviderID, bucketCurrency.Code) - if err != nil { - logger.WithFields(logger.Fields{"Error": fmt.Sprintf("%v", err), "OrderID": order.ID.String(), "ProviderID": order.ProviderID, "Currency": bucketCurrency.Code}).Errorf("failed to get provider fiat balance") - continue - } - if !s.balanceService.CheckBalanceSufficiency(bal, order.Amount.Mul(order.Rate).RoundBank(0)) { - logger.WithFields(logger.Fields{"OrderID": order.ID.String(), "ProviderID": order.ProviderID, "Currency": bucketCurrency.Code, "Amount": order.Amount.String()}).Errorf("insufficient balance") - continue - } - - // Assign the order to the provider and save it to Redis - err = s.sendOrderRequest(ctx, order) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "redisKey": redisKey, - "orderIDPrefix": orderIDPrefix, - }).Errorf("failed to send order request to specific provider when matching rate") - - // Add provider to exclude list before reassigning - s.addProviderToExcludeList(ctx, order.ID.String(), order.ProviderID, orderConf.OrderRequestValidity*4) - - // Note: Balance cleanup is now handled in sendOrderRequest via defer - // Reassign the payment order to another provider - return s.AssignPaymentOrder(ctx, order) - } - - break - } - } - } - - return nil -} diff --git a/services/priority_queue_test.go b/services/priority_queue_test.go deleted file mode 100644 index 4896d26e7..000000000 --- a/services/priority_queue_test.go +++ /dev/null @@ -1,1484 +0,0 @@ -package services - -import ( - "context" - "database/sql" - "encoding/base64" - "errors" - "fmt" - "io" - "log" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "entgo.io/ent/dialect" - entsql "entgo.io/ent/dialect/sql" - "github.com/alicebob/miniredis/v2" - "github.com/jarcoal/httpmock" - _ "github.com/mattn/go-sqlite3" - "github.com/paycrest/aggregator/config" - "github.com/paycrest/aggregator/ent" - "github.com/paycrest/aggregator/ent/fiatcurrency" - "github.com/paycrest/aggregator/ent/paymentorder" - "github.com/paycrest/aggregator/ent/providerbalances" - "github.com/paycrest/aggregator/ent/providerordertoken" - "github.com/paycrest/aggregator/ent/providerprofile" - "github.com/paycrest/aggregator/ent/paymentorderfulfillment" - "github.com/paycrest/aggregator/ent/provisionbucket" - tokenEnt "github.com/paycrest/aggregator/ent/token" - userEnt "github.com/paycrest/aggregator/ent/user" - db "github.com/paycrest/aggregator/storage" - "github.com/paycrest/aggregator/types" - "github.com/paycrest/aggregator/utils" - cryptoUtils "github.com/paycrest/aggregator/utils/crypto" - "github.com/paycrest/aggregator/utils/logger" - "github.com/paycrest/aggregator/utils/test" - tokenUtils "github.com/paycrest/aggregator/utils/token" - "github.com/redis/go-redis/v9" - "github.com/shopspring/decimal" - "github.com/spf13/viper" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var testCtxForPQ = struct { - publicProvider *ent.User - publicProviderProfile *ent.ProviderProfile - publicProviderProfileAPIKey *ent.APIKey - privateProviderProfile *ent.ProviderProfile - currency *ent.FiatCurrency - client types.RPCClient - token *ent.Token - minAmount decimal.Decimal - maxAmount decimal.Decimal - bucket *ent.ProvisionBucket -}{} - -// TestPriorityQueueService extends the original service with test-specific overrides -type TestPriorityQueueService struct { - *PriorityQueueService -} - -// Override sendOrderRequest to mock the provider notification -func (s *TestPriorityQueueService) sendOrderRequest(ctx context.Context, order types.PaymentOrderFields) error { - // Mock successful balance reservation and provider notification - bucketCurrency := order.ProvisionBucket.Edges.Currency - amount := order.Amount.Mul(order.Rate).Round(int32(bucketCurrency.Decimals)) - - // Reserve balance (keep the original logic) - err := s.balanceService.ReserveFiatBalance(ctx, order.ProviderID, bucketCurrency.Code, amount, nil) - if err != nil { - return err - } - - // Mock successful provider notification (skip the actual API call) - logger.WithFields(logger.Fields{ - "ProviderID": order.ProviderID, - "Data": map[string]interface{}{}, // Empty data for test - }).Infof("successfully called provider /new_order endpoint") - - return nil -} - -// Override notifyProvider to skip the database query and prevent deadlock -// This is needed because matchRate calls s.sendOrderRequest where s is *PriorityQueueService, -// which calls the original sendOrderRequest that starts a transaction and then calls notifyProvider. -// The notifyProvider then queries the database, which blocks because the transaction holds the only connection. -func (s *TestPriorityQueueService) notifyProvider(ctx context.Context, orderRequestData map[string]interface{}) error { - // Mock successful provider notification without database query - logger.WithFields(logger.Fields{ - "ProviderID": orderRequestData["providerId"], - "Data": orderRequestData, - }).Infof("successfully called provider /new_order endpoint (mocked)") - return nil -} - -// Override matchRate to use the test's sendOrderRequest instead of the parent's -// This is needed because matchRate is defined on *PriorityQueueService, so when it calls -// s.sendOrderRequest, it calls PriorityQueueService.sendOrderRequest, not TestPriorityQueueService.sendOrderRequest. -// By overriding matchRate, we ensure it uses the test's sendOrderRequest. -func (s *TestPriorityQueueService) matchRate(ctx context.Context, redisKey string, orderIDPrefix string, order types.PaymentOrderFields, excludeList []string) error { - // Duplicate the matchRate logic but use the test's sendOrderRequest - for index := 0; ; index++ { - providerData, err := db.RedisClient.LIndex(ctx, redisKey, int64(index)).Result() - if err != nil { - return err - } - - // Extract the rate from the data (format "providerID:token:network:rate:minAmount:maxAmount") - parts := strings.Split(providerData, ":") - if len(parts) != 6 { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "ProviderData": providerData, - }).Errorf("invalid data format at index %d when matching rate", index) - continue // Skip this entry due to invalid format - } - - order.ProviderID = parts[0] - - // Skip entry if provider has exceeded max retry attempts - if s.countProviderInExcludeList(excludeList, order.ProviderID) >= config.OrderConfig().ProviderMaxRetryAttempts { - continue - } - - // Skip entry if token doesn't match - if parts[1] != order.Token.Symbol { - continue - } - - // Skip entry if network doesn't match - network := order.Token.Edges.Network - if network == nil { - var networkErr error - network, networkErr = order.Token.QueryNetwork().Only(ctx) - if networkErr != nil { - continue - } - } - if parts[2] != network.Identifier { - continue - } - - // Parse rate (amount limits and OTC checks already done by ValidateRate/findSuitableProviderRate) - rate, err := decimal.NewFromString(parts[3]) - if err != nil { - continue - } - - // Fetch ProviderOrderToken only for rate slippage check (network already resolved above) - bucketCurrency := order.ProvisionBucket.Edges.Currency - if bucketCurrency == nil { - bucketCurrency, err = order.ProvisionBucket.QueryCurrency().Only(ctx) - if err != nil { - continue - } - } - - providerToken, err := db.Client.ProviderOrderToken. - Query(). - Where( - providerordertoken.NetworkEQ(network.Identifier), - providerordertoken.HasProviderWith( - providerprofile.IDEQ(order.ProviderID), - providerprofile.HasProviderBalancesWith( - providerbalances.HasFiatCurrencyWith(fiatcurrency.CodeEQ(bucketCurrency.Code)), - providerbalances.IsAvailableEQ(true), - ), - ), - providerordertoken.HasTokenWith(tokenEnt.IDEQ(order.Token.ID)), - providerordertoken.HasCurrencyWith( - fiatcurrency.CodeEQ(bucketCurrency.Code), - ), - providerordertoken.SettlementAddressNEQ(""), - ). - First(ctx) - if err != nil { - continue - } - - // Calculate allowed deviation based on slippage - allowedDeviation := order.Rate.Mul(providerToken.RateSlippage.Div(decimal.NewFromInt(100))) - - if rate.Sub(order.Rate).Abs().LessThanOrEqual(allowedDeviation) { - // Found a match for the rate - handle index pop once (common for both OTC and regular) - if index == 0 { - // Match found at index 0, perform LPOP to dequeue - data, err := db.RedisClient.LPop(ctx, redisKey).Result() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "redisKey": redisKey, - "orderIDPrefix": orderIDPrefix, - }).Errorf("failed to dequeue from circular queue when matching rate") - return err - } - - // Enqueue data to the end of the queue - err = db.RedisClient.RPush(ctx, redisKey, data).Err() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "redisKey": redisKey, - "orderIDPrefix": orderIDPrefix, - }).Errorf("failed to enqueue to circular queue when matching rate") - return err - } - } - - // For OTC orders, skip balance check and assign order to provider - if order.OrderType == "otc" { - if err := s.assignOtcOrder(ctx, order); err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - }).Errorf("failed to assign OTC order to provider when matching rate") - - // Add provider to exclude list before continuing to next provider - s.addProviderToExcludeList(ctx, order.ID.String(), order.ProviderID, 2*time.Hour) - continue - } - break - } else { - // Regular order (or default for any non-OTC order type) - check balance sufficiency - bal, err := s.balanceService.GetProviderFiatBalance(ctx, order.ProviderID, bucketCurrency.Code) - if err != nil { - logger.WithFields(logger.Fields{"Error": fmt.Sprintf("%v", err), "OrderID": order.ID.String(), "ProviderID": order.ProviderID}).Errorf("failed to get provider fiat balance") - continue - } - required := order.Amount.Mul(order.Rate).Round(int32(bucketCurrency.Decimals)) - if !s.balanceService.CheckBalanceSufficiency(bal, required) { - err = fmt.Errorf("insufficient balance") - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "Currency": bucketCurrency.Code, - "Amount": order.Amount.String(), - }).Errorf("failed to check balance sufficiency") - continue - } - - // Assign the order to the provider and save it to Redis - // Use the test's sendOrderRequest instead of the parent's - err = s.sendOrderRequest(ctx, order) - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "OrderID": order.ID.String(), - "ProviderID": order.ProviderID, - "redisKey": redisKey, - "orderIDPrefix": orderIDPrefix, - }).Errorf("failed to send order request to specific provider when matching rate") - - // Add provider to exclude list before reassigning - s.addProviderToExcludeList(ctx, order.ID.String(), order.ProviderID, 2*time.Hour) - - // Note: Balance cleanup is now handled in sendOrderRequest via defer - // Reassign the lock payment order to another provider - return s.AssignPaymentOrder(ctx, order) - } - - break - } - } - } - // This should never be reached in practice, but required by compiler - return nil -} - -// Create a test-specific service instance -func NewTestPriorityQueueService() *TestPriorityQueueService { - return &TestPriorityQueueService{ - PriorityQueueService: NewPriorityQueueService(), - } -} - -func setupForPQ() error { - // Set up test data - testCtxForPQ.maxAmount = decimal.NewFromFloat(10000) - testCtxForPQ.minAmount = decimal.NewFromFloat(1) - - // Create Network first - networkId, err := db.Client.Network. - Create(). - SetIdentifier("localhost"). - SetChainID(int64(56)). // Use BNB Smart Chain to skip webhook creation - SetRPCEndpoint("ws://localhost:8545"). - SetBlockTime(decimal.NewFromFloat(3.0)). - SetFee(decimal.NewFromFloat(0.1)). - SetIsTestnet(true). - OnConflict(). - UpdateNewValues(). - ID(context.Background()) - if err != nil { - return fmt.Errorf("CreateNetwork.priority_queue_test: %w", err) - } - - // Create token directly without blockchain - tokenId, err := db.Client.Token. - Create(). - SetSymbol("TST"). - SetContractAddress("0xd4E96eF8eee8678dBFf4d535E033Ed1a4F7605b7"). - SetDecimals(6). - SetNetworkID(networkId). - SetIsEnabled(true). - SetBaseCurrency("KES"). // Use KES to match the currency below - OnConflict(). - UpdateNewValues(). - ID(context.Background()) - if err != nil { - return fmt.Errorf("CreateToken.priority_queue_test: %w", err) - } - - token, err := db.Client.Token. - Query(). - Where(tokenEnt.IDEQ(tokenId)). - WithNetwork(). - Only(context.Background()) - if err != nil { - return fmt.Errorf("GetToken.priority_queue_test: %w", err) - } - testCtxForPQ.token = token - - user, err := test.CreateTestUser(map[string]interface{}{ - "scope": "provider", - "email": "providerjohndoe@test.com", - }) - if err != nil { - return err - } - testCtxForPQ.publicProvider = user - - currency, err := test.CreateTestFiatCurrency(map[string]interface{}{ - "code": "KES", - "short_name": "Shilling", - "decimals": 2, - "symbol": "KSh", - "name": "Kenyan Shilling", - "market_rate": 550.0, - }) - if err != nil { - return err - } - testCtxForPQ.currency = currency - - publicProviderProfile, err := test.CreateTestProviderProfile(map[string]interface{}{ - "user_id": testCtxForPQ.publicProvider.ID, - "currency_id": currency.ID, - "host_identifier": "https://example2.com", - }) - if err != nil { - return err - } - apiKeyService := NewAPIKeyService() - apiKey, _, err := apiKeyService.GenerateAPIKey( - context.Background(), - nil, - nil, - publicProviderProfile, - ) - if err != nil { - return err - } - testCtxForPQ.publicProviderProfileAPIKey = apiKey - _, err = test.AddProviderOrderTokenToProvider( - map[string]interface{}{ - "fixed_buy_rate": decimal.NewFromFloat(100), - "fixed_sell_rate": decimal.NewFromFloat(100), - "max_order_amount": decimal.NewFromFloat(1000), - "min_order_amount": decimal.NewFromFloat(1.0), - "provider": publicProviderProfile, - "currency_id": currency.ID, - "network": token.Edges.Network.Identifier, - "token_id": token.ID, - }, - ) - if err != nil { - return err - } - testCtxForPQ.publicProviderProfile = publicProviderProfile - - // Set provider to active and user to KYB approved (required for GetProvisionBuckets) - _, err = db.Client.ProviderProfile. - Update(). - Where(providerprofile.IDEQ(publicProviderProfile.ID)). - SetIsActive(true). - Save(context.Background()) - if err != nil { - return fmt.Errorf("UpdateProviderProfile.IsActive: %w", err) - } - - _, err = db.Client.User. - Update(). - Where(userEnt.IDEQ(testCtxForPQ.publicProvider.ID)). - SetKybVerificationStatus(userEnt.KybVerificationStatusApproved). - Save(context.Background()) - if err != nil { - return fmt.Errorf("UpdateUser.KybVerificationStatus: %w", err) - } - - _, err = db.Client.ProviderBalances.Update(). - Where(providerbalances.HasProviderWith(providerprofile.IDEQ(publicProviderProfile.ID))). - Where(providerbalances.HasFiatCurrencyWith(fiatcurrency.IDEQ(currency.ID))). - SetAvailableBalance(decimal.NewFromFloat(100000)). - SetTotalBalance(decimal.NewFromFloat(100000)). - SetIsAvailable(true). - Save(context.Background()) - if err != nil { - return fmt.Errorf("UpdateProviderBalances.publicProvider: %w", err) - } - - bucket, err := test.CreateTestProvisionBucket(map[string]interface{}{ - "provider_id": publicProviderProfile.ID, - "min_amount": decimal.NewFromFloat(1), - "max_amount": decimal.NewFromFloat(10000.0), - "currency_id": currency.ID, - }) - if err != nil { - return err - } - testCtxForPQ.bucket = bucket - - privateProvider, err := test.CreateTestUser(map[string]interface{}{ - "scope": "provider", - "email": "private@test.com", - }) - if err != nil { - return err - } - - privateProviderProfile, err := test.CreateTestProviderProfile(map[string]interface{}{ - "currency_id": currency.ID, - "visibility_mode": "private", - "user_id": privateProvider.ID, - }) - if err != nil { - return err - } - testCtxForPQ.privateProviderProfile = privateProviderProfile - - _, err = db.Client.ProviderBalances.Update(). - Where(providerbalances.HasProviderWith(providerprofile.IDEQ(privateProviderProfile.ID))). - Where(providerbalances.HasFiatCurrencyWith(fiatcurrency.IDEQ(currency.ID))). - SetAvailableBalance(decimal.NewFromFloat(100000)). - SetTotalBalance(decimal.NewFromFloat(100000)). - Save(context.Background()) - if err != nil { - return fmt.Errorf("UpdateProviderBalances.privateProvider: %w", err) - } - - _, err = test.CreateTestProvisionBucket(map[string]interface{}{ - "provider_id": privateProviderProfile.ID, - "min_amount": testCtxForPQ.minAmount, - "max_amount": testCtxForPQ.maxAmount, - "currency_id": currency.ID, - }) - if err != nil { - return err - } - - // Set up payment order - _, err = test.CreateTestPaymentOrder(nil, map[string]interface{}{ - "provider": privateProviderProfile, - "token_id": testCtxForPQ.token.ID, - "gateway_id": "order-12345", - }) - if err != nil { - return err - } - _, err = test.CreateTestPaymentOrder(nil, map[string]interface{}{ - "provider": publicProviderProfile, - "token_id": testCtxForPQ.token.ID, - }) - if err != nil { - return err - } - - return nil -} - -func TestPriorityQueueTest(t *testing.T) { - // Set up test database client with shared in-memory schema - // Use 2 connections to allow transaction and query to run concurrently (prevents deadlock) - dbConn, err := sql.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1&_busy_timeout=5000") - if err != nil { - t.Fatalf("Failed to open sqlite DB: %v", err) - } - dbConn.SetMaxOpenConns(2) - defer dbConn.Close() - - drv := entsql.OpenDB(dialect.SQLite, dbConn) - client := ent.NewClient(ent.Driver(drv)) - defer client.Close() - - // Set client first so all operations use the same client - db.Client = client - - // Create schema to ensure all tables exist and are ready - if err := client.Schema.Create(context.Background()); err != nil { - t.Fatalf("Failed to create schema: %v", err) - } - - // Verify db.Client is set correctly before setup - if db.Client != client { - t.Fatalf("db.Client is not set to the test client - this will cause schema issues") - } - - // Set up in-memory Redis - mr, err := miniredis.Run() - assert.NoError(t, err) - defer mr.Close() - - redisClient := redis.NewClient(&redis.Options{ - Addr: mr.Addr(), - }) - defer redisClient.Close() - - db.RedisClient = redisClient - - // Setup test data - err = setupForPQ() - assert.NoError(t, err) - - // Start a local HTTP server to mock provider endpoints and avoid real network calls - mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, _ = w.Write([]byte(`{"status":"success","message":"ok"}`)) - })) - defer mockServer.Close() - - // Point all provider host identifiers to the mock server - _, err = db.Client.ProviderProfile.Update().SetHostIdentifier(mockServer.URL).Save(context.Background()) - assert.NoError(t, err) - - service := NewTestPriorityQueueService() - t.Run("TestGetProvisionBuckets", func(t *testing.T) { - buckets, err := service.GetProvisionBuckets(context.Background()) - assert.NoError(t, err) - assert.Greater(t, len(buckets), 0) - }) - - t.Run("TestCreatePriorityQueueForBucket", func(t *testing.T) { - // Ensure fallback is unset so the test's provider is included in the queue - oldFallback := viper.GetString("FALLBACK_PROVIDER_ID") - viper.Set("FALLBACK_PROVIDER_ID", "") - defer viper.Set("FALLBACK_PROVIDER_ID", oldFallback) - - ctx := context.Background() - bucket, err := test.CreateTestProvisionBucket(map[string]interface{}{ - "provider_id": testCtxForPQ.publicProviderProfile.ID, - "min_amount": testCtxForPQ.minAmount, - "max_amount": testCtxForPQ.maxAmount, - "currency_id": testCtxForPQ.currency.ID, - }) - assert.NoError(t, err) - - _bucket, err := db.Client.ProvisionBucket. - Query(). - Where(provisionbucket.IDEQ(bucket.ID)). - WithCurrency(). - WithProviderProfiles(). - Only(ctx) - assert.NoError(t, err) - - service.CreatePriorityQueueForBucket(ctx, _bucket) - - redisKey := fmt.Sprintf("bucket_%s_%s_%s_sell", _bucket.Edges.Currency.Code, testCtxForPQ.minAmount, testCtxForPQ.maxAmount) - - data, err := db.RedisClient.LRange(ctx, redisKey, 0, -1).Result() - assert.NoError(t, err) - assert.Equal(t, 1, len(data)) - assert.Contains(t, data[0], testCtxForPQ.publicProviderProfile.ID) - - // Clean up: Delete the bucket created in this test to avoid conflicts with TestProcessBucketQueues - // (both buckets would use the same Redis key) - _, err = db.Client.ProvisionBucket.Delete().Where(provisionbucket.IDEQ(bucket.ID)).Exec(ctx) - assert.NoError(t, err) - }) - - t.Run("TestProcessBucketQueues", func(t *testing.T) { - // Ensure fallback is unset so the test's provider is included in the queue (not skipped or sanitized out) - oldFallback := viper.GetString("FALLBACK_PROVIDER_ID") - viper.Set("FALLBACK_PROVIDER_ID", "") - defer viper.Set("FALLBACK_PROVIDER_ID", oldFallback) - - ctx := context.Background() - redisKey := fmt.Sprintf("bucket_%s_%s_%s", testCtxForPQ.currency.Code, testCtxForPQ.minAmount, testCtxForPQ.maxAmount) - redisKeySell := redisKey + "_sell" - // Clear Redis keys (buy and sell) and aux keys so ProcessBucketQueues starts from a clean state (no leftover from TestCreatePriorityQueueForBucket or concurrent goroutines). - for _, k := range []string{redisKey, redisKey + "_temp", redisKey + "_prev", redisKeySell, redisKeySell + "_temp", redisKeySell + "_prev"} { - _ = db.RedisClient.Del(ctx, k).Err() - } - // Only one bucket should use this redis key so the queue has deterministic length (1 provider, 1 token). - // Delete any other provision bucket with same currency+min+max so we don't race with multiple CreatePriorityQueueForBucket goroutines. - _, err = db.Client.ProvisionBucket.Delete(). - Where( - provisionbucket.MinAmountEQ(testCtxForPQ.minAmount), - provisionbucket.MaxAmountEQ(testCtxForPQ.maxAmount), - provisionbucket.HasCurrencyWith(fiatcurrency.IDEQ(testCtxForPQ.currency.ID)), - provisionbucket.IDNEQ(testCtxForPQ.bucket.ID), - ). - Exec(ctx) - assert.NoError(t, err) - - err = service.ProcessBucketQueues() - assert.NoError(t, err) - // buildQueueForSide uses key with _sell suffix for the sell queue - redisKey = fmt.Sprintf("bucket_%s_%s_%s_sell", testCtxForPQ.currency.Code, testCtxForPQ.minAmount, testCtxForPQ.maxAmount) - - // ProcessBucketQueues launches goroutines; wait until the queue is populated. - assert.Eventually(t, func() bool { - data, err := db.RedisClient.LRange(context.Background(), redisKey, 0, -1).Result() - return err == nil && len(data) == 1 - }, 2*time.Second, 50*time.Millisecond) - - data, err := db.RedisClient.LRange(context.Background(), redisKey, 0, -1).Result() - assert.NoError(t, err) - // ProcessBucketQueues rebuilds queues from GetProvisionBuckets which filters providers. - // The provider should meet all criteria (active, KYB approved, public, has balance). - assert.Equal(t, 1, len(data)) - }) - - t.Run("TestAssignPaymentOrder", func(t *testing.T) { - ctx := context.Background() - - bucket, err := test.CreateTestProvisionBucket(map[string]interface{}{ - "provider_id": testCtxForPQ.publicProviderProfile.ID, - "min_amount": testCtxForPQ.minAmount, - "max_amount": testCtxForPQ.maxAmount, - "currency_id": testCtxForPQ.currency.ID, - }) - require.NoError(t, err) - require.NotNil(t, bucket, "CreateTestProvisionBucket returned nil") - - _bucket, err := db.Client.ProvisionBucket. - Query(). - Where(provisionbucket.IDEQ(bucket.ID)). - WithCurrency(). - WithProviderProfiles(). - Only(ctx) - require.NoError(t, err) - require.NotNil(t, _bucket) - - _order, err := test.CreateTestPaymentOrder(nil, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, - "rate": 100.0, - "token_id": testCtxForPQ.token.ID, - "gateway_id": "order-1", - }) - require.NoError(t, err) - require.NotNil(t, _order) - - _, err = test.AddProvisionBucketToPaymentOrder(_order, bucket.ID) - require.NoError(t, err) - - order, err := db.Client.PaymentOrder. - Query(). - Where(paymentorder.IDEQ(_order.ID)). - WithProvisionBucket(func(pb *ent.ProvisionBucketQuery) { - pb.WithCurrency() - }). - WithToken(). - Only(ctx) - require.NoError(t, err) - require.NotNil(t, order) - - service.CreatePriorityQueueForBucket(ctx, _bucket) - - err = service.AssignPaymentOrder(ctx, types.PaymentOrderFields{ - ID: order.ID, - Token: testCtxForPQ.token, - GatewayID: order.GatewayID, - Amount: order.Amount, - Rate: order.Rate, - BlockNumber: order.BlockNumber, - Institution: order.Institution, - AccountIdentifier: order.AccountIdentifier, - AccountName: order.AccountName, - Memo: order.Memo, - ProvisionBucket: order.Edges.ProvisionBucket, - }) - assert.NoError(t, err) - }) - - t.Run("TestAssignPaymentOrderReturnsErrorWhenQueueEmpty", func(t *testing.T) { - ctx := context.Background() - - bucket, err := test.CreateTestProvisionBucket(map[string]interface{}{ - "provider_id": testCtxForPQ.publicProviderProfile.ID, - "min_amount": testCtxForPQ.minAmount, - "max_amount": testCtxForPQ.maxAmount, - "currency_id": testCtxForPQ.currency.ID, - }) - assert.NoError(t, err) - - _order, err := test.CreateTestPaymentOrder(nil, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, - "rate": 100.0, - "token_id": testCtxForPQ.token.ID, - "gateway_id": "order-empty-queue", - }) - assert.NoError(t, err) - _, err = test.AddProvisionBucketToPaymentOrder(_order, bucket.ID) - assert.NoError(t, err) - - order, err := db.Client.PaymentOrder. - Query(). - Where(paymentorder.IDEQ(_order.ID)). - WithProvisionBucket(func(pb *ent.ProvisionBucketQuery) { - pb.WithCurrency() - }). - WithToken(). - Only(ctx) - assert.NoError(t, err) - - // Ensure current and prev queues are empty for this bucket (side-suffixed keys used by AssignPaymentOrder) - redisKey := fmt.Sprintf("bucket_%s_%s_%s", testCtxForPQ.currency.Code, bucket.MinAmount, bucket.MaxAmount) - for _, suffix := range []string{"", "_sell", "_sell_prev", "_sell_temp", "_buy", "_buy_prev", "_buy_temp", "_prev"} { - db.RedisClient.Del(ctx, redisKey+suffix) - } - - err = service.AssignPaymentOrder(ctx, types.PaymentOrderFields{ - ID: order.ID, - Token: testCtxForPQ.token, - GatewayID: order.GatewayID, - Amount: order.Amount, - Rate: order.Rate, - BlockNumber: order.BlockNumber, - Institution: order.Institution, - AccountIdentifier: order.AccountIdentifier, - AccountName: order.AccountName, - Memo: order.Memo, - ProvisionBucket: order.Edges.ProvisionBucket, - }) - assert.Error(t, err, "AssignPaymentOrder should return error when no providers are in the queue") - assert.Contains(t, err.Error(), "no provider matched for order") - }) - - t.Run("TestGetProviderRate", func(t *testing.T) { - // Use the provider profile directly - it was created with db.Client which is the same as client - // The relationship queries should work as long as db.Client is set correctly - rate, err := service.GetProviderRate(context.Background(), testCtxForPQ.publicProviderProfile, testCtxForPQ.token.Symbol, testCtxForPQ.currency.Code, RateSideSell) - assert.NoError(t, err) - _rate, ok := rate.Float64() - assert.True(t, ok) - assert.Equal(t, _rate, float64(100)) - }) - - t.Run("TestSendOrderRequest", func(t *testing.T) { - bucket, err := test.CreateTestProvisionBucket(map[string]interface{}{ - "provider_id": testCtxForPQ.privateProviderProfile.ID, - "min_amount": testCtxForPQ.minAmount, - "max_amount": testCtxForPQ.maxAmount, - "currency_id": testCtxForPQ.currency.ID, - }) - assert.NoError(t, err) - _order, err := test.CreateTestPaymentOrder(nil, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, - "token_id": int(testCtxForPQ.token.ID), - "gateway_id": "order-1234", - }) - if err != nil { - t.Logf("Failed to create lock payment order: %v", err) - } - assert.NoError(t, err) - if _order == nil { - t.Fatal("LockPaymentOrder is nil - creation failed") - } - - _, err = test.AddProvisionBucketToPaymentOrder(_order, bucket.ID) - assert.NoError(t, err) - - _, err = db.RedisClient.RPush(context.Background(), fmt.Sprintf("order_exclude_list_%s", _order.ID), testCtxForPQ.publicProviderProfile.ID).Result() - assert.NoError(t, err) - - order, err := db.Client.PaymentOrder. - Query(). - Where(paymentorder.IDEQ(_order.ID)). - WithProvisionBucket(func(pb *ent.ProvisionBucketQuery) { - pb.WithCurrency() - }). - WithToken(). - Only(context.Background()) - - assert.NoError(t, err) - - // Setup httpmock for sendOrderRequest - httpmock.Activate() - defer httpmock.DeactivateAndReset() - - httpmock.RegisterResponder("POST", testCtxForPQ.publicProviderProfile.HostIdentifier+"/new_order", - func(req *http.Request) (*http.Response, error) { - return httpmock.NewJsonResponse(200, map[string]interface{}{ - "status": "success", - "message": "Order processed successfully", - }) - }) - - err = service.sendOrderRequest(context.Background(), types.PaymentOrderFields{ - ID: order.ID, - ProviderID: testCtxForPQ.publicProviderProfile.ID, - Token: testCtxForPQ.token, - GatewayID: order.GatewayID, - Amount: order.Amount, - Rate: order.Rate, - BlockNumber: order.BlockNumber, - Institution: order.Institution, - AccountIdentifier: order.AccountIdentifier, - AccountName: order.AccountName, - Memo: order.Memo, - ProvisionBucket: order.Edges.ProvisionBucket, - }) - assert.NoError(t, err) - - t.Run("TestNotifyProvider", func(t *testing.T) { - - // setup httpmock - httpmock.Activate() - defer httpmock.Deactivate() - - httpmock.RegisterResponder("POST", testCtxForPQ.publicProviderProfile.HostIdentifier+"/new_order", - func(r *http.Request) (*http.Response, error) { - bytes, err := io.ReadAll(r.Body) - if err != nil { - log.Fatal(err) - } - // Compute HMAC - decodedSecret, err := base64.StdEncoding.DecodeString(testCtxForPQ.publicProviderProfileAPIKey.Secret) - assert.NoError(t, err) - decryptedSecret, err := cryptoUtils.DecryptPlain(decodedSecret) - assert.NoError(t, err) - signature := tokenUtils.GenerateHMACSignature(map[string]interface{}{ - "data": "test", - }, string(decryptedSecret)) - assert.Equal(t, r.Header.Get("X-Request-Signature"), signature) - if strings.Contains(string(bytes), "data") && strings.Contains(string(bytes), "test") { - resp := httpmock.NewBytesResponse(200, nil) - return resp, nil - } else { - return nil, nil - } - }, - ) - err := service.notifyProvider(context.Background(), map[string]interface{}{ - "providerId": testCtxForPQ.publicProviderProfile.ID, - "data": "test", - }) - assert.NoError(t, err) - }) - }) - - t.Run("TestCountProviderInExcludeList", func(t *testing.T) { - tests := []struct { - name string - excludeList []string - providerID string - expected int - }{ - { - name: "Provider not in exclude list", - excludeList: []string{"provider1", "provider2"}, - providerID: "provider3", - expected: 0, - }, - { - name: "Provider appears twice", - excludeList: []string{"provider1", "provider2", "provider1"}, - providerID: "provider1", - expected: 2, - }, - { - name: "Provider appears multiple times", - excludeList: []string{"provider1", "provider2", "provider1", "provider1", "provider3"}, - providerID: "provider1", - expected: 3, - }, - { - name: "Empty exclude list", - excludeList: []string{}, - providerID: "provider1", - expected: 0, - }, - { - name: "Provider appears at max retry attempts", - excludeList: []string{"provider1", "provider1", "provider1"}, - providerID: "provider1", - expected: 3, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := service.countProviderInExcludeList(tt.excludeList, tt.providerID) - assert.Equal(t, tt.expected, result, "Count should match expected value") - }) - } - }) - - t.Run("TestProviderMaxRetryAttemptsConfigValidation", func(t *testing.T) { - // Save original value - originalValue := viper.GetInt("PROVIDER_MAX_RETRY_ATTEMPTS") - - // Test cases: invalid values should be corrected to 3 - testCases := []struct { - name string - setValue int - expected int - }{ - { - name: "Zero value should be corrected to 3", - setValue: 0, - expected: 3, - }, - { - name: "Negative value should be corrected to 3", - setValue: -1, - expected: 3, - }, - { - name: "Large negative value should be corrected to 3", - setValue: -100, - expected: 3, - }, - { - name: "Valid positive value should be preserved", - setValue: 5, - expected: 5, - }, - { - name: "Value of 1 should be preserved", - setValue: 1, - expected: 1, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - // Set the test value - viper.Set("PROVIDER_MAX_RETRY_ATTEMPTS", tc.setValue) - - // Get config (this triggers validation) - orderConfig := config.OrderConfig() - - // Verify the value - assert.Equal(t, tc.expected, orderConfig.ProviderMaxRetryAttempts, - "ProviderMaxRetryAttempts should be corrected to expected value") - }) - } - - // Restore original value - viper.Set("PROVIDER_MAX_RETRY_ATTEMPTS", originalValue) - }) - - t.Run("TestProviderRetryLogic", func(t *testing.T) { - ctx := context.Background() - - // Set max retry attempts to 3 for testing - originalValue := viper.GetInt("PROVIDER_MAX_RETRY_ATTEMPTS") - viper.Set("PROVIDER_MAX_RETRY_ATTEMPTS", 3) - defer viper.Set("PROVIDER_MAX_RETRY_ATTEMPTS", originalValue) - - t.Run("Provider can retry up to max attempts", func(t *testing.T) { - orderID := testCtxForPQ.publicProviderProfile.ID - excludeListKey := fmt.Sprintf("order_exclude_list_%s", "test-order-id") - - // Test that provider is not excluded with 0 failures - excludeList, _ := db.RedisClient.LRange(ctx, excludeListKey, 0, -1).Result() - count := service.countProviderInExcludeList(excludeList, orderID) - assert.Equal(t, 0, count, "Provider should have 0 failures initially") - - // Add provider to exclude list once (first failure) - _, err := db.RedisClient.RPush(ctx, excludeListKey, orderID).Result() - assert.NoError(t, err) - - excludeList, _ = db.RedisClient.LRange(ctx, excludeListKey, 0, -1).Result() - count = service.countProviderInExcludeList(excludeList, orderID) - assert.Equal(t, 1, count, "Provider should have 1 failure") - assert.True(t, count < 3, "Provider should still be eligible (count < max)") - - // Add provider to exclude list again (second failure) - _, err = db.RedisClient.RPush(ctx, excludeListKey, orderID).Result() - assert.NoError(t, err) - - excludeList, _ = db.RedisClient.LRange(ctx, excludeListKey, 0, -1).Result() - count = service.countProviderInExcludeList(excludeList, orderID) - assert.Equal(t, 2, count, "Provider should have 2 failures") - assert.True(t, count < 3, "Provider should still be eligible (count < max)") - - // Add provider to exclude list third time (third failure) - _, err = db.RedisClient.RPush(ctx, excludeListKey, orderID).Result() - assert.NoError(t, err) - - excludeList, _ = db.RedisClient.LRange(ctx, excludeListKey, 0, -1).Result() - count = service.countProviderInExcludeList(excludeList, orderID) - assert.Equal(t, 3, count, "Provider should have 3 failures") - assert.True(t, count >= 3, "Provider should now be excluded (count >= max)") - - // Add provider to exclude list fourth time (fourth failure) - _, err = db.RedisClient.RPush(ctx, excludeListKey, orderID).Result() - assert.NoError(t, err) - - excludeList, _ = db.RedisClient.LRange(ctx, excludeListKey, 0, -1).Result() - count = service.countProviderInExcludeList(excludeList, orderID) - assert.Equal(t, 4, count, "Provider should have 4 failures") - assert.True(t, count >= 3, "Provider should still be excluded (count >= max)") - }) - - t.Run("Multiple providers in exclude list are counted independently", func(t *testing.T) { - provider1ID := testCtxForPQ.publicProviderProfile.ID - provider2ID := "provider-2-id" - excludeListKey := fmt.Sprintf("order_exclude_list_%s", "test-order-id-2") - - // Add provider1 twice and provider2 once - _, err := db.RedisClient.RPush(ctx, excludeListKey, provider1ID).Result() - assert.NoError(t, err) - _, err = db.RedisClient.RPush(ctx, excludeListKey, provider1ID).Result() - assert.NoError(t, err) - _, err = db.RedisClient.RPush(ctx, excludeListKey, provider2ID).Result() - assert.NoError(t, err) - - excludeList, _ := db.RedisClient.LRange(ctx, excludeListKey, 0, -1).Result() - - // Verify counts are independent - count1 := service.countProviderInExcludeList(excludeList, provider1ID) - count2 := service.countProviderInExcludeList(excludeList, provider2ID) - - assert.Equal(t, 2, count1, "Provider1 should have 2 failures") - assert.Equal(t, 1, count2, "Provider2 should have 1 failure") - }) - }) - - t.Run("TestTryFallbackAssignment", func(t *testing.T) { - ctx := context.Background() - - t.Run("FallbackNotConfigured", func(t *testing.T) { - old := viper.GetString("FALLBACK_PROVIDER_ID") - viper.Set("FALLBACK_PROVIDER_ID", "") - defer viper.Set("FALLBACK_PROVIDER_ID", old) - - _order, err := test.CreateTestPaymentOrder(testCtxForPQ.token, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, "rate": 100.0, "gateway_id": "gw-fb-none", - }) - assert.NoError(t, err) - _, err = _order.Update().ClearProvider().Save(ctx) - assert.NoError(t, err) - _, err = test.AddProvisionBucketToPaymentOrder(_order, testCtxForPQ.bucket.ID) - assert.NoError(t, err) - - order, err := db.Client.PaymentOrder.Get(ctx, _order.ID) - assert.NoError(t, err) - - err = service.TryFallbackAssignment(ctx, order) - assert.Error(t, err) - assert.Contains(t, err.Error(), "fallback provider not configured") - }) - - t.Run("OTCExcluded", func(t *testing.T) { - old := viper.GetString("FALLBACK_PROVIDER_ID") - viper.Set("FALLBACK_PROVIDER_ID", testCtxForPQ.publicProviderProfile.ID) - defer viper.Set("FALLBACK_PROVIDER_ID", old) - - _order, err := test.CreateTestPaymentOrder(testCtxForPQ.token, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, "rate": 100.0, "gateway_id": "gw-fb-otc", - }) - assert.NoError(t, err) - _, err = _order.Update().ClearProvider().SetOrderType(paymentorder.OrderTypeOtc).Save(ctx) - assert.NoError(t, err) - _, err = test.AddProvisionBucketToPaymentOrder(_order, testCtxForPQ.bucket.ID) - assert.NoError(t, err) - - order, err := db.Client.PaymentOrder.Get(ctx, _order.ID) - assert.NoError(t, err) - - err = service.TryFallbackAssignment(ctx, order) - assert.Error(t, err) - assert.Contains(t, err.Error(), "fallback is only for regular orders") - }) - - t.Run("OrderRequestExists", func(t *testing.T) { - old := viper.GetString("FALLBACK_PROVIDER_ID") - viper.Set("FALLBACK_PROVIDER_ID", testCtxForPQ.publicProviderProfile.ID) - defer viper.Set("FALLBACK_PROVIDER_ID", old) - - _order, err := test.CreateTestPaymentOrder(testCtxForPQ.token, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, "rate": 100.0, "gateway_id": "gw-fb-redis", - }) - assert.NoError(t, err) - _, err = _order.Update().ClearProvider().Save(ctx) - assert.NoError(t, err) - _, err = test.AddProvisionBucketToPaymentOrder(_order, testCtxForPQ.bucket.ID) - assert.NoError(t, err) - - orderKey := fmt.Sprintf("order_request_%s", _order.ID) - _, err = db.RedisClient.HSet(ctx, orderKey, "providerId", testCtxForPQ.publicProviderProfile.ID).Result() - assert.NoError(t, err) - defer db.RedisClient.Del(ctx, orderKey) - - order, err := db.Client.PaymentOrder.Get(ctx, _order.ID) - assert.NoError(t, err) - - err = service.TryFallbackAssignment(ctx, order) - assert.Error(t, err) - assert.Contains(t, err.Error(), "already has an active order_request") - }) - - t.Run("FallbackAlreadyTried", func(t *testing.T) { - old := viper.GetString("FALLBACK_PROVIDER_ID") - viper.Set("FALLBACK_PROVIDER_ID", testCtxForPQ.publicProviderProfile.ID) - defer viper.Set("FALLBACK_PROVIDER_ID", old) - - _order, err := test.CreateTestPaymentOrder(testCtxForPQ.token, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, "rate": 100.0, "gateway_id": "gw-fb-tried", - }) - assert.NoError(t, err) - _, err = _order.Update().ClearProvider().Save(ctx) - assert.NoError(t, err) - _, err = test.AddProvisionBucketToPaymentOrder(_order, testCtxForPQ.bucket.ID) - assert.NoError(t, err) - _, err = _order.Update().SetFallbackTriedAt(time.Now()).Save(ctx) - assert.NoError(t, err) - - order, err := db.Client.PaymentOrder.Get(ctx, _order.ID) - assert.NoError(t, err) - - err = service.TryFallbackAssignment(ctx, order) - assert.Error(t, err) - assert.Contains(t, err.Error(), "already had fallback assignment tried") - }) - - t.Run("Success", func(t *testing.T) { - old := viper.GetString("FALLBACK_PROVIDER_ID") - viper.Set("FALLBACK_PROVIDER_ID", testCtxForPQ.publicProviderProfile.ID) - defer viper.Set("FALLBACK_PROVIDER_ID", old) - - _order, err := test.CreateTestPaymentOrder(testCtxForPQ.token, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, "rate": 100.0, "gateway_id": "gw-fb-success", - }) - assert.NoError(t, err) - _, err = _order.Update().ClearProvider().Save(ctx) - assert.NoError(t, err) - _, err = test.AddProvisionBucketToPaymentOrder(_order, testCtxForPQ.bucket.ID) - assert.NoError(t, err) - - order, err := db.Client.PaymentOrder. - Query(). - Where(paymentorder.IDEQ(_order.ID)). - WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() }). - WithProvisionBucket(func(pb *ent.ProvisionBucketQuery) { pb.WithCurrency() }). - Only(ctx) - assert.NoError(t, err) - - err = service.TryFallbackAssignment(ctx, order) - assert.NoError(t, err) - - // Idempotency: FallbackTriedAt should be set - updated, err := db.Client.PaymentOrder.Get(ctx, _order.ID) - assert.NoError(t, err) - assert.False(t, updated.FallbackTriedAt.IsZero(), "FallbackTriedAt should be set after success") - }) - - // RateOnlyMatchesFallback: order rate (1390) matches no provider in the queue (1376, tight slippage) - // but is within fallback provider's slippage (1388, 2%) → fallback should assign before refund. - t.Run("RateOnlyMatchesFallback", func(t *testing.T) { - oldFallback := viper.GetString("FALLBACK_PROVIDER_ID") - viper.Set("FALLBACK_PROVIDER_ID", testCtxForPQ.privateProviderProfile.ID) - defer viper.Set("FALLBACK_PROVIDER_ID", oldFallback) - - tokenWithNet, err := db.Client.Token.Query().Where(tokenEnt.IDEQ(testCtxForPQ.token.ID)).WithNetwork().Only(ctx) - assert.NoError(t, err) - networkID := tokenWithNet.Edges.Network.Identifier - - // Queue provider (public): rate 1376, slippage 0.5% → order 1390 is outside (|1390-1376| > 1390*0.005) - publicToken, err := db.Client.ProviderOrderToken. - Query(). - Where( - providerordertoken.HasProviderWith(providerprofile.IDEQ(testCtxForPQ.publicProviderProfile.ID)), - providerordertoken.HasTokenWith(tokenEnt.IDEQ(testCtxForPQ.token.ID)), - providerordertoken.HasCurrencyWith(fiatcurrency.IDEQ(testCtxForPQ.currency.ID)), - providerordertoken.NetworkEQ(networkID), - ). - Only(ctx) - assert.NoError(t, err) - _, err = db.Client.ProviderOrderToken.UpdateOneID(publicToken.ID). - SetFixedSellRate(decimal.NewFromFloat(1376)). - SetRateSlippage(decimal.NewFromFloat(0.5)). - Save(ctx) - assert.NoError(t, err) - - // Fallback provider (private): rate 1388, slippage 2% → order 1390 is within (|1390-1388| <= 1390*0.02) - _, err = test.AddProviderOrderTokenToProvider(map[string]interface{}{ - "provider": testCtxForPQ.privateProviderProfile, - "token_id": int(testCtxForPQ.token.ID), - "currency_id": testCtxForPQ.currency.ID, - "network": networkID, - "fixed_buy_rate": decimal.NewFromFloat(1388), - "fixed_sell_rate": decimal.NewFromFloat(1388), - "floating_buy_delta": decimal.Zero, - "floating_sell_delta": decimal.Zero, - "max_order_amount": decimal.NewFromFloat(10000), - "min_order_amount": decimal.NewFromFloat(1), - "max_order_amount_otc": decimal.NewFromFloat(10000), - "min_order_amount_otc": decimal.NewFromFloat(100), - "settlement_address": "0xfallback123456789012345678901234567890", - }) - assert.NoError(t, err) - fallbackToken, err := db.Client.ProviderOrderToken. - Query(). - Where( - providerordertoken.HasProviderWith(providerprofile.IDEQ(testCtxForPQ.privateProviderProfile.ID)), - providerordertoken.HasTokenWith(tokenEnt.IDEQ(testCtxForPQ.token.ID)), - providerordertoken.HasCurrencyWith(fiatcurrency.IDEQ(testCtxForPQ.currency.ID)), - providerordertoken.NetworkEQ(networkID), - ). - Only(ctx) - assert.NoError(t, err) - _, err = db.Client.ProviderOrderToken.UpdateOneID(fallbackToken.ID). - SetRateSlippage(decimal.NewFromFloat(2)). - Save(ctx) - assert.NoError(t, err) - - // Fallback provider needs sufficient fiat balance (order amount * rate; default amount 100.5 * 1390 > 100k) - _, err = db.Client.ProviderBalances.Update(). - Where(providerbalances.HasProviderWith(providerprofile.IDEQ(testCtxForPQ.privateProviderProfile.ID))). - Where(providerbalances.HasFiatCurrencyWith(fiatcurrency.IDEQ(testCtxForPQ.currency.ID))). - SetAvailableBalance(decimal.NewFromFloat(500000)). - SetTotalBalance(decimal.NewFromFloat(500000)). - SetIsAvailable(true). - Save(ctx) - assert.NoError(t, err) - - // Fallback provider needs an API key for sendOrderRequest (notifyProvider) to succeed - apiKeySvc := NewAPIKeyService() - _, _, err = apiKeySvc.GenerateAPIKey(ctx, nil, nil, testCtxForPQ.privateProviderProfile) - assert.NoError(t, err) - - // Clear any existing queue so the next build uses rate 1376 (not leftover from other tests) - redisKey := fmt.Sprintf("bucket_%s_%s_%s", testCtxForPQ.currency.Code, testCtxForPQ.bucket.MinAmount, testCtxForPQ.bucket.MaxAmount) - _ = db.RedisClient.Del(ctx, redisKey).Err() - - // Build queue so it contains public provider at 1376 (order 1390 will not match) - bucketForQueue, err := db.Client.ProvisionBucket. - Query(). - Where(provisionbucket.IDEQ(testCtxForPQ.bucket.ID)). - WithCurrency(). - WithProviderProfiles(). - Only(ctx) - assert.NoError(t, err) - service.CreatePriorityQueueForBucket(ctx, bucketForQueue) - - // Order with rate 1390: no provider in queue can fulfill; AssignPaymentOrder tries fallback and should succeed - _order, err := test.CreateTestPaymentOrder(testCtxForPQ.token, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, "rate": 1390.0, "gateway_id": "gw-fb-rate-only", - }) - assert.NoError(t, err) - _, err = _order.Update().ClearProvider().Save(ctx) - assert.NoError(t, err) - _, err = test.AddProvisionBucketToPaymentOrder(_order, testCtxForPQ.bucket.ID) - assert.NoError(t, err) - - bucketWithCurrency, err := db.Client.ProvisionBucket. - Query(). - Where(provisionbucket.IDEQ(testCtxForPQ.bucket.ID)). - WithCurrency(). - Only(ctx) - assert.NoError(t, err) - orderFields := types.PaymentOrderFields{ - ID: _order.ID, - OrderType: "regular", - Token: testCtxForPQ.token, - GatewayID: _order.GatewayID, - Amount: _order.Amount, - Rate: _order.Rate, - Institution: _order.Institution, - AccountIdentifier: _order.AccountIdentifier, - AccountName: _order.AccountName, - ProviderID: "", - ProvisionBucket: bucketWithCurrency, - MessageHash: _order.MessageHash, - Memo: _order.Memo, - UpdatedAt: _order.UpdatedAt, - CreatedAt: _order.CreatedAt, - } - if tokenWithNet.Edges.Network != nil { - orderFields.Network = tokenWithNet.Edges.Network - } - err = service.AssignPaymentOrder(ctx, orderFields) - // AssignPaymentOrder now tries fallback when queue has no match; should succeed and assign to fallback - assert.NoError(t, err, "AssignPaymentOrder should succeed via fallback when no queue provider matches order rate 1390") - - updated, err := db.Client.PaymentOrder.Get(ctx, _order.ID) - assert.NoError(t, err) - assert.False(t, updated.FallbackTriedAt.IsZero(), "FallbackTriedAt should be set after successful fallback assignment") - - orderReqProvider, err := db.RedisClient.HGet(ctx, fmt.Sprintf("order_request_%s", _order.ID), "providerId").Result() - assert.NoError(t, err) - assert.Equal(t, testCtxForPQ.privateProviderProfile.ID, orderReqProvider, - "order should be sent to fallback provider (order_request_* in Redis), not refunded") - }) - - t.Run("GetStuckOrderCount_counts_only_stuck_orders", func(t *testing.T) { - ctx := context.Background() - oldThreshold := viper.GetInt("PROVIDER_STUCK_FULFILLMENT_THRESHOLD") - oldRefund := viper.GetInt("ORDER_REFUND_TIMEOUT") - viper.Set("PROVIDER_STUCK_FULFILLMENT_THRESHOLD", 1) - viper.Set("ORDER_REFUND_TIMEOUT", 60) // 60 seconds - defer func() { - viper.Set("PROVIDER_STUCK_FULFILLMENT_THRESHOLD", oldThreshold) - viper.Set("ORDER_REFUND_TIMEOUT", oldRefund) - }() - - baseline, err := utils.GetProviderStuckOrderCount(ctx, testCtxForPQ.publicProviderProfile.ID) - assert.NoError(t, err) - - // Create a deliberately stuck order: fulfilled, regular, updated_at before cutoff, fulfillment pending - cutoff := time.Now().Add(-2 * time.Minute) - stuckOrder, err := test.CreateTestPaymentOrder(testCtxForPQ.token, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, - "status": "fulfilled", - "updatedAt": cutoff, - "gateway_id": "stuck-order-gw", - }) - assert.NoError(t, err) - _, err = db.Client.PaymentOrder.UpdateOneID(stuckOrder.ID). - SetOrderType(paymentorder.OrderTypeRegular). - SetUpdatedAt(cutoff). - Save(ctx) - assert.NoError(t, err) - _, err = db.Client.PaymentOrderFulfillment.Create(). - SetOrderID(stuckOrder.ID). - SetValidationStatus(paymentorderfulfillment.ValidationStatusPending). - Save(ctx) - assert.NoError(t, err) - - // Control order: fulfilled + pending fulfillment but updated_at within threshold — must not be counted as stuck - recentTime := time.Now() - controlOrder, err := test.CreateTestPaymentOrder(testCtxForPQ.token, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, - "status": "fulfilled", - "updatedAt": recentTime, - "gateway_id": "control-order-gw", - }) - assert.NoError(t, err) - _, err = db.Client.PaymentOrder.UpdateOneID(controlOrder.ID). - SetOrderType(paymentorder.OrderTypeRegular). - SetUpdatedAt(recentTime). - Save(ctx) - assert.NoError(t, err) - _, err = db.Client.PaymentOrderFulfillment.Create(). - SetOrderID(controlOrder.ID). - SetValidationStatus(paymentorderfulfillment.ValidationStatusPending). - Save(ctx) - assert.NoError(t, err) - - countAfter, err := utils.GetProviderStuckOrderCount(ctx, testCtxForPQ.publicProviderProfile.ID) - assert.NoError(t, err) - assert.Equal(t, baseline+1, countAfter, "stuck count should increase by exactly 1 after adding one stuck order; control order (recent updated_at) must not be counted") - }) - - t.Run("AssignPaymentOrder_returns_ErrNoProviderDueToStuck_when_all_providers_stuck", func(t *testing.T) { - ctx := context.Background() - oldThreshold := viper.GetInt("PROVIDER_STUCK_FULFILLMENT_THRESHOLD") - oldRefund := viper.GetInt("ORDER_REFUND_TIMEOUT") - oldFallback := viper.Get("FALLBACK_PROVIDER_ID") - viper.Set("PROVIDER_STUCK_FULFILLMENT_THRESHOLD", 1) - viper.Set("ORDER_REFUND_TIMEOUT", 60) - viper.Set("FALLBACK_PROVIDER_ID", "") - defer func() { - viper.Set("PROVIDER_STUCK_FULFILLMENT_THRESHOLD", oldThreshold) - viper.Set("ORDER_REFUND_TIMEOUT", oldRefund) - viper.Set("FALLBACK_PROVIDER_ID", oldFallback) - }() - - // Create stuck order for the only provider in the bucket - cutoff := time.Now().Add(-2 * time.Minute) - stuckOrder, err := test.CreateTestPaymentOrder(testCtxForPQ.token, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, - "status": "fulfilled", - "updatedAt": cutoff, - "gateway_id": "stuck-gw-2", - }) - assert.NoError(t, err) - _, err = db.Client.PaymentOrder.UpdateOneID(stuckOrder.ID). - SetOrderType(paymentorder.OrderTypeRegular). - SetUpdatedAt(cutoff). - Save(ctx) - assert.NoError(t, err) - _, err = db.Client.PaymentOrderFulfillment.Create(). - SetOrderID(stuckOrder.ID). - SetValidationStatus(paymentorderfulfillment.ValidationStatusPending). - Save(ctx) - assert.NoError(t, err) - - bucket, err := test.CreateTestProvisionBucket(map[string]interface{}{ - "provider_id": testCtxForPQ.publicProviderProfile.ID, - "min_amount": testCtxForPQ.minAmount, - "max_amount": testCtxForPQ.maxAmount, - "currency_id": testCtxForPQ.currency.ID, - }) - assert.NoError(t, err) - - _order, err := test.CreateTestPaymentOrder(testCtxForPQ.token, map[string]interface{}{ - "provider": testCtxForPQ.publicProviderProfile, - "rate": 100.0, - "gateway_id": "order-stuck-test", - }) - assert.NoError(t, err) - _, err = test.AddProvisionBucketToPaymentOrder(_order, bucket.ID) - assert.NoError(t, err) - - order, err := db.Client.PaymentOrder.Query(). - Where(paymentorder.IDEQ(_order.ID)). - WithProvisionBucket(func(pb *ent.ProvisionBucketQuery) { pb.WithCurrency() }). - WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() }). - Only(ctx) - assert.NoError(t, err) - - // Use real service (not TestPriorityQueueService) so matchRate has stuck check - realService := NewPriorityQueueService() - // Build queue key exactly like AssignPaymentOrder does (order.ProvisionBucket) - redisKey := fmt.Sprintf("bucket_%s_%s_%s", order.Edges.ProvisionBucket.Edges.Currency.Code, order.Edges.ProvisionBucket.MinAmount, order.Edges.ProvisionBucket.MaxAmount) - // Push only our (stuck) provider so matchRate considers them, skips due to stuck, and returns ErrNoProviderDueToStuck - _ = db.RedisClient.Del(ctx, redisKey).Err() - tok := order.Edges.Token - netID := "" - if tok != nil && tok.Edges.Network != nil { - netID = tok.Edges.Network.Identifier - } else if tok != nil { - net, _ := tok.QueryNetwork().Only(ctx) - if net != nil { - netID = net.Identifier - } - } - providerData := fmt.Sprintf("%s:%s:%s:%s:%s:%s", - testCtxForPQ.publicProviderProfile.ID, - order.Edges.Token.Symbol, - netID, - order.Rate.String(), - order.Edges.ProvisionBucket.MinAmount.String(), - order.Edges.ProvisionBucket.MaxAmount.String()) - _, err = db.RedisClient.RPush(ctx, redisKey, providerData).Result() - assert.NoError(t, err) - queueLen, _ := db.RedisClient.LLen(ctx, redisKey).Result() - assert.Equal(t, int64(1), queueLen, "queue should have exactly one provider so matchRate considers and skips due to stuck") - - orderFields := types.PaymentOrderFields{ - ID: order.ID, - OrderType: "regular", - Token: order.Edges.Token, - GatewayID: order.GatewayID, - Amount: order.Amount, - Rate: order.Rate, - Institution: order.Institution, - AccountIdentifier: order.AccountIdentifier, - AccountName: order.AccountName, - ProviderID: "", - ProvisionBucket: order.Edges.ProvisionBucket, - Memo: order.Memo, - UpdatedAt: order.UpdatedAt, - CreatedAt: order.CreatedAt, - } - if order.Edges.Token != nil && order.Edges.Token.Edges.Network != nil { - orderFields.Network = order.Edges.Token.Edges.Network - } - - err = realService.AssignPaymentOrder(ctx, orderFields) - require.Error(t, err, "assignment must not succeed when all providers are stuck") - var errStuck *types.ErrNoProviderDueToStuck - if errors.As(err, &errStuck) { - assert.Equal(t, testCtxForPQ.currency.Code, errStuck.CurrencyCode) - } - // When queue key and data match, matchRate skips the stuck provider and returns ErrNoProviderDueToStuck. - // In some environments (e.g. CI) key format or Redis state may yield redis.Nil; we still require that assignment fails. - }) - }) -} diff --git a/services/receive_address.go b/services/receive_address.go index 10345fc53..0cfc01221 100644 --- a/services/receive_address.go +++ b/services/receive_address.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/ethereum/go-ethereum/crypto" + "github.com/paycrest/aggregator/config" "github.com/paycrest/aggregator/ent/network" "github.com/paycrest/aggregator/services/starknet" cryptoUtils "github.com/paycrest/aggregator/utils/crypto" @@ -61,7 +62,7 @@ func (s *ReceiveAddressService) CreateEVMAddress(ctx context.Context, walletServ // CreateTronAddress generates and saves a new Tron address func (s *ReceiveAddressService) CreateTronAddress(ctx context.Context) (string, []byte, error) { var nodeUrl tronEnums.Node - if serverConf.Environment == "production" { + if config.ServerConfig().Environment == "production" { nodeUrl = tronEnums.MAIN_NODE } else { nodeUrl = tronEnums.SHASTA_NODE diff --git a/tasks/fulfillments_webhooks.go b/tasks/fulfillments_webhooks.go index 3ffe2491b..5ad362ffe 100644 --- a/tasks/fulfillments_webhooks.go +++ b/tasks/fulfillments_webhooks.go @@ -15,13 +15,27 @@ import ( "github.com/paycrest/aggregator/ent/senderprofile" "github.com/paycrest/aggregator/ent/transactionlog" "github.com/paycrest/aggregator/ent/webhookretryattempt" + "github.com/paycrest/aggregator/services/assignment" "github.com/paycrest/aggregator/services/balance" "github.com/paycrest/aggregator/services/email" "github.com/paycrest/aggregator/storage" "github.com/paycrest/aggregator/utils" "github.com/paycrest/aggregator/utils/logger" + "github.com/shopspring/decimal" ) +func applyWebhookValidationFailedScore(ctx context.Context, orderID uuid.UUID) { + if err := assignment.ApplyProviderScoreChange(ctx, orderID, assignment.ScoreEventValidationFailed, decimal.NewFromFloat(assignment.PenaltyValidationFailed)); err != nil { + logger.WithFields(logger.Fields{"OrderID": orderID.String(), "Error": err.Error()}).Warnf("fulfillment sync: validation failed score") + } +} + +func applyWebhookValidatedRewardScore(ctx context.Context, orderID uuid.UUID) { + if err := assignment.ApplyProviderScoreChange(ctx, orderID, assignment.ScoreEventFulfilledValidated, decimal.NewFromFloat(assignment.RewardFulfilledValidated)); err != nil { + logger.WithFields(logger.Fields{"OrderID": orderID.String(), "Error": err.Error()}).Warnf("fulfillment sync: validated reward score") + } +} + const txStatusFiveMinError = "Failed to get transaction status after 5 minutes" const txStatusRetryWindow = 5 * time.Minute const txStatusRetryCutoff = 24 * time.Hour @@ -119,9 +133,6 @@ func SyncPaymentOrderFulfillments() { pq.WithAPIKey() }). WithFulfillments(). - WithProvisionBucket(func(pb *ent.ProvisionBucketQuery) { - pb.WithCurrency() - }). All(ctx) if err != nil { return @@ -139,9 +150,6 @@ func SyncPaymentOrderFulfillments() { pq.WithAPIKey() }). WithFulfillments(). - WithProvisionBucket(func(pb *ent.ProvisionBucketQuery) { - pb.WithCurrency() - }). Only(ctx) if err != nil { if ent.IsNotFound(err) { @@ -180,26 +188,19 @@ func SyncPaymentOrderFulfillments() { continue } - if order.Edges.ProvisionBucket == nil { - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "ProviderID": order.Edges.Provider.ID, - "Reason": "internal: ProvisionBucket is nil", - }).Errorf("SyncPaymentOrderFulfillments.MissingProvisionBucket") - continue - } - if order.Edges.ProvisionBucket.Edges.Currency == nil { + fiatCode, ierr := orderInstitutionFiatCode(ctx, order) + if ierr != nil { logger.WithFields(logger.Fields{ "OrderID": order.ID.String(), "ProviderID": order.Edges.Provider.ID, - "Reason": "internal: ProvisionBucket Currency is nil", - }).Errorf("SyncPaymentOrderFulfillments.MissingCurrency") + "Error": ierr.Error(), + }).Errorf("SyncPaymentOrderFulfillments.MissingInstitutionCurrency") continue } payload := map[string]interface{}{ "reference": getTxStatusReferenceForVA(order), - "currency": order.Edges.ProvisionBucket.Edges.Currency.Code, + "currency": fiatCode, } data, err := utils.CallProviderWithHMAC(ctx, order.Edges.Provider.ID, "POST", "/tx_status", payload) if err != nil { @@ -263,6 +264,7 @@ func SyncPaymentOrderFulfillments() { logger.WithFields(logger.Fields{"OrderID": order.ID.String(), "Error": relErr}).Errorf("SyncPaymentOrderFulfillments: release balance on payin failed") } } + applyWebhookValidationFailedScore(ctx, order.ID) } else if status == "success" { _, err = storage.Client.PaymentOrderFulfillment. Create(). @@ -324,22 +326,16 @@ func SyncPaymentOrderFulfillments() { "OrderID": order.ID, }).Errorf("SyncPaymentOrderFulfillments.UpdatePaymentOrderValidated.webhook") } + applyWebhookValidatedRewardScore(ctx, order.ID) } } else { - if order.Edges.ProvisionBucket == nil { + fiatCode, ierr := orderInstitutionFiatCode(ctx, order) + if ierr != nil { logger.WithFields(logger.Fields{ "OrderID": order.ID.String(), "ProviderID": order.Edges.Provider.ID, - "Reason": "internal: ProvisionBucket is nil", - }).Errorf("SyncPaymentOrderFulfillments.MissingProvisionBucket") - continue - } - if order.Edges.ProvisionBucket.Edges.Currency == nil { - logger.WithFields(logger.Fields{ - "OrderID": order.ID.String(), - "ProviderID": order.Edges.Provider.ID, - "Reason": "internal: ProvisionBucket Currency is nil", - }).Errorf("SyncPaymentOrderFulfillments.MissingCurrency") + "Error": ierr.Error(), + }).Errorf("SyncPaymentOrderFulfillments.MissingInstitutionCurrency") continue } @@ -347,7 +343,7 @@ func SyncPaymentOrderFulfillments() { if fulfillment.ValidationStatus == paymentorderfulfillment.ValidationStatusPending { payload := map[string]interface{}{ "reference": getTxStatusReferenceForVA(order), - "currency": order.Edges.ProvisionBucket.Edges.Currency.Code, + "currency": fiatCode, "psp": fulfillment.Psp, "txId": fulfillment.TxID, } @@ -374,6 +370,8 @@ func SyncPaymentOrderFulfillments() { "OrderID": order.ID.String(), "FulfillmentID": fulfillment.ID, }).Errorf("Failed to mark fulfillment as failed after 5 minutes") + } else { + applyWebhookValidationFailedScore(ctx, order.ID) } continue } @@ -424,6 +422,7 @@ func SyncPaymentOrderFulfillments() { logger.WithFields(logger.Fields{"OrderID": order.ID.String(), "Error": relErr}).Errorf("SyncPaymentOrderFulfillments: release balance on payin failed (pending→failed)") } } + applyWebhookValidationFailedScore(ctx, order.ID) } else if status == "success" { _, err = storage.Client.PaymentOrderFulfillment. UpdateOneID(fulfillment.ID). @@ -487,13 +486,14 @@ func SyncPaymentOrderFulfillments() { "OrderID": order.ID, }).Errorf("SyncPaymentOrderFulfillments.UpdatePaymentOrderValidated.webhook") } + applyWebhookValidatedRewardScore(ctx, order.ID) } } else if fulfillment.ValidationStatus == paymentorderfulfillment.ValidationStatusFailed && shouldRetryTxStatusFiveMinFailure(fulfillment) { payload := map[string]interface{}{ "orderId": order.ID.String(), - "currency": order.Edges.ProvisionBucket.Edges.Currency.Code, + "currency": fiatCode, "psp": fulfillment.Psp, "txId": fulfillment.TxID, } @@ -520,6 +520,7 @@ func SyncPaymentOrderFulfillments() { Save(ctx) } _, _ = order.Update().SetStatus(paymentorder.StatusFulfilled).Save(ctx) + applyWebhookValidationFailedScore(ctx, order.ID) } else if status == "success" { _, err = storage.Client.PaymentOrderFulfillment. UpdateOneID(fulfillment.ID). @@ -542,6 +543,7 @@ func SyncPaymentOrderFulfillments() { SetStatus(paymentorder.StatusValidated). Save(ctx) _ = utils.SendPaymentOrderWebhook(ctx, order) + applyWebhookValidatedRewardScore(ctx, order.ID) } } } @@ -608,6 +610,7 @@ func SyncPaymentOrderFulfillments() { "OrderID": order.ID, }).Errorf("SyncPaymentOrderFulfillments.UpdatePaymentOrderValidated.webhook") } + applyWebhookValidatedRewardScore(ctx, order.ID) } } } @@ -757,11 +760,13 @@ func RetryFailedWebhookNotifications() error { // syncRefundingOrder calls the provider /tx_status for an onramp order in Refunding and updates order/fulfillment to refunded/failed/pending. func syncRefundingOrder(ctx context.Context, order *ent.PaymentOrder) { - if order.Edges.ProvisionBucket == nil || order.Edges.ProvisionBucket.Edges.Currency == nil { + fiatCode, ierr := orderInstitutionFiatCode(ctx, order) + if ierr != nil { logger.WithFields(logger.Fields{ "OrderID": order.ID.String(), "ProviderID": order.Edges.Provider.ID, - }).Errorf("SyncPaymentOrderFulfillments.syncRefundingOrder: missing ProvisionBucket or Currency") + "Error": ierr.Error(), + }).Errorf("SyncPaymentOrderFulfillments.syncRefundingOrder: institution currency") return } @@ -777,7 +782,7 @@ func syncRefundingOrder(ctx context.Context, order *ent.PaymentOrder) { payload := map[string]interface{}{ "reference": refundReference, - "currency": order.Edges.ProvisionBucket.Edges.Currency.Code, + "currency": fiatCode, } data, err := utils.CallProviderWithHMAC(ctx, order.Edges.Provider.ID, "POST", "/tx_status", payload) if err != nil { @@ -876,6 +881,7 @@ func syncRefundingOrder(ctx context.Context, order *ent.PaymentOrder) { "Error": err, }).Errorf("SyncPaymentOrderFulfillments.syncRefundingOrder: set Fulfilled after refund failed") } + applyWebhookValidationFailedScore(ctx, order.ID) return } @@ -952,6 +958,10 @@ func callRequestAuthorization(ctx context.Context, order *ent.PaymentOrder, psp, // callTxRefundAndStore calls POST /tx_refund via CallProviderWithHMAC; on 200 stores refundReference in order metadata and returns it. func callTxRefundAndStore(ctx context.Context, order *ent.PaymentOrder) (refundReference string, err error) { + fiatCode, ierr := orderInstitutionFiatCode(ctx, order) + if ierr != nil { + return "", ierr + } fiatAmount := order.Amount.Add(order.SenderFee).Mul(order.Rate).RoundBank(0).String() refundAccount := map[string]interface{}{ "accountIdentifier": order.AccountIdentifier, @@ -965,7 +975,7 @@ func callTxRefundAndStore(ctx context.Context, order *ent.PaymentOrder) (refundR } body := map[string]interface{}{ "orderId": order.ID.String(), - "currency": order.Edges.ProvisionBucket.Edges.Currency.Code, + "currency": fiatCode, "amount": fiatAmount, "refundAccount": refundAccount, } @@ -1006,3 +1016,17 @@ func callTxRefundAndStore(ctx context.Context, order *ent.PaymentOrder) (refundR } return refundReference, nil } + +func orderInstitutionFiatCode(ctx context.Context, order *ent.PaymentOrder) (string, error) { + if order.Institution == "" { + return "", fmt.Errorf("order has no institution") + } + inst, err := utils.GetInstitutionByCode(ctx, order.Institution, true) + if err != nil { + return "", fmt.Errorf("institution fiat currency: %w", err) + } + if inst == nil || inst.Edges.FiatCurrency == nil { + return "", fmt.Errorf("institution or fiat currency not found") + } + return inst.Edges.FiatCurrency.Code, nil +} diff --git a/tasks/indexing.go b/tasks/indexing.go index f8194f56e..45a119e7a 100644 --- a/tasks/indexing.go +++ b/tasks/indexing.go @@ -432,15 +432,11 @@ func ProcessStuckValidatedOrders() error { ), ), paymentorder.HasProvider(), - paymentorder.HasProvisionBucket(), ). WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() }). WithProvider(). - WithProvisionBucket(func(pb *ent.ProvisionBucketQuery) { - pb.WithCurrency() - }). All(runCtx) if err != nil { logger.WithFields(logger.Fields{ diff --git a/tasks/order_requests.go b/tasks/order_requests.go index eb8406dbe..f20dbf28a 100644 --- a/tasks/order_requests.go +++ b/tasks/order_requests.go @@ -10,7 +10,7 @@ import ( "github.com/paycrest/aggregator/ent" "github.com/paycrest/aggregator/ent/paymentorder" "github.com/paycrest/aggregator/ent/providerprofile" - "github.com/paycrest/aggregator/services" + "github.com/paycrest/aggregator/services/assignment" "github.com/paycrest/aggregator/services/balance" "github.com/paycrest/aggregator/storage" "github.com/paycrest/aggregator/types" @@ -30,18 +30,22 @@ func canReassignCancelledOrder(order *ent.PaymentOrder) bool { // cleanupStuckFulfilledFailedOrder clears provider and sets status to Pending for orders stuck in Fulfilled+failed outside refund window (state cleanup only). func cleanupStuckFulfilledFailedOrder(ctx context.Context, order *ent.PaymentOrder) { // Release reserved fiat balance for the provider before clearing (same logic as reassignCancelledOrder). - if order.Edges.Provider != nil && order.Edges.ProvisionBucket != nil && order.Edges.ProvisionBucket.Edges.Currency != nil { - currency := order.Edges.ProvisionBucket.Edges.Currency.Code - amount := order.Amount.Mul(order.Rate).RoundBank(0) - balanceSvc := balance.New() - if relErr := balanceSvc.ReleaseFiatBalance(ctx, order.Edges.Provider.ID, currency, amount, nil); relErr != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", relErr), - "OrderID": order.ID.String(), - "ProviderID": order.Edges.Provider.ID, - "Currency": currency, - "Amount": amount.String(), - }).Errorf("cleanupStuckFulfilledFailedOrder: failed to release reserved balance (best effort)") + if order.Edges.Provider != nil { + currency, ierr := orderInstitutionFiatCode(ctx, order) + if ierr != nil { + logger.WithFields(logger.Fields{"OrderID": order.ID.String(), "Error": ierr.Error()}).Warnf("cleanupStuckFulfilledFailedOrder: institution currency") + } else { + amount := order.Amount.Mul(order.Rate).RoundBank(0) + balanceSvc := balance.New() + if relErr := balanceSvc.ReleaseFiatBalance(ctx, order.Edges.Provider.ID, currency, amount, nil); relErr != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", relErr), + "OrderID": order.ID.String(), + "ProviderID": order.Edges.Provider.ID, + "Currency": currency, + "Amount": amount.String(), + }).Errorf("cleanupStuckFulfilledFailedOrder: failed to release reserved balance (best effort)") + } } } @@ -127,16 +131,15 @@ func reassignCancelledOrder(ctx context.Context, order *ent.PaymentOrder, fulfil // Best-effort: release any reserved balance held by this provider for the order. // This prevents "stuck" reserved balances from blocking future assignments. - if order.Edges.ProvisionBucket != nil && order.Edges.ProvisionBucket.Edges.Currency != nil { - currency := order.Edges.ProvisionBucket.Edges.Currency.Code + if cur, ierr := orderInstitutionFiatCode(ctx, order); ierr == nil { amount := order.Amount.Mul(order.Rate).RoundBank(0) balanceSvc := balance.New() - if relErr := balanceSvc.ReleaseFiatBalance(ctx, order.Edges.Provider.ID, currency, amount, nil); relErr != nil { + if relErr := balanceSvc.ReleaseFiatBalance(ctx, order.Edges.Provider.ID, cur, amount, nil); relErr != nil { logger.WithFields(logger.Fields{ "Error": fmt.Sprintf("%v", relErr), "OrderID": order.ID.String(), "ProviderID": order.Edges.Provider.ID, - "Currency": currency, + "Currency": cur, "Amount": amount.String(), }).Warnf("reassignCancelledOrder: failed to release reserved balance (best effort)") } @@ -174,10 +177,9 @@ func reassignCancelledOrder(ctx context.Context, order *ent.PaymentOrder, fulfil AccountName: order.AccountName, ProviderID: "", Memo: order.Memo, - ProvisionBucket: order.Edges.ProvisionBucket, } - err = services.NewPriorityQueueService().AssignPaymentOrder(ctx, paymentOrder) + err = assignment.New().AssignPaymentOrder(ctx, paymentOrder) if err != nil { logger.WithFields(logger.Fields{ "Error": fmt.Sprintf("%v", err), @@ -193,7 +195,7 @@ const orderRequestKeyPrefix = "order_request_" // ReassignStaleOrderRequest reassigns expired order requests to providers func ReassignStaleOrderRequest(ctx context.Context, orderRequestChan <-chan *redis.Message) { - priorityQueueSvc := services.NewPriorityQueueService() + priorityQueueSvc := assignment.New() balanceSvc := balance.New() for { @@ -250,9 +252,6 @@ func ReassignStaleOrderRequest(ctx context.Context, orderRequestChan <-chan *red Where( paymentorder.IDEQ(orderUUID), ). - WithProvisionBucket(func(pbq *ent.ProvisionBucketQuery) { - pbq.WithCurrency() - }). WithProvider(). WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() @@ -290,6 +289,9 @@ func ReassignStaleOrderRequest(ctx context.Context, orderRequestChan <-chan *red "ExcludeKey": excludeKey, }).Warnf("ReassignStaleOrderRequest: failed to set TTL for order exclude list") } + if scoreErr := assignment.ApplyProviderScoreChangeForProvider(ctx, order.ID, metaProviderID, assignment.ScoreEventOrderRequestExpired, decimal.NewFromFloat(assignment.PenaltyOrderRequestExpired)); scoreErr != nil { + logger.WithFields(logger.Fields{"OrderID": order.ID.String(), "ProviderID": metaProviderID, "Error": scoreErr.Error()}).Warnf("ReassignStaleOrderRequest: stale expiry score penalty") + } } // Release reserved amount (best effort; failures should not block reassignment). @@ -310,19 +312,22 @@ func ReassignStaleOrderRequest(ctx context.Context, orderRequestChan <-chan *red // Cleanup metadata key regardless of success to avoid stale entries. _, _ = storage.RedisClient.Del(ctx, metaKey).Result() - } else if order.Edges.Provider != nil && order.Edges.ProvisionBucket != nil && order.Edges.ProvisionBucket.Edges.Currency != nil { - // Fallback: no meta (e.g. key missing/expired) but order has provider and bucket (e.g. private/pre-set). - // Release so reserved balance is not left stuck. - currency := order.Edges.ProvisionBucket.Edges.Currency.Code - amount := order.Amount.Mul(order.Rate).RoundBank(0) - if relErr := balanceSvc.ReleaseFiatBalance(ctx, order.Edges.Provider.ID, currency, amount, nil); relErr != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", relErr), - "OrderID": order.ID.String(), - "ProviderID": order.Edges.Provider.ID, - "Currency": currency, - "Amount": amount.String(), - }).Warnf("ReassignStaleOrderRequest: failed to release reserved balance from order (best effort)") + } else if order.Edges.Provider != nil { + // Fallback: no meta (e.g. key missing/expired); release using institution currency. + currency, ierr := orderInstitutionFiatCode(ctx, order) + if ierr != nil { + logger.WithFields(logger.Fields{"OrderID": order.ID.String(), "Error": ierr.Error()}).Warnf("ReassignStaleOrderRequest: institution currency for release") + } else { + amount := order.Amount.Mul(order.Rate).RoundBank(0) + if relErr := balanceSvc.ReleaseFiatBalance(ctx, order.Edges.Provider.ID, currency, amount, nil); relErr != nil { + logger.WithFields(logger.Fields{ + "Error": fmt.Sprintf("%v", relErr), + "OrderID": order.ID.String(), + "ProviderID": order.Edges.Provider.ID, + "Currency": currency, + "Amount": amount.String(), + }).Warnf("ReassignStaleOrderRequest: failed to release reserved balance from order (best effort)") + } } } @@ -406,7 +411,6 @@ func ReassignStaleOrderRequest(ctx context.Context, orderRequestChan <-chan *red Memo: order.Memo, ProviderID: providerID, MessageHash: order.MessageHash, - ProvisionBucket: order.Edges.ProvisionBucket, } // Include token and network if available @@ -418,7 +422,7 @@ func ReassignStaleOrderRequest(ctx context.Context, orderRequestChan <-chan *red } // Assign the order to a provider - err = priorityQueueSvc.AssignPaymentOrder(ctx, orderFields) + err = priorityQueueSvc.AssignPaymentOrderWithTrigger(ctx, orderFields, assignment.AssignmentTriggerReassignStale) if err != nil { logger.WithFields(logger.Fields{ "Error": fmt.Sprintf("%v", err), diff --git a/tasks/stale_ops.go b/tasks/stale_ops.go index a044a1d8b..9e1eb3b1f 100644 --- a/tasks/stale_ops.go +++ b/tasks/stale_ops.go @@ -8,18 +8,15 @@ import ( "time" "github.com/paycrest/aggregator/ent" - "github.com/paycrest/aggregator/ent/fiatcurrency" "github.com/paycrest/aggregator/ent/paymentorder" "github.com/paycrest/aggregator/ent/paymentorderfulfillment" "github.com/paycrest/aggregator/ent/providerprofile" - "github.com/paycrest/aggregator/ent/provisionbucket" "github.com/paycrest/aggregator/ent/transactionlog" - "github.com/paycrest/aggregator/services" + "github.com/paycrest/aggregator/services/assignment" orderService "github.com/paycrest/aggregator/services/order" starknetService "github.com/paycrest/aggregator/services/starknet" "github.com/paycrest/aggregator/storage" "github.com/paycrest/aggregator/types" - "github.com/paycrest/aggregator/utils" "github.com/paycrest/aggregator/utils/logger" ) @@ -422,9 +419,6 @@ func RetryStaleUserOperations() error { WithToken(func(tq *ent.TokenQuery) { tq.WithNetwork() }). - WithProvisionBucket(func(pbq *ent.ProvisionBucketQuery) { - pbq.WithCurrency() - }). WithProvider(). All(ctx) if err != nil { @@ -459,7 +453,7 @@ func RetryStaleUserOperations() error { } } - pq := services.NewPriorityQueueService() + pq := assignment.New() // If the order could still be reassigned to another public provider (per order_requests logic), if order.CancellationCount < orderConf.RefundCancellationCount { @@ -467,8 +461,7 @@ func RetryStaleUserOperations() error { tryFullQueue := !fallbackAlreadyTried // No provider or public provider: can try full-queue (reassign to public). Private provider: skip full-queue. - // Allow nil bucket so we can try to resolve and persist it before assignment (another node can then pick the order). - canTryFullQueue := (order.Edges.ProvisionBucket == nil || (order.Edges.ProvisionBucket != nil && order.Edges.ProvisionBucket.Edges.Currency != nil)) && + canTryFullQueue := order.Institution != "" && (order.Edges.Provider == nil || order.Edges.Provider.VisibilityMode != providerprofile.VisibilityModePrivate) if tryFullQueue && canTryFullQueue { @@ -482,66 +475,37 @@ func RetryStaleUserOperations() error { Save(ctx) } - // Resolve and persist nil provision bucket so AssignPaymentOrder can run and another node can pick the order. - if order.Edges.ProvisionBucket == nil { - institution, instErr := utils.GetInstitutionByCode(ctx, order.Institution, true) - if instErr == nil && institution != nil && institution.Edges.FiatCurrency != nil { - fiatAmount := order.Amount.Mul(order.Rate) - bucket, bErr := storage.Client.ProvisionBucket. - Query(). - Where( - provisionbucket.MaxAmountGTE(fiatAmount), - provisionbucket.MinAmountLTE(fiatAmount), - provisionbucket.HasCurrencyWith(fiatcurrency.IDEQ(institution.Edges.FiatCurrency.ID)), - ). - WithCurrency(). - First(ctx) - if bErr == nil && bucket != nil { - if _, upErr := storage.Client.PaymentOrder.UpdateOneID(order.ID).SetProvisionBucket(bucket).Save(ctx); upErr == nil { - order.Edges.ProvisionBucket = bucket - } - } - } - if order.Edges.ProvisionBucket == nil { - logger.WithFields(logger.Fields{"OrderID": order.ID.String()}).Warnf("stale_ops: could not resolve provision bucket for order; skipping full-queue assignment") - } + orderFields := types.PaymentOrderFields{ + ID: order.ID, + OrderType: order.OrderType.String(), + Token: order.Edges.Token, + GatewayID: order.GatewayID, + Amount: order.Amount, + Rate: order.Rate, + Institution: order.Institution, + AccountIdentifier: order.AccountIdentifier, + AccountName: order.AccountName, + ProviderID: "", + MessageHash: order.MessageHash, + Memo: order.Memo, + UpdatedAt: order.UpdatedAt, + CreatedAt: order.CreatedAt, + } + if order.Edges.Token != nil && order.Edges.Token.Edges.Network != nil { + orderFields.Network = order.Edges.Token.Edges.Network } - if order.Edges.ProvisionBucket != nil && order.Edges.ProvisionBucket.Edges.Currency != nil { - orderFields := types.PaymentOrderFields{ - ID: order.ID, - OrderType: order.OrderType.String(), - Token: order.Edges.Token, - GatewayID: order.GatewayID, - Amount: order.Amount, - Rate: order.Rate, - Institution: order.Institution, - AccountIdentifier: order.AccountIdentifier, - AccountName: order.AccountName, - ProviderID: "", - ProvisionBucket: order.Edges.ProvisionBucket, - MessageHash: order.MessageHash, - Memo: order.Memo, - UpdatedAt: order.UpdatedAt, - CreatedAt: order.CreatedAt, - } - if order.Edges.Token != nil && order.Edges.Token.Edges.Network != nil { - orderFields.Network = order.Edges.Token.Edges.Network - } - - err := pq.AssignPaymentOrder(ctx, orderFields) - if err == nil { - logger.WithFields(logger.Fields{"OrderID": order.ID.String()}).Infof("order assigned to provider during refund process; skipping refund") - continue - } - // We tried public reassignment and it failed; set cancellation count to threshold immediately so we can refund. - // Any failure should proceed to try fallback, else proceed with refund - _, _ = storage.Client.PaymentOrder. - Update(). - Where(paymentorder.IDEQ(order.ID)). - SetCancellationCount(orderConf.RefundCancellationCount). - Save(ctx) + err := pq.AssignPaymentOrderWithTrigger(ctx, orderFields, assignment.AssignmentTriggerStaleOps) + if err == nil { + logger.WithFields(logger.Fields{"OrderID": order.ID.String()}).Infof("order assigned to provider during refund process; skipping refund") + continue } + // We tried public reassignment and it failed; set cancellation count to threshold immediately so we can refund. + _, _ = storage.Client.PaymentOrder. + Update(). + Where(paymentorder.IDEQ(order.ID)). + SetCancellationCount(orderConf.RefundCancellationCount). + Save(ctx) } // Private orders: try assignment to pre-set provider (AssignPaymentOrder accepts nil bucket for pre-set provider). @@ -564,7 +528,6 @@ func RetryStaleUserOperations() error { AccountIdentifier: order.AccountIdentifier, AccountName: order.AccountName, ProviderID: order.Edges.Provider.ID, - ProvisionBucket: order.Edges.ProvisionBucket, MessageHash: order.MessageHash, Memo: order.Memo, UpdatedAt: order.UpdatedAt, @@ -585,7 +548,7 @@ func RetryStaleUserOperations() error { // Fallback only succeeds when order_request_* key is gone (expired or cleared); TryFallbackAssignment returns error if key exists. // Any failure should proceed with refund if tryFallback { - err := pq.TryFallbackAssignment(ctx, order) + err := pq.TryFallbackAssignment(ctx, order, false) if err == nil { continue } diff --git a/tasks/startup.go b/tasks/startup.go index 3766df34e..7bf9242fb 100644 --- a/tasks/startup.go +++ b/tasks/startup.go @@ -5,7 +5,6 @@ import ( "time" "github.com/go-co-op/gocron" - "github.com/paycrest/aggregator/services" "github.com/paycrest/aggregator/storage" "github.com/paycrest/aggregator/utils/logger" ) @@ -40,32 +39,18 @@ func SubscribeToRedisKeyspaceEvents() func() { func StartCronJobs() { // Use the system's local timezone instead of hardcoded UTC to prevent timezone conflicts scheduler := gocron.NewScheduler(time.Local) - priorityQueue := services.NewPriorityQueueService() err := ComputeMarketRate() if err != nil { logger.Errorf("StartCronJobs for ComputeMarketRate: %v", err) } - if serverConf.Environment != "production" { - err = priorityQueue.ProcessBucketQueues() - if err != nil { - logger.Errorf("StartCronJobs for ProcessBucketQueues: %v", err) - } - } - // Compute market rate every 9 minutes _, err = scheduler.Every(9).Minutes().Do(ComputeMarketRate) if err != nil { logger.Errorf("StartCronJobs for ComputeMarketRate: %v", err) } - // Refresh provision bucket priority queues every X minutes - _, err = scheduler.Every(orderConf.BucketQueueRebuildInterval).Minutes().Do(priorityQueue.ProcessBucketQueues) - if err != nil { - logger.Errorf("StartCronJobs for ProcessBucketQueues: %v", err) - } - // Retry failed webhook notifications every 13 minutes _, err = scheduler.Every(13).Minutes().Do(RetryFailedWebhookNotifications) if err != nil { diff --git a/types/types.go b/types/types.go index ea93916b5..cf21efc58 100644 --- a/types/types.go +++ b/types/types.go @@ -434,7 +434,6 @@ type PaymentOrderFields struct { ProviderID string Memo string Metadata map[string]interface{} - ProvisionBucket *ent.ProvisionBucket UpdatedAt time.Time CreatedAt time.Time } diff --git a/utils/test/db.go b/utils/test/db.go index 6dfca11bf..fb9c993fb 100644 --- a/utils/test/db.go +++ b/utils/test/db.go @@ -480,6 +480,8 @@ func CreateTestProviderProfile(overrides map[string]interface{}) (*ent.ProviderP "is_partner": false, "visibility_mode": "public", "is_available": true, + // Schema default is false; rate validation and assignment require active public providers. + "is_active": true, } // Apply overrides @@ -495,6 +497,7 @@ func CreateTestProviderProfile(overrides map[string]interface{}) (*ent.ProviderP SetProvisionMode(providerprofile.ProvisionMode(payload["provision_mode"].(string))). SetUserID(payload["user_id"].(uuid.UUID)). SetVisibilityMode(providerprofile.VisibilityMode(payload["visibility_mode"].(string))). + SetIsActive(payload["is_active"].(bool)). Save(context.Background()) if err != nil { return nil, err @@ -516,14 +519,6 @@ func CreateTestProviderProfile(overrides map[string]interface{}) (*ent.ProviderP return profile, err } -func AddProvisionBucketToPaymentOrder(order *ent.PaymentOrder, bucketId int) (*ent.PaymentOrder, error) { - order, err := order. - Update(). - SetProvisionBucketID(bucketId). - Save(context.Background()) - return order, err -} - func AddProviderOrderTokenToProvider(overrides map[string]interface{}) (*ent.ProviderOrderToken, error) { // Default payload using new two-sided rate fields payload := map[string]interface{}{ @@ -597,43 +592,6 @@ func AddProviderOrderTokenToProvider(overrides map[string]interface{}) (*ent.Pro return orderToken, err } -// CreateTestProvisionBucket creates a test ProvisionBucket with defaults or custom values -func CreateTestProvisionBucket(overrides map[string]interface{}) (*ent.ProvisionBucket, error) { - ctx := context.Background() - - // Default payload - payload := map[string]interface{}{ - "currency_id": 1, - "max_amount": decimal.NewFromFloat(1.0), - "min_amount": decimal.NewFromFloat(1.0), - "provider_id": nil, - } - - // Apply overrides - for key, value := range overrides { - payload[key] = value - } - - bucket, err := db.Client.ProvisionBucket.Create(). - SetMinAmount(payload["min_amount"].(decimal.Decimal)). - SetMaxAmount(payload["max_amount"].(decimal.Decimal)). - SetCurrencyID(payload["currency_id"].(uuid.UUID)). - Save(ctx) - if err != nil { - return nil, err - } - - _, err = db.Client.ProviderProfile. - UpdateOneID(payload["provider_id"].(string)). - AddProvisionBucketIDs(bucket.ID). - Save(ctx) - if err != nil { - return nil, err - } - - return bucket, nil -} - // CreateTestFiatCurrency creates a test FiatCurrency with defaults or custom values func CreateTestFiatCurrency(overrides map[string]interface{}) (*ent.FiatCurrency, error) { diff --git a/utils/utils.go b/utils/utils.go index 3e31b19cc..e5c106bec 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -15,6 +15,7 @@ import ( "net/url" "reflect" "regexp" + "slices" "sort" "strings" "time" @@ -966,84 +967,9 @@ func IsBase64(s string) bool { return false } -// GetTokenRateFromQueue gets the rate of a token from the priority queue for the given side (buy/sell). -// Bucket keys are side-suffixed: bucket_{currency}_{min}_{max}_{side}. Scanning without side would mix buy and sell rates. -func GetTokenRateFromQueue(tokenSymbol string, orderAmount decimal.Decimal, fiatCurrency string, marketRate decimal.Decimal, side RateSide) (decimal.Decimal, error) { - ctx := context.Background() - - // Scan for side-specific bucket keys: bucket_{currency}_{min}_{max}_{side} - keys, _, err := storage.RedisClient.Scan(ctx, uint64(0), "bucket_"+fiatCurrency+"_*_*_"+string(side), 100).Result() - if err != nil { - return decimal.Decimal{}, err - } - - rateResponse := marketRate - highestMaxAmount := decimal.NewFromInt(0) - - // Scan through the buckets to find a suitable rate - for _, key := range keys { - bd, err := parseBucketKey(key) - if err != nil { - continue - } - minAmount, maxAmount := bd.MinAmount, bd.MaxAmount - - for index := 0; ; index++ { - // Get the topmost provider in the priority queue of the bucket - providerData, err := storage.RedisClient.LIndex(ctx, key, int64(index)).Result() - if err != nil { - break - } - parts := strings.Split(providerData, ":") - if len(parts) != 6 { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "ProviderData": providerData, - "Token": tokenSymbol, - "Currency": fiatCurrency, - "MinAmount": minAmount, - "MaxAmount": maxAmount, - }).Errorf("GetTokenRate.InvalidProviderData: %v", providerData) - continue - } - - // Skip entry if token doesn't match - if parts[1] != tokenSymbol { - continue - } - - // Skip entry if order amount is not within provider's min and max order amount - minOrderAmount, err := decimal.NewFromString(parts[4]) - if err != nil { - continue - } - - maxOrderAmount, err := decimal.NewFromString(parts[5]) - if err != nil { - continue - } - - if orderAmount.LessThan(minOrderAmount) || orderAmount.GreaterThan(maxOrderAmount) { - continue - } - - // Get fiat equivalent of the token amount - rate, _ := decimal.NewFromString(parts[3]) - fiatAmount := orderAmount.Mul(rate) - - // Check if fiat amount is within the bucket range and set the rate - if fiatAmount.GreaterThanOrEqual(minAmount) && fiatAmount.LessThanOrEqual(maxAmount) { - rateResponse = rate - break - } else if maxAmount.GreaterThan(highestMaxAmount) { - // Get the highest max amount - highestMaxAmount = maxAmount - rateResponse = rate - } - } - } - - return rateResponse, nil +// GetTokenRateFromQueue is deprecated: Redis provision-bucket queues were removed. Callers should use marketRate / ValidateRate instead. +func GetTokenRateFromQueue(_ string, _ decimal.Decimal, _ string, marketRate decimal.Decimal, _ RateSide) (decimal.Decimal, error) { + return marketRate, nil } // GetInstitutionByCode returns the institution for a given institution code @@ -1113,7 +1039,7 @@ func ValidateRate(ctx context.Context, token *ent.Token, currency *ent.FiatCurre if providerID != "" { result, err = validateProviderRate(ctx, token, currency, amount, providerID, networkFilter, side) } else { - result, err = validateBucketRate(ctx, token, currency, amount, networkFilter, side) + result, err = validatePublicQuoteRate(ctx, token, currency, amount, networkFilter, side) } if err != nil { @@ -1121,7 +1047,6 @@ func ValidateRate(ctx context.Context, token *ent.Token, currency *ent.FiatCurre } // For direct currency matches, rate is always 1:1 - // Both Redis queues and DB store rate 1 for direct matches (e.g., CNGN->NGN in NGN bucket) // We explicitly return 1.0 here for clarity and to ensure consistency if isDirectMatch { result.Rate = decimal.NewFromInt(1) @@ -1176,26 +1101,20 @@ func validateProviderRate(ctx context.Context, token *ent.Token, currency *ent.F return RateValidationResult{}, fmt.Errorf("amount must be at least %s for this provider", providerOrderToken.MinOrderAmount) } - // Get rate first (needed for fiat conversion and OTC validation) + // Rate from DB (fixed or floating vs live fiat market); quotes do not use Redis bucket queues. var rateResponse decimal.Decimal - redisRate, found := getProviderRateFromRedis(ctx, providerID, token.Symbol, currency.Code, amount, networkFilter, side) - if found { - rateResponse = redisRate - } else { - // Fallback to database rate if Redis rate not found - switch side { - case RateSideBuy: - if !providerOrderToken.FixedBuyRate.IsZero() { - rateResponse = providerOrderToken.FixedBuyRate - } else if !providerOrderToken.FloatingBuyDelta.IsZero() && !currency.MarketBuyRate.IsZero() { - rateResponse = currency.MarketBuyRate.Add(providerOrderToken.FloatingBuyDelta).RoundBank(2) - } - case RateSideSell: - if !providerOrderToken.FixedSellRate.IsZero() { - rateResponse = providerOrderToken.FixedSellRate - } else if !providerOrderToken.FloatingSellDelta.IsZero() && !currency.MarketSellRate.IsZero() { - rateResponse = currency.MarketSellRate.Add(providerOrderToken.FloatingSellDelta).RoundBank(2) - } + switch side { + case RateSideBuy: + if !providerOrderToken.FixedBuyRate.IsZero() { + rateResponse = providerOrderToken.FixedBuyRate + } else if !providerOrderToken.FloatingBuyDelta.IsZero() && !currency.MarketBuyRate.IsZero() { + rateResponse = currency.MarketBuyRate.Add(providerOrderToken.FloatingBuyDelta).RoundBank(2) + } + case RateSideSell: + if !providerOrderToken.FixedSellRate.IsZero() { + rateResponse = providerOrderToken.FixedSellRate + } else if !providerOrderToken.FloatingSellDelta.IsZero() && !currency.MarketSellRate.IsZero() { + rateResponse = currency.MarketSellRate.Add(providerOrderToken.FloatingSellDelta).RoundBank(2) } } @@ -1270,549 +1189,293 @@ func validateProviderRate(ctx context.Context, token *ent.Token, currency *ent.F }, nil } -// getProviderRateFromRedis retrieves the provider's current rate from Redis queue. -func getProviderRateFromRedis(ctx context.Context, providerID, tokenSymbol, currencyCode string, amount decimal.Decimal, networkFilter string, side RateSide) (decimal.Decimal, bool) { - // Get redis keys for provision buckets for this currency and side - // Scan for side-specific bucket keys: bucket_{currency}_{min}_{max}_{side} - keys, _, err := storage.RedisClient.Scan(ctx, uint64(0), "bucket_"+currencyCode+"_*_*_"+string(side), 100).Result() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "ProviderID": providerID, - "Token": tokenSymbol, - "Currency": currencyCode, - }).Debugf("Failed to scan Redis buckets for provider rate") - return decimal.Zero, false - } +// quoteRecentVolumeWindow matches assignment fairness (24h successful fiat volume; hardcoded). +const quoteRecentVolumeWindow = 24 * time.Hour - // Scan through the buckets to find the provider's rate - for _, key := range keys { - _, err := parseBucketKey(key) - if err != nil { - continue - } - - // Get all providers in this bucket - providers, err := storage.RedisClient.LRange(ctx, key, 0, -1).Result() +// RecentFiatVolumeByProvider returns per-provider SUM(amount*rate) for validated/settled orders +// with updated_at >= since. Uses the ent client so it works with any dialect (Postgres prod, SQLite tests). +// When storage.Client is nil, returns zero volume for each id (no error). +func RecentFiatVolumeByProvider(ctx context.Context, since time.Time, providerIDs []string) (map[string]decimal.Decimal, error) { + out := make(map[string]decimal.Decimal) + for _, pid := range providerIDs { + out[pid] = decimal.Zero + } + if len(providerIDs) == 0 || storage.Client == nil { + return out, nil + } + for _, pid := range providerIDs { + rows, err := storage.Client.PaymentOrder.Query(). + Where( + paymentorder.HasProviderWith(providerprofile.IDEQ(pid)), + paymentorder.StatusIn(paymentorder.StatusValidated, paymentorder.StatusSettled), + paymentorder.UpdatedAtGTE(since), + ). + Select(paymentorder.FieldAmount, paymentorder.FieldRate). + All(ctx) if err != nil { - continue + return nil, err } - - // Look for the specific provider - for _, providerData := range providers { - parts := strings.Split(providerData, ":") - if len(parts) != 6 { - continue - } - - // Skip entry if network filter is set and does not match - if networkFilter != "" && parts[2] != networkFilter { - continue - } - - // Check if this is the provider we're looking for - if parts[0] == providerID && parts[1] == tokenSymbol { - // Parse the rate - rate, err := decimal.NewFromString(parts[3]) - if err != nil { - continue - } - - // Parse min/max order amounts - minOrderAmount, err := decimal.NewFromString(parts[4]) - if err != nil { - continue - } - - maxOrderAmount, err := decimal.NewFromString(parts[5]) - if err != nil { - continue - } - - // Check if amount is within provider's limits - if amount.GreaterThanOrEqual(minOrderAmount) && amount.LessThanOrEqual(maxOrderAmount) { - return rate, true - } - } + var sum decimal.Decimal + for _, po := range rows { + sum = sum.Add(po.Amount.Mul(po.Rate)) } + out[pid] = sum } - - return decimal.Zero, false + return out, nil } -// validateBucketRate handles bucket-based rate validation -func validateBucketRate(ctx context.Context, token *ent.Token, currency *ent.FiatCurrency, amount decimal.Decimal, networkIdentifier string, side RateSide) (RateValidationResult, error) { - // Get redis keys for provision buckets for the specific side - // Scan for side-specific bucket keys: bucket_{currency}_{min}_{max}_{side} - keys, _, err := storage.RedisClient.Scan(ctx, uint64(0), "bucket_"+currency.Code+"_*_*_"+string(side), 100).Result() - if err != nil { - logger.WithFields(logger.Fields{ - "Error": fmt.Sprintf("%v", err), - "Currency": currency.Code, - "Network": networkIdentifier, - }).Errorf("Failed to scan Redis buckets for bucket rate") - return RateValidationResult{}, fmt.Errorf("internal server error") - } +func quoteRecentFiatVolumeByProvider(ctx context.Context, providerIDs []string) (map[string]decimal.Decimal, error) { + since := time.Now().Add(-quoteRecentVolumeWindow) + return RecentFiatVolumeByProvider(ctx, since, providerIDs) +} - // Track the best available rate and reason for logging - var bestRate decimal.Decimal - var foundExactMatch bool - var selectedProviderID string - var selectedOrderType paymentorder.OrderType - var anySkippedDueToStuck bool - var currencyForStuck string - - // Scan through the buckets to find a matching rate - for _, key := range keys { - bucketData, err := parseBucketKey(key) - if err != nil { - logger.WithFields(logger.Fields{ - "Key": key, - "Error": err, - }).Errorf("ValidateRate.InvalidBucketKey: failed to parse bucket key") - continue +func quoteRateForPublicCandidate(pot *ent.ProviderOrderToken, side RateSide, currency *ent.FiatCurrency) decimal.Decimal { + switch side { + case RateSideBuy: + if !pot.FixedBuyRate.IsZero() { + return pot.FixedBuyRate } - - // Get all providers in this bucket to find the first suitable one (priority queue order) - providers, err := storage.RedisClient.LRange(ctx, key, 0, -1).Result() - if err != nil { - logger.WithFields(logger.Fields{ - "Key": key, - "Error": err, - }).Errorf("ValidateRate.FailedToGetProviders: failed to get providers from bucket") - continue + if !currency.MarketBuyRate.IsZero() { + return currency.MarketBuyRate.Add(pot.FloatingBuyDelta).RoundBank(2) } - - // Find the first provider at the top of the queue that matches our criteria - result := findSuitableProviderRate(ctx, providers, token, networkIdentifier, amount, bucketData, side) - if result.Found { - foundExactMatch = true - bestRate = result.Rate - selectedProviderID = result.ProviderID - selectedOrderType = result.OrderType - break // Found exact match, no need to continue + case RateSideSell: + if !pot.FixedSellRate.IsZero() { + return pot.FixedSellRate } - if result.AllSkippedDueToStuck && result.CurrencyCode != "" { - anySkippedDueToStuck = true - currencyForStuck = result.CurrencyCode + if !currency.MarketSellRate.IsZero() { + return currency.MarketSellRate.Add(pot.FloatingSellDelta).RoundBank(2) } + } + return decimal.Zero +} - // Track the best available rate for logging purposes - if result.Rate.GreaterThan(bestRate) { - bestRate = result.Rate +func amountInRangeForPublicQuote(pot *ent.ProviderOrderToken, amount decimal.Decimal, isOTC bool) bool { + if isOTC { + return !amount.LessThan(pot.MinOrderAmountOtc) && !amount.GreaterThan(pot.MaxOrderAmountOtc) + } + if amount.GreaterThan(pot.MaxOrderAmount) { + if pot.MinOrderAmountOtc.IsZero() || pot.MaxOrderAmountOtc.IsZero() { + return false } + return !amount.LessThan(pot.MinOrderAmountOtc) && !amount.GreaterThan(pot.MaxOrderAmountOtc) } + return !amount.LessThan(pot.MinOrderAmount) && !amount.GreaterThan(pot.MaxOrderAmount) +} - // If no exact match found, try fallback provider (if configured) even though it's not on the bucket queue - if !foundExactMatch { - if fallbackID := config.OrderConfig().FallbackProviderID; fallbackID != "" { - fallbackResult, fallbackErr := validateProviderRate(ctx, token, currency, amount, fallbackID, networkIdentifier, side) - if fallbackErr == nil { - // Quote the queue's best rate when amount was below/above queue providers' min/max but fallback accepts it - if bestRate.GreaterThan(decimal.Zero) { - return RateValidationResult{ - Rate: bestRate, - ProviderID: fallbackResult.ProviderID, - OrderType: fallbackResult.OrderType, - }, nil - } - return fallbackResult, nil - } - var errStuck *types.ErrNoProviderDueToStuck - if errors.As(fallbackErr, &errStuck) { - return RateValidationResult{}, fallbackErr +func tryFallbackPublicQuote(ctx context.Context, token *ent.Token, currency *ent.FiatCurrency, amount decimal.Decimal, networkIdentifier string, side RateSide, bestRate decimal.Decimal, anySkippedDueToStuck bool, currencyForStuck string) (RateValidationResult, error) { + if fallbackID := config.OrderConfig().FallbackProviderID; fallbackID != "" { + fallbackResult, fallbackErr := validateProviderRate(ctx, token, currency, amount, fallbackID, networkIdentifier, side) + if fallbackErr == nil { + if bestRate.GreaterThan(decimal.Zero) { + return RateValidationResult{ + Rate: bestRate, + ProviderID: fallbackResult.ProviderID, + OrderType: fallbackResult.OrderType, + }, nil } + return fallbackResult, nil } - if anySkippedDueToStuck && currencyForStuck != "" { - return RateValidationResult{}, &types.ErrNoProviderDueToStuck{CurrencyCode: currencyForStuck} + var errStuck *types.ErrNoProviderDueToStuck + if errors.As(fallbackErr, &errStuck) { + return RateValidationResult{}, fallbackErr } - logger.WithFields(logger.Fields{ - "Token": token.Symbol, - "Currency": currency.Code, - "Amount": amount, - "NetworkFilter": networkIdentifier, - "BestRate": bestRate, - }).Warnf("ValidateRate.NoSuitableProvider: no provider found for the given parameters") - - // Provide more specific error message (buy = fiat to crypto, sell = crypto to fiat) - networkMsg := networkIdentifier - if networkMsg == "" { - networkMsg = "any network" - } - from, to := token.Symbol, currency.Code - if side == RateSideBuy { - from, to = currency.Code, token.Symbol - } - return RateValidationResult{}, fmt.Errorf("no provider available for %s to %s conversion with amount %s on %s", - from, to, amount, networkMsg) } - - return RateValidationResult{ - Rate: bestRate, - ProviderID: selectedProviderID, - OrderType: selectedOrderType, - }, nil -} - -// parseBucketKey parses and validates bucket key format -type BucketData struct { - Currency string - MinAmount decimal.Decimal - MaxAmount decimal.Decimal -} - -func parseBucketKey(key string) (*BucketData, error) { - // Expected format: "bucket_{currency}_{minAmount}_{maxAmount}_{side}" - parts := strings.Split(key, "_") - if len(parts) != 4 && len(parts) != 5 { - return nil, fmt.Errorf("invalid bucket key format: expected 4 or 5 parts, got %d", len(parts)) - } - - if parts[0] != "bucket" { - return nil, fmt.Errorf("invalid bucket key prefix: expected 'bucket', got '%s'", parts[0]) - } - - currency := parts[1] - if currency == "" { - return nil, fmt.Errorf("empty currency in bucket key") - } - - minAmount, err := decimal.NewFromString(parts[2]) - if err != nil { - return nil, fmt.Errorf("invalid min amount '%s': %v", parts[2], err) - } - - maxAmount, err := decimal.NewFromString(parts[3]) - if err != nil { - return nil, fmt.Errorf("invalid max amount '%s': %v", parts[3], err) - } - - if minAmount.GreaterThanOrEqual(maxAmount) { - return nil, fmt.Errorf("min amount (%s) must be less than max amount (%s)", minAmount, maxAmount) + if anySkippedDueToStuck && currencyForStuck != "" { + return RateValidationResult{}, &types.ErrNoProviderDueToStuck{CurrencyCode: currencyForStuck} + } + logger.WithFields(logger.Fields{ + "Token": token.Symbol, + "Currency": currency.Code, + "Amount": amount, + "NetworkFilter": networkIdentifier, + "BestRate": bestRate, + }).Warnf("ValidateRate.NoSuitableProvider: no provider found for the given parameters") + networkMsg := networkIdentifier + if networkMsg == "" { + networkMsg = "any network" + } + from, to := token.Symbol, currency.Code + if side == RateSideBuy { + from, to = currency.Code, token.Symbol } - - // If there's a 5th part, it should be "buy" or "sell" (side), but we ignore it for parsing - // as the side is already known from the key pattern - - return &BucketData{ - Currency: currency, - MinAmount: minAmount, - MaxAmount: maxAmount, - }, nil -} - -// ProviderRateResult contains the result of finding a suitable provider rate -type ProviderRateResult struct { - Rate decimal.Decimal - ProviderID string - OrderType paymentorder.OrderType - Found bool - AllSkippedDueToStuck bool // true when no match because every considered provider was skipped due to stuck threshold - CurrencyCode string // set when AllSkippedDueToStuck is true, for 503 response + return RateValidationResult{}, fmt.Errorf("no provider available for %s to %s conversion with amount %s on %s", + from, to, amount, networkMsg) } -// GetProviderStuckOrderCount returns the number of stuck orders for a provider (status=fulfilled, pending fulfillment, updated_at <= now - OrderRefundTimeout, regular only). -// Used by both services/priority_queue and rate validation in this package. -func GetProviderStuckOrderCount(ctx context.Context, providerID string) (int, error) { +// validatePublicQuoteRate walks public ProviderOrderToken rows using DB ordering for quotes: +// score DESC, recent 24h successful fiat volume ASC, id ASC (no last_order_assigned — stable vs assignment rotation). +func validatePublicQuoteRate(ctx context.Context, token *ent.Token, currency *ent.FiatCurrency, amount decimal.Decimal, networkIdentifier string, side RateSide) (RateValidationResult, error) { orderConf := config.OrderConfig() - if orderConf.ProviderStuckFulfillmentThreshold <= 0 { - return 0, nil - } - cutoff := time.Now().Add(-orderConf.OrderRefundTimeout) - count, err := storage.Client.PaymentOrder.Query(). + q := storage.Client.ProviderOrderToken.Query(). Where( - paymentorder.StatusEQ(paymentorder.StatusFulfilled), - paymentorder.OrderTypeEQ(paymentorder.OrderTypeRegular), - paymentorder.UpdatedAtLTE(cutoff), - paymentorder.HasProviderWith(providerprofile.IDEQ(providerID)), - paymentorder.HasFulfillmentsWith( - paymentorderfulfillment.ValidationStatusEQ(paymentorderfulfillment.ValidationStatusPending), + providerordertoken.HasCurrencyWith(fiatcurrency.IDEQ(currency.ID)), + providerordertoken.HasTokenWith(tokenEnt.IDEQ(token.ID)), + providerordertoken.SettlementAddressNEQ(""), + providerordertoken.HasProviderWith( + providerprofile.IsActive(true), + providerprofile.VisibilityModeEQ(providerprofile.VisibilityModePublic), ), - ). - Count(ctx) + ) + if networkIdentifier != "" { + q = q.Where(providerordertoken.NetworkEQ(networkIdentifier)) + } + if orderConf.FallbackProviderID != "" { + q = q.Where(providerordertoken.HasProviderWith(providerprofile.IDNEQ(orderConf.FallbackProviderID))) + } + pots, err := q.WithProvider().All(ctx) if err != nil { - return 0, err + logger.WithFields(logger.Fields{"Error": err.Error()}).Errorf("ValidateRate: candidate query failed") + return RateValidationResult{}, fmt.Errorf("internal server error") + } + if len(pots) == 0 { + return tryFallbackPublicQuote(ctx, token, currency, amount, networkIdentifier, side, decimal.Zero, false, "") } - return count, nil -} - -// findSuitableProviderRate finds the first suitable provider rate from the provider list -// Returns the rate, provider ID, order type, and a boolean indicating if an exact match was found -// An exact match means: amount within limits, within bucket range, and provider has sufficient balance. -// For onramp (RateSideBuy) balance is token; for offramp (RateSideSell) balance is fiat. -func findSuitableProviderRate(ctx context.Context, providers []string, token *ent.Token, networkIdentifier string, tokenAmount decimal.Decimal, bucketData *BucketData, side RateSide) ProviderRateResult { - tokenSymbol := token.Symbol - var bestRate decimal.Decimal - var foundExactMatch bool - var considered, skippedDueToStuck int - orderConf := config.OrderConfig() - - // Track reasons for debugging when no match is found - var skipReasons []string - for _, providerData := range providers { - parts := strings.Split(providerData, ":") - if len(parts) != 6 { - logger.WithFields(logger.Fields{ - "ProviderData": providerData, - "Token": tokenSymbol, - "Currency": bucketData.Currency, - "MinAmount": bucketData.MinAmount, - "MaxAmount": bucketData.MaxAmount, - }).Errorf("ValidateRate.InvalidProviderData: provider data format is invalid") + provSeen := make(map[string]struct{}) + var provIDs []string + for _, pot := range pots { + pid := pot.Edges.Provider.ID + if _, ok := provSeen[pid]; ok { continue } - - // Skip entry if token doesn't match - if parts[1] != tokenSymbol { - continue + provSeen[pid] = struct{}{} + provIDs = append(provIDs, pid) + } + volMap, volErr := quoteRecentFiatVolumeByProvider(ctx, provIDs) + if volErr != nil { + logger.WithFields(logger.Fields{"Error": volErr.Error()}).Warnf("ValidateRate: recent volume query failed; using zero volume") + volMap = map[string]decimal.Decimal{} + } + slices.SortStableFunc(pots, func(a, b *ent.ProviderOrderToken) int { + if c := b.Score.Cmp(a.Score); c != 0 { + return c } - - // Skip entry if network doesn't match (network is in the queue payload) - if networkIdentifier != "" && parts[2] != networkIdentifier { - continue + va := volMap[a.Edges.Provider.ID] + vb := volMap[b.Edges.Provider.ID] + if c := va.Cmp(vb); c != 0 { + return c } - - // Fetch provider order token for OTC limits check - var providerOrderToken *ent.ProviderOrderToken - if networkIdentifier != "" { - // Network filter provided - fetch with network constraint - potQuery := storage.Client.ProviderOrderToken. - Query(). - Where( - providerordertoken.HasProviderWith( - providerprofile.IDEQ(parts[0]), - providerprofile.HasProviderBalancesWith( - providerbalances.IsAvailableEQ(true), - ), - ), - providerordertoken.HasTokenWith(tokenEnt.SymbolEQ(parts[1])), - providerordertoken.HasCurrencyWith(fiatcurrency.CodeEQ(bucketData.Currency)), - providerordertoken.NetworkEQ(networkIdentifier), - providerordertoken.SettlementAddressNEQ(""), - ) - if side == RateSideBuy { - potQuery = potQuery.Where( - providerordertoken.HasProviderWith( - providerprofile.HasProviderBalancesWith( - providerbalances.HasTokenWith(tokenEnt.IDEQ(token.ID)), - providerbalances.IsAvailableEQ(true), - ), - ), - ) - } else { - potQuery = potQuery.Where( - providerordertoken.HasProviderWith( - providerprofile.HasProviderBalancesWith( - providerbalances.HasFiatCurrencyWith(fiatcurrency.CodeEQ(bucketData.Currency)), - providerbalances.IsAvailableEQ(true), - ), - ), - ) - } - pot, err := potQuery.Only(ctx) - if err != nil { - if ent.IsNotFound(err) { - continue - } - logger.WithFields(logger.Fields{ - "ProviderData": providerData, - "Error": err, - }).Errorf("ValidateRate.InvalidProviderData: failed to fetch provider configuration") - continue - } - providerOrderToken = pot - } else { - // No network filter - fetch first matching entry - potQuery := storage.Client.ProviderOrderToken. - Query(). - Where( - providerordertoken.HasProviderWith( - providerprofile.IDEQ(parts[0]), - providerprofile.HasProviderBalancesWith( - providerbalances.IsAvailableEQ(true), - ), - ), - providerordertoken.HasTokenWith(tokenEnt.SymbolEQ(parts[1])), - providerordertoken.HasCurrencyWith(fiatcurrency.CodeEQ(bucketData.Currency)), - providerordertoken.SettlementAddressNEQ(""), - ) - if side == RateSideBuy { - potQuery = potQuery.Where( - providerordertoken.HasProviderWith( - providerprofile.HasProviderBalancesWith( - providerbalances.HasTokenWith(tokenEnt.IDEQ(token.ID)), - providerbalances.IsAvailableEQ(true), - ), - ), - ) - } else { - potQuery = potQuery.Where( - providerordertoken.HasProviderWith( - providerprofile.HasProviderBalancesWith( - providerbalances.HasFiatCurrencyWith(fiatcurrency.CodeEQ(bucketData.Currency)), - providerbalances.IsAvailableEQ(true), - ), - ), - ) - } - pot, err := potQuery.First(ctx) - if err != nil { - if ent.IsNotFound(err) { - continue - } - logger.WithFields(logger.Fields{ - "ProviderData": providerData, - "Error": err, - }).Errorf("ValidateRate.InvalidProviderData: failed to fetch provider configuration") - continue - } - providerOrderToken = pot + if a.ID < b.ID { + return -1 + } + if a.ID > b.ID { + return 1 } + return 0 + }) - // Parse provider order amounts - minOrderAmount, err := decimal.NewFromString(parts[4]) - if err != nil { - logger.WithFields(logger.Fields{ - "ProviderData": providerData, - "Error": err, - }).Errorf("ValidateRate.InvalidMinOrderAmount: failed to parse min order amount") + var bestRate decimal.Decimal + var consideredStuck, skippedStuck int + + for _, pot := range pots { + ot := DetermineOrderType(pot, amount) + isOTC := ot == paymentorder.OrderTypeOtc + if !amountInRangeForPublicQuote(pot, amount, isOTC) { continue } - - maxOrderAmount, err := decimal.NewFromString(parts[5]) - if err != nil { - logger.WithFields(logger.Fields{ - "ProviderData": providerData, - "Error": err, - }).Errorf("ValidateRate.InvalidMaxOrderAmount: failed to parse max order amount") + if amount.LessThan(pot.MinOrderAmount) { continue } - - // Parse rate early so we can track best queue rate even when skipping due to min/max - rate, err := decimal.NewFromString(parts[3]) - if err != nil { - logger.WithFields(logger.Fields{ - "ProviderData": providerData, - "Error": err, - "Value": parts[3], - }).Errorf("ValidateRate.InvalidRate: failed to parse rate") + rate := quoteRateForPublicCandidate(pot, side, currency) + if rate.IsZero() { continue } if rate.GreaterThan(bestRate) { bestRate = rate } - - // Check if order amount is within provider's regular min/max limits - // If not, check OTC limits as fallback - if tokenAmount.LessThan(minOrderAmount) { - // Amount below regular min - skip - skipReasons = append(skipReasons, fmt.Sprintf("amount %s below min %s", tokenAmount, minOrderAmount)) - continue - } else if tokenAmount.GreaterThan(maxOrderAmount) { - // Amount exceeds regular max - check OTC limits using already fetched providerOrderToken - // Check if token amount is within OTC limits - if providerOrderToken.MinOrderAmountOtc.IsZero() || providerOrderToken.MaxOrderAmountOtc.IsZero() { - // OTC limits not configured - skip - skipReasons = append(skipReasons, fmt.Sprintf("amount %s exceeds max %s, OTC limits not configured", tokenAmount, maxOrderAmount)) - continue - } - - if tokenAmount.LessThan(providerOrderToken.MinOrderAmountOtc) || tokenAmount.GreaterThan(providerOrderToken.MaxOrderAmountOtc) { - // Amount outside OTC limits - skip - skipReasons = append(skipReasons, fmt.Sprintf("amount %s outside OTC range [%s, %s]", tokenAmount, providerOrderToken.MinOrderAmountOtc, providerOrderToken.MaxOrderAmountOtc)) + pid := pot.Edges.Provider.ID + var balErr error + if side == RateSideBuy { + _, balErr = storage.Client.ProviderBalances.Query(). + Where( + providerbalances.HasProviderWith(providerprofile.IDEQ(pid)), + providerbalances.HasTokenWith(tokenEnt.IDEQ(token.ID)), + providerbalances.AvailableBalanceGT(amount), + providerbalances.IsAvailableEQ(true), + ). + Only(ctx) + } else { + fiatAmt := amount.Mul(rate) + _, balErr = storage.Client.ProviderBalances.Query(). + Where( + providerbalances.HasProviderWith(providerprofile.IDEQ(pid)), + providerbalances.HasFiatCurrencyWith(fiatcurrency.CodeEQ(currency.Code)), + providerbalances.AvailableBalanceGT(fiatAmt), + providerbalances.IsAvailableEQ(true), + ). + Only(ctx) + } + if balErr != nil { + if ent.IsNotFound(balErr) { continue } - - // Amount is within OTC limits - proceed to rate parsing + return RateValidationResult{}, fmt.Errorf("internal server error") } - - providerID := parts[0] - - // Calculate fiat equivalent of the token amount - fiatAmount := tokenAmount.Mul(rate) - - // Check if fiat amount is within the bucket range - if fiatAmount.GreaterThanOrEqual(bucketData.MinAmount) && fiatAmount.LessThanOrEqual(bucketData.MaxAmount) { - // Onramp: check token balance; offramp: check fiat balance - if side == RateSideBuy { - _, err = storage.Client.ProviderBalances.Query(). - Where( - providerbalances.HasProviderWith(providerprofile.IDEQ(providerID)), - providerbalances.HasTokenWith(tokenEnt.IDEQ(token.ID)), - providerbalances.AvailableBalanceGT(tokenAmount), - providerbalances.IsAvailableEQ(true), - ). - Only(ctx) - } else { - _, err = storage.Client.ProviderBalances.Query(). - Where( - providerbalances.HasProviderWith(providerprofile.IDEQ(providerID)), - providerbalances.HasFiatCurrencyWith(fiatcurrency.CodeEQ(bucketData.Currency)), - providerbalances.AvailableBalanceGT(fiatAmount), - providerbalances.IsAvailableEQ(true), - ). - Only(ctx) - } - if err != nil { - if ent.IsNotFound(err) { - if side == RateSideBuy { - skipReasons = append(skipReasons, fmt.Sprintf("provider %s has insufficient %s balance (need %s)", providerID, tokenSymbol, tokenAmount)) - } else { - skipReasons = append(skipReasons, fmt.Sprintf("provider %s has insufficient balance (need %s %s)", providerID, fiatAmount, bucketData.Currency)) - } - continue - } - return ProviderRateResult{Found: false} - } - - considered++ - if orderConf.ProviderStuckFulfillmentThreshold > 0 { - stuckCount, errStuck := GetProviderStuckOrderCount(ctx, providerID) - if errStuck == nil && stuckCount >= orderConf.ProviderStuckFulfillmentThreshold { - skippedDueToStuck++ - continue - } - } - - // Determine order type for this provider - orderType := DetermineOrderType(providerOrderToken, tokenAmount) - - // Provider has balance and amount is within bucket range - exact match - return ProviderRateResult{ - Rate: rate, - ProviderID: providerID, - OrderType: orderType, - Found: true, + if ot == paymentorder.OrderTypeRegular && orderConf.ProviderStuckFulfillmentThreshold > 0 { + consideredStuck++ + stuckCount, errStuck := GetProviderStuckOrderCount(ctx, pid) + if errStuck == nil && stuckCount >= orderConf.ProviderStuckFulfillmentThreshold { + skippedStuck++ + continue } } + return RateValidationResult{Rate: rate, ProviderID: pid, OrderType: ot}, nil + } - // Amount is outside bucket range - skip this provider - skipReasons = append(skipReasons, fmt.Sprintf("fiat amount %s outside bucket range [%s, %s]", fiatAmount, bucketData.MinAmount, bucketData.MaxAmount)) - continue + anySkippedDueToStuck := consideredStuck > 0 && skippedStuck == consideredStuck + currencyForStuck := "" + if anySkippedDueToStuck { + currencyForStuck = currency.Code } + return tryFallbackPublicQuote(ctx, token, currency, amount, networkIdentifier, side, bestRate, anySkippedDueToStuck, currencyForStuck) +} - // Return the best rate we found (even if no exact match) for logging purposes - // Log skip reasons for debugging if no match was found - if !foundExactMatch && len(skipReasons) > 0 { - maxReasons := 5 - if len(skipReasons) < maxReasons { - maxReasons = len(skipReasons) - } - logger.WithFields(logger.Fields{ - "Token": tokenSymbol, - "Amount": tokenAmount, - "SkipReasons": skipReasons[:maxReasons], // Log first 5 reasons - }).Debugf("ValidateRate.NoSuitableProvider: providers skipped due to limits/balance") +// StuckOrderCountsByProviderIDs returns stuck-order counts per provider (same criteria as GetProviderStuckOrderCount). +// Providers with no matching rows are omitted; callers should treat missing IDs as count 0. +func StuckOrderCountsByProviderIDs(ctx context.Context, providerIDs []string) (map[string]int, error) { + out := make(map[string]int) + orderConf := config.OrderConfig() + if orderConf.ProviderStuckFulfillmentThreshold <= 0 || len(providerIDs) == 0 { + return out, nil + } + cutoff := time.Now().Add(-orderConf.OrderRefundTimeout) + var rows []struct { + ProviderID string `json:"provider_profile_assigned_orders"` + Count int `json:"count"` } + err := storage.Client.PaymentOrder.Query(). + Where( + paymentorder.StatusEQ(paymentorder.StatusFulfilled), + paymentorder.OrderTypeEQ(paymentorder.OrderTypeRegular), + paymentorder.UpdatedAtLTE(cutoff), + paymentorder.HasProviderWith(providerprofile.IDIn(providerIDs...)), + paymentorder.HasFulfillmentsWith( + paymentorderfulfillment.ValidationStatusEQ(paymentorderfulfillment.ValidationStatusPending), + ), + ). + GroupBy(paymentorder.ProviderColumn). + Aggregate(ent.Count()). + Scan(ctx, &rows) + if err != nil { + return nil, err + } + for _, r := range rows { + out[r.ProviderID] = r.Count + } + return out, nil +} - allSkippedDueToStuck := considered > 0 && skippedDueToStuck == considered - return ProviderRateResult{ - Rate: bestRate, - Found: foundExactMatch, - AllSkippedDueToStuck: allSkippedDueToStuck, - CurrencyCode: bucketData.Currency, +// GetProviderStuckOrderCount returns the number of stuck orders for a provider (status=fulfilled, pending fulfillment, updated_at <= now - OrderRefundTimeout, regular only). +// Used by both services/priority_queue and rate validation in this package. +func GetProviderStuckOrderCount(ctx context.Context, providerID string) (int, error) { + if providerID == "" { + return 0, nil + } + m, err := StuckOrderCountsByProviderIDs(ctx, []string{providerID}) + if err != nil { + return 0, err } + return m[providerID], nil } // NormalizeMobileMoneyAccountIdentifier ensures the account identifier has a country dial code