Skip to main content
PATCH
http://api.gu1.ai
/
transactions
/
:id
/
changeStatus
Change Transaction Status
curl --request PATCH \
  --url http://api.gu1.ai/transactions/:id/changeStatus \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --data '
{
  "status": "<string>"
}
'
{
  "success": true,
  "transaction": {},
  "statusChanged": {},
  "rulesResult": {}
}

Endpoint

Change Transaction Status

PATCH http://api.gu1.ai/transactions/:id/changeStatus
Updates the status of an existing transaction with automatic validation of state transitions and optional rule execution for real-time risk re-assessment. Features:
  • Automatic validation of status transitions (prevents invalid state changes)
  • State machine enforcement (open ↔ closed state rules)
  • Automatic execution of update rules with trigger_transaction_updated trigger
  • Transaction integrity protection
  • Comprehensive audit trail

Authentication

All requests must include an API key in the Authorization header:
Authorization: Bearer YOUR_API_KEY

Required Headers

Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

Path Parameters

id
string
required
The UUID of the transaction to updateType: string (uuid)

Request Body

status
string
required
New transaction status. Must be a valid status enum value.Valid Statuses:
  • CREATED - Transaction created (open state)
  • PROCESSING - Transaction being processed (open state)
  • SUSPENDED - Transaction temporarily suspended (open state)
  • SENT - Transaction sent/transmitted (closed state)
  • EXPIRED - Transaction expired (closed state)
  • DECLINED - Transaction declined/rejected (closed state)
  • REFUNDED - Transaction refunded/reversed (closed state)
  • SUCCESSFUL - Transaction completed successfully (closed state)
Type: enum - 'CREATED' | 'PROCESSING' | 'SUSPENDED' | 'SENT' | 'EXPIRED' | 'DECLINED' | 'REFUNDED' | 'SUCCESSFUL'

State Transition Rules

The endpoint enforces strict state transition rules to maintain transaction integrity:

Open States

States that allow further transitions:
  • CREATED
  • PROCESSING
  • SUSPENDED
  • SENT

Closed States

Final states that cannot transition to other states:
  • EXPIRED
  • DECLINED
  • REFUNDED
  • SUCCESSFUL

Transition Matrix

From StateTo StateAllowed?Note
CREATEDPROCESSINGβœ… YesNormal flow
CREATEDSUSPENDEDβœ… YesSuspend for review
CREATEDSUCCESSFULβœ… YesQuick approval
PROCESSINGSUSPENDEDβœ… YesSuspend during processing
PROCESSINGSUCCESSFULβœ… YesNormal completion
PROCESSINGDECLINEDβœ… YesReject during processing
SUSPENDEDPROCESSINGβœ… YesResume processing
SUSPENDEDSUCCESSFULβœ… YesApprove suspended transaction
SUSPENDEDDECLINEDβœ… YesReject suspended transaction
SUCCESSFULPROCESSING❌ NoCannot reopen closed transaction
DECLINEDPROCESSING❌ NoCannot reopen closed transaction
EXPIREDPROCESSING❌ NoCannot reopen closed transaction
REFUNDEDany❌ NoCannot change refunded transaction
SUCCESSFULDECLINED❌ NoCannot change between closed states
Key Rules:
  1. βœ… Open β†’ Open: Allowed (e.g., CREATED β†’ PROCESSING)
  2. βœ… Open β†’ Closed: Allowed (e.g., PROCESSING β†’ SUCCESSFUL)
  3. ❌ Closed β†’ Open: NOT Allowed (e.g., SUCCESSFUL β†’ PROCESSING)
  4. ❌ Closed β†’ Closed: NOT Allowed (e.g., DECLINED β†’ REFUNDED)

Update Rules Execution

When a transaction status is changed, the endpoint automatically:
  1. Validates the transition - Ensures the new status is valid and transition is allowed
  2. Updates the status - Changes the transaction status in the database
  3. Executes update rules - Runs all rules with trigger: 'updated' in their scope
  4. Updates risk score - Re-calculates risk based on rule results
  5. Returns updated transaction - Returns the complete transaction with new risk assessment

Rules Trigger

