Files
fgueryandQuentin David a77f1fabef fix(EN-549): remove config and connector dependencies (#622)
* chore: rename RunNextTasks workflow

* feat: added a trimmed down type for connector only containing the id

* feat: make runNextTask use connectorIdOnly

* feat: added isScheduledForDeletion to plugin interface

* feat: add scheduledForDeletion at plugin level

* feat: refactor manager.Load to take a connector instead of parts of it

* feat: saves the connector's scheduledFOrDeletion into the plugin

* feat: use plugin.IsScheduledForDeletion instead of loading connector

* fix: make e2e tests less flaky

* fix: remove config from most request types

* feat: (WIP) remove config from runNextTask

* fix: remove unneeded method definitions in each plugin

* fix: simplify RunNextFlow as anyway we need to change the parameters

* fix: add a workflow compatible with previous version for runNextTasks

* fix(EN-577): added back RunSendEvents as a deprecated workflow

* fix(EN-577): added back RunUpdatePaymentInitiationFromPayment as a deprecated workflow

* fix: fix linting directives

* fix: replace old usage with refactored one

* fix: added back missing deprecated activities

* fix: ensure fetch_next_balance works with v3.0 code

* fix: simplify a bit the versionning etc

* fix: quick refactor before applying solution elsewhere

* fix: add back RunSendEvents and RunNextTask child workflows where necessary for backward compatibility

* fix: add back missing activity, seems like it's mandatory?

* fix: run payment initiation update as child workflow when necessary

* fix: missing activy call in test, refine some todos

* fix: lint

* fix: ensure we always reload plugins into the manager -- so exposing isScheduledForDeletion

* fix: ensure we stop storing clear config in temporal

* fix: make store config support plain text config

* fix: some comments

* fix: change runSendEvent workflow to be match what we had in 3.0

* feat: enable worker versionning to avoid workflow from new version to get executed on old code

* fix: lint

* fix: revert worker versionning

* fix: minor code review comments

* fix: add context to Encrypt & Decrypt methods

* fix: improve lint, add couple tests

* fix: use atomic to handle isScheduledForDeletion

* fix: make create_events work on migration

* fix: avoid returning channel; just send what is needed in runSendEventAsChildWorkflow and runNextTaskAsChildWorkflow

* fix: remove extra call to installWorkflow on start plugin

* fix: typo in error log line

* fix: simplify errChan initialization

* fix: clarify feature flag names
2026-01-19 14:35:36 +01:00

205 lines
5.7 KiB
Go

package workflow
import (
"errors"
"math/big"
"github.com/formancehq/go-libs/v3/bun/bunpaginate"
"github.com/formancehq/go-libs/v3/query"
"github.com/formancehq/payments/internal/connectors/engine/activities"
"github.com/formancehq/payments/internal/models"
"github.com/formancehq/payments/internal/storage"
"go.temporal.io/api/enums/v1"
"go.temporal.io/sdk/temporal"
"go.temporal.io/sdk/workflow"
)
var ErrPaymentInitiationNotProcessed = errors.New("payment initiation not processed")
type ValidateReverse struct {
ConnectorID models.ConnectorID
PI *models.PaymentInitiation
PIReversal *models.PaymentInitiationReversal
}
func (w Workflow) validateReverse(
ctx workflow.Context,
validateReverse ValidateReverse,
) error {
// First ensure that the payment initiation was processed successfully
err := w.validatePaymentInitiationProcessed(ctx, validateReverse)
if err != nil {
return err
}
err = w.validateReverseAmount(ctx, validateReverse)
if err != nil {
return err
}
err = w.validateOnlyReverse(ctx, validateReverse)
if err != nil {
return err
}
return nil
}
func (w Workflow) validateOnlyReverse(
ctx workflow.Context,
validateReverse ValidateReverse,
) error {
now := workflow.Now(ctx)
adj := models.PaymentInitiationAdjustment{
ID: models.PaymentInitiationAdjustmentID{
PaymentInitiationID: validateReverse.PIReversal.PaymentInitiationID,
CreatedAt: now,
Status: models.PAYMENT_INITIATION_ADJUSTMENT_STATUS_REVERSE_PROCESSING,
},
CreatedAt: now,
Status: models.PAYMENT_INITIATION_ADJUSTMENT_STATUS_REVERSE_PROCESSING,
Amount: validateReverse.PIReversal.Amount,
Asset: &validateReverse.PI.Asset,
Metadata: validateReverse.PIReversal.Metadata,
}
// Second, ensure that we do not have another reverse currently being processed
inserted, err := activities.StoragePaymentInitiationsAdjustmentsIfPredicateStore(
infiniteRetryContext(ctx),
adj,
[]models.PaymentInitiationAdjustmentStatus{
models.PAYMENT_INITIATION_ADJUSTMENT_STATUS_REVERSE_PROCESSING,
},
)
if err != nil {
return err
}
if !inserted {
err = errors.New("another reverse is already in progress")
return temporal.NewNonRetryableApplicationError(err.Error(), "ANOTHER_REVERSE_IN_PROGRESS", err)
}
// Payment initiation adjustment events are now sent via outbox pattern in PaymentInitiationAdjustmentsUpsertIfPredicate
// (unless it's a rerun from a previous version, in which case -- )
if !IsEventOutboxPatternEnabled(ctx) {
if err := workflow.ExecuteChildWorkflow(
workflow.WithChildOptions(
ctx,
workflow.ChildWorkflowOptions{
TaskQueue: w.getDefaultTaskQueue(),
ParentClosePolicy: enums.PARENT_CLOSE_POLICY_ABANDON,
SearchAttributes: map[string]interface{}{
SearchAttributeStack: w.stack,
},
},
),
RunSendEvents, //nolint:staticcheck // ignore deprecation
SendEvents{
PaymentInitiationAdjustment: &adj,
},
).Get(ctx, nil); err != nil {
return err
}
}
return nil
}
func (w Workflow) validatePaymentInitiationProcessed(
ctx workflow.Context,
validateReverse ValidateReverse,
) error {
query := storage.NewListPaymentInitiationAdjustmentsQuery(
bunpaginate.NewPaginatedQueryOptions(storage.PaymentInitiationAdjustmentsQuery{}).
WithPageSize(1).
WithQueryBuilder(query.Match("status", models.PAYMENT_INITIATION_ADJUSTMENT_STATUS_PROCESSED.String())),
)
adjustments, err := activities.StoragePaymentInitiationAdjustmentsList(
infiniteRetryContext(ctx),
models.PaymentInitiationID(validateReverse.PIReversal.PaymentInitiationID),
query,
)
if err != nil {
return err
}
if len(adjustments.Data) > 0 {
// Payment initiation has been processed
return nil
}
return temporal.NewNonRetryableApplicationError("no adjustments found", "PAYMENT_INITIATION_NOT_PROCESSED", ErrPaymentInitiationNotProcessed)
}
func (w Workflow) validateReverseAmount(
ctx workflow.Context,
validateReverse ValidateReverse,
) error {
amount := validateReverse.PI.Amount
query := storage.NewListPaymentInitiationAdjustmentsQuery(
bunpaginate.NewPaginatedQueryOptions(storage.PaymentInitiationAdjustmentsQuery{}).
WithPageSize(100).
WithQueryBuilder(query.Match("status", models.PAYMENT_INITIATION_ADJUSTMENT_STATUS_REVERSED.String())),
)
amountReversed := big.NewInt(0)
for {
adjs, err := activities.StoragePaymentInitiationAdjustmentsList(
infiniteRetryContext(ctx),
validateReverse.PI.ID,
query,
)
if err != nil {
return err
}
for _, adj := range adjs.Data {
amountReversed.Add(amountReversed, adj.Amount)
}
if !adjs.HasMore {
break
}
err = bunpaginate.UnmarshalCursor(adjs.Next, &query)
if err != nil {
return err
}
}
currentAmount := new(big.Int).Sub(amount, amountReversed)
nextAmount := new(big.Int).Sub(currentAmount, validateReverse.PIReversal.Amount)
switch nextAmount.Sign() {
case -1:
// we are in the negative, we cannot reverse more than the amount
err := errors.New("cannot reverse more than the amount")
return temporal.NewNonRetryableApplicationError(err.Error(), "CANNOT_REVERSE_MORE_THAN_AMOUNT", err)
default:
return nil
}
}
func (w Workflow) addPIReversalAdjustment(
ctx workflow.Context,
adjustmentID models.PaymentInitiationReversalAdjustmentID,
err error,
metadata map[string]string,
) error {
adj := models.PaymentInitiationReversalAdjustment{
ID: adjustmentID,
PaymentInitiationReversalID: adjustmentID.PaymentInitiationReversalID,
CreatedAt: workflow.Now(ctx),
Status: adjustmentID.Status,
Error: err,
Metadata: metadata,
}
return activities.StoragePaymentInitiationReversalsAdjustmentsStore(
infiniteRetryContext(ctx),
adj,
)
}