Bibliothèque de scripts Groovy

Bulk Order Status Update

intermediate medium risk Order Management

Description

Update order statuses in bulk with validation and business rule checks

Prerequisites

  • Order status workflow definitions
  • Business rule validation
  • Backup of order data

Parameters

orderCodes

Collection*

Collection of order codes to update

newStatus

String*

New status to set for orders

validateTransition

Boolean

Validate status transition is allowed

Default: true

Script Code

import de.hybris.platform.core.model.order.OrderModel
import de.hybris.platform.servicelayer.search.FlexibleSearchService
import de.hybris.platform.servicelayer.model.ModelService
import de.hybris.platform.workflow.WorkflowProcessingService

def orderCodes = parameters.orderCodes
def newStatus = parameters.newStatus
def validateTransition = parameters.validateTransition ?: true

def errors = []
def updatedCount = 0

try {
    orderCodes.each { orderCode ->
        try {
            def order = flexibleSearchService.search("SELECT {pk} FROM {Order} WHERE {code} = ?code", 
                [code: orderCode]).result[0]
            
            if (!order) {
                errors.add("Order with code '$orderCode' not found")
                return
            }
            
            // Validate status transition if required
            if (validateTransition) {
                def currentStatus = order.status
                if (!isValidTransition(currentStatus, newStatus)) {
                    errors.add("Invalid status transition from '$currentStatus' to '$newStatus' for order $orderCode")
                    return
                }
            }
            
            // Update order status
            order.setStatus(newStatus)
            modelService.save(order)
            
            // Trigger workflow if needed
            if (shouldTriggerWorkflow(newStatus)) {
                // workflowProcessingService.startWorkflow(order, newStatus)
                println "Workflow triggered for order $orderCode"
            }
            
            updatedCount++
            
        } catch (Exception e) {
            errors.add("Error updating order '$orderCode': $e.message")
        }
    }
    
    println "Updated $updatedCount orders successfully"
    if (errors) {
        println "Errors encountered:"
        errors.each { println "  - $it" }
    }
    
} catch (Exception e) {
    errors.add("Bulk order status update failed: $e.message")
}

def isValidTransition(currentStatus, newStatus) {
    // Define valid status transitions
    def validTransitions = [
        'CREATED': ['CONFIRMED', 'CANCELLED'],
        'CONFIRMED': ['SHIPPED', 'CANCELLED'],
        'SHIPPED': ['DELIVERED', 'RETURNED'],
        'DELIVERED': ['COMPLETED', 'RETURNED']
    ]
    
    return validTransitions[currentStatus]?.contains(newStatus) ?: false
}

def shouldTriggerWorkflow(status) {
    def workflowStatuses = ['CONFIRMED', 'SHIPPED', 'DELIVERED']
    return workflowStatuses.contains(status)
}

Script Information

Author:SAP Commerce Team
Execution Time:2-6 minutes
Rating:4.4/5
Downloads:750
Last Updated:2024-01-08
Version:1.3.0

Tags

order status bulk workflow validation

Bibliothèque de scripts Groovy

Collection complète de scripts Groovy pour le développement SAP Commerce

Fonctionnalités

  • Curated library of Groovy scripts for SAP Commerce: FlexibleSearch queries, ImpEx generation, type-system introspection, OOTB business-logic tasks (orders, carts, catalogs, users) — copy-paste ready for HAC's groovy console
  • Categorized by use case: SAP query examples, batch update scripts, validation checks, migration helpers, debugging utilities — find the right starting point quickly
  • Each script includes inline comments explaining the SAP API calls (modelService, flexibleSearchService, etc.), required permissions, and rollback considerations — production-aware patterns
  • Syntax-highlighted output ready to paste into HAC (hac/console.zul/groovy), with line numbers preserved for debugging when the script throws
  • Side-by-side script + explanation: each example has a doc panel describing what it does, when to use it, what could go wrong, and how to adapt it to your project
  • Search and filter by SAP type, operation (read/write), or complexity level (beginner / intermediate / advanced) — narrow down 40+ scripts to the relevant 3-5
  • Copy individual scripts to clipboard or download as .groovy files for version control — each carries a header comment with attribution and version
  • Pure client-side: scripts are static content in the page bundle, no upload needed; safe to read on a sensitive machine without internet

Mode d'emploi

  1. Browse or search the library for a script matching your task — SAP query, batch update, type introspection, etc.
  2. Read the doc panel to understand what the script does, expected inputs, and any prerequisites.
  3. Copy the script to your clipboard.
  4. Paste into HAC's Groovy console (hac/console.zul → Groovy tab).
  5. For write scripts: ALWAYS run in a non-production environment first; the console executes immediately with full ModelService access.
  6. Adapt the script to your project: replace placeholder values (catalog name, product code, etc.) before running.

Conseils et bonnes pratiques

  • Always run read-only scripts first to verify the data state before any write operation.
  • For batch updates, prefer modelService.saveAll(list) over modelService.save(item) in a loop — vastly faster.
  • Use Cookie permissions in HAC to require fresh authentication before write operations — adds an explicit confirmation step.
  • Version-control your project-specific Groovy scripts in your repo, not in the library; centralized library is for shared patterns.
  • When debugging, add println statements at strategic points; HAC's Groovy console captures stdout to the output panel.

FAQ

Can I run these scripts directly in production?

Only the read-only scripts (FlexibleSearch queries, type introspection). Write scripts (modelService.save, batch updates) can corrupt your data if misconfigured — always test in a staging environment first. The library marks read-only scripts as "safe in production"; everything else requires the test-first discipline.

Do the scripts work on all SAP Commerce versions?

They target SAP Commerce 2105+. Older versions (1811, 1905) lack some APIs (e.g., new cart-service methods, updated tax handling). Each script's doc panel notes the minimum version. If you're on 1811, focus on the FlexibleSearch and type-introspection scripts — those work across all versions.

Why is my Groovy script throwing "ModelService not found"?

Inside HAC's console, services are auto-injected via Spring. If you see ModelService not found, check that you're in the Groovy tab (not Beanshell), that the import statements at top are correct, and that your hybris environment has loaded the model package. Reset HAC if needed.

Can these scripts be used in customer-facing flows?

No — they're for admin/dev tooling. For runtime code, you'd call the same APIs from a Spring bean (annotated with @Service), not via Groovy. The library is for one-off admin tasks, not for app-runtime logic.

How do I add my own scripts to the library?

The library is curated. For sharing project-specific scripts within your team, store them in your repo (typically under src/com/yourcompany/scripts/) and version them like other code. Personal scripts can be saved as .groovy files locally; this library shows community-vetted patterns.

Are the scripts free to use commercially?

Yes. The library content is provided under a permissive license (MIT/Apache-style) for use in your SAP Commerce projects without restriction. Attribution appears in the script header comment but is not required for use.

Why don't the scripts auto-rollback on error?

Groovy scripts in HAC run in a transaction by default (configurable). If the script throws, the transaction rolls back automatically. For multi-step scripts, wrap them in try/catch and call modelService.save() at the end so partial state isn't committed.

Is anything sent to a server when I copy a script?

No. The scripts are static content baked into the page bundle. We don't observe which scripts you copy or which patterns you use. Safe to browse on an air-gapped workstation.