The endpoint uses the trigger_transaction_updated mode, which executes all rules configured with the updated trigger. Example rule scope configuration:
{
  "scope": {
    "triggers": ["updated"],
    "targetEntityTypes": ["transaction"]
  }
}

Complete Request Examples

Approve a Suspended Transaction

curl -X PATCH http://api.gu1.ai/transactions/550e8400-e29b-41d4-a716-446655440000/changeStatus \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "SUCCESSFUL"
  }'

Decline a Transaction Under Review

curl -X PATCH http://api.gu1.ai/transactions/550e8400-e29b-41d4-a716-446655440000/changeStatus \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "DECLINED"
  }'

Suspend a Transaction for Manual Review

curl -X PATCH http://api.gu1.ai/transactions/550e8400-e29b-41d4-a716-446655440000/changeStatus \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "SUSPENDED"
  }'

Response

Success Response (200 OK)

{
  "success": true,
  "transaction": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "externalId": "txn_12345",
    "type": "PAYMENT",
    "status": "SUCCESSFUL",
    "amount": 1500.00,
    "currency": "USD",
    "amountInUsd": 1500.00,
    "origin": {
      "entityId": "customer_001",
      "externalId": "EXT-001",
      "name": "John Doe",
      "country": "US",
      "details": {},
      "type": "person",
      "riskScore": 15.50
    },
    "destination": {
      "entityId": "merchant_002",
      "externalId": "MER-002",
      "name": "Electronics Store",
      "country": "US",
      "details": {},
      "type": "company",
      "riskScore": 8.20
    },
    "riskScore": 22.50,
    "riskFactors": [
      {
        "factor": "status_change",
        "score": 5,
        "description": "Transaction status changed to SUCCESSFUL"
      }
    ],
    "flagged": false,
    "description": "Laptop purchase",
    "category": "electronics",
    "metadata": {},
    "transactedAt": "2024-12-23T14:30:00.000Z",
    "createdAt": "2024-12-23T14:30:00.000Z",
    "updatedAt": "2024-12-23T15:45:00.000Z"
  },
  "statusChanged": {
    "from": "SUSPENDED",
    "to": "SUCCESSFUL"
  },
  "rulesResult": {
    "success": true,
    "executed": true,
    "rulesTriggered": 3,
    "executionTimeMs": 245,
    "result": {
      "entityId": "550e8400-e29b-41d4-a716-446655440000",
      "entityType": "transaction",
      "rulesExecuted": [
        {
          "ruleId": "rule_001",
          "ruleName": "High Value Transaction Check",
          "passed": true,
          "score": 5
        }
      ],
      "totalRules": 3,
      "successfulRules": 3,
      "failedRules": 0,
      "overallConfidence": 0.95,
      "riskScore": 22.50,
      "flags": []
    },
    "auditId": "audit_12345",
    "isNewAudit": false
  }
}

Response Fields

success
boolean
Whether the status change was successful
transaction
object
The updated transaction with all its data, including:
  • id (string) - Transaction UUID
  • status (string) - New transaction status
  • origin (object) - Origin party information (nested structure)
    • entityId (string) - Origin entity UUID
    • name (string) - Origin party name
    • country (string) - Origin country
    • details (object) - Additional origin details
    • type (string) - Origin entity type
    • riskScore (number) - Origin entity risk score
  • destination (object) - Destination party information (nested structure)
    • entityId (string) - Destination entity UUID
    • name (string) - Destination party name
    • country (string) - Destination country
    • details (object) - Additional destination details
    • type (string) - Destination entity type
    • riskScore (number) - Destination entity risk score
  • riskScore (number) - Updated risk score after re-evaluation
  • riskFactors (array) - Updated risk factors
  • flagged (boolean) - Updated flag status
  • updatedAt (string) - Timestamp of the update
statusChanged
object
Information about the status transition:
  • from (string) - Previous status
  • to (string) - New status
rulesResult
object
Complete result of update rules execution (RulesExecutionResult):
  • success (boolean) - Whether rules executed successfully
  • executed (boolean) - Whether any rules were executed
  • result (object | undefined) - Entity analysis result with rule execution details
  • rulesTriggered (number | undefined) - Number of rules that were executed
  • executionTimeMs (number | undefined) - Execution time in milliseconds
  • error (string | undefined) - Error message if execution failed
  • auditId (string | undefined) - Audit log ID
  • isNewAudit (boolean | undefined) - Whether a new audit was created
  • warnings (array | undefined) - Array of warning messages
  • metadata (object | undefined) - Additional metadata including coverage summary, missing fields, and recommendations

Error Responses

400 Bad Request - Invalid Status

{
  "error": "Invalid status",
  "validStatuses": [
    "CREATED",
    "PROCESSING",
    "SUSPENDED",
    "SENT",
    "EXPIRED",
    "DECLINED",
    "REFUNDED",
    "SUCCESSFUL"
  ]
}

400 Bad Request - Invalid Transition

{
  "error": "Cannot transition from closed status to open status",
  "currentStatus": "SUCCESSFUL",
  "requestedStatus": "PROCESSING",
  "message": "Transaction is in a closed state (SUCCESSFUL) and cannot be reopened"
}

404 Not Found

{
  "error": "Transaction not found"
}

401 Unauthorized

{
  "error": "Unauthorized",
  "message": "Invalid or missing API key"
}

500 Internal Server Error

{
  "error": "Failed to change transaction status",
  "details": "Internal server error message"
}

Use Cases

1. Manual Review Workflow

// Step 1: Suspend suspicious transaction
await changeStatus(transactionId, 'SUSPENDED');

// Step 2: Analyst reviews transaction
// ... manual review process ...

// Step 3: Approve or decline based on review
if (approved) {
  await changeStatus(transactionId, 'SUCCESSFUL');
} else {
  await changeStatus(transactionId, 'DECLINED');
}

2. Automated Compliance Check

// Transaction created with CREATED status
const transaction = await createTransaction({...});

// Run additional compliance checks
const complianceResult = await runComplianceChecks(transaction.id);

if (complianceResult.passed) {
  // Move to processing
  await changeStatus(transaction.id, 'PROCESSING');

  // Complete transaction
  await changeStatus(transaction.id, 'SUCCESSFUL');
} else {
  // Decline due to compliance issues
  await changeStatus(transaction.id, 'DECLINED');
}

3. Fraud Detection Response

// Monitor transaction updates
if (fraudDetected) {
  // Immediately suspend transaction
  await changeStatus(transactionId, 'SUSPENDED');

  // Create alert for investigation
  await createAlert({
    transactionId,
    type: 'fraud_suspected',
    severity: 'high'
  });

  // After investigation, take action
  if (confirmed) {
    await changeStatus(transactionId, 'DECLINED');
  } else {
    await changeStatus(transactionId, 'SUCCESSFUL');
  }
}

4. Bulk Status Updates

// Update multiple transactions in parallel
const suspendedTransactions = await getTransactionsByStatus('SUSPENDED');

const results = await Promise.allSettled(
  suspendedTransactions.map(async (txn) => {
    if (shouldApprove(txn)) {
      return await changeStatus(txn.id, 'SUCCESSFUL');
    } else if (shouldDecline(txn)) {
      return await changeStatus(txn.id, 'DECLINED');
    }
  })
);

console.log(`Updated ${results.filter(r => r.status === 'fulfilled').length} transactions`);

Best Practices

  1. Validate before changing - Always check the current status before attempting a status change to avoid unnecessary API calls
  2. Handle transition errors - Implement proper error handling for invalid transitions, as closed transactions cannot be reopened
  3. Use appropriate statuses - Choose the correct status that reflects the actual business state of the transaction
  4. Monitor rule execution - Pay attention to the rulesResult object to ensure update rules are triggering as expected and check execution details, warnings, and metadata
  5. Implement audit logging - Track all status changes in your system for compliance and debugging purposes
  6. Bulk updates - When updating multiple transactions, use Promise.allSettled() to continue processing even if some updates fail
  7. Webhook integration - Consider setting up webhooks to receive notifications when status changes trigger important rules
  8. Testing state transitions - Test all possible state transitions in your development environment before deploying to production