Библиотека Groovy-скриптов

Data Export to CSV

beginner low risk Utilities

Description

Export data from SAP Commerce to CSV format with customizable fields and filters

Prerequisites

  • Data access permissions
  • CSV export format specification
  • File system write access

Parameters

dataType

String*

Type of data to export: users, products, orders, or custom

outputPath

String*

File path for CSV output

includeHeaders

Boolean

Include column headers in CSV

Default: true

fieldList

Collection

List of fields to include in export

Script Code

import de.hybris.platform.servicelayer.search.FlexibleSearchService
import java.io.FileWriter
import java.io.IOException

def dataType = parameters.dataType
def outputPath = parameters.outputPath
def includeHeaders = parameters.includeHeaders ?: true
def fieldList = parameters.fieldList

def errors = []
def exportedCount = 0

try {
    def query = ""
    def headers = []
    
    switch (dataType) {
        case 'users':
            query = "SELECT {pk} FROM {User}"
            headers = ['uid', 'name', 'email', 'creationtime']
            break
        case 'products':
            query = "SELECT {pk} FROM {Product}"
            headers = ['code', 'name', 'description', 'creationtime']
            break
        case 'orders':
            query = "SELECT {pk} FROM {Order}"
            headers = ['code', 'user', 'totalprice', 'creationtime']
            break
        default:
            errors.add("Unsupported data type: $dataType")
            return
    }
    
    // Use custom field list if provided
    if (fieldList && !fieldList.isEmpty()) {
        headers = fieldList
    }
    
    def results = flexibleSearchService.search(query).result
    
    def fileWriter = new FileWriter(outputPath)
    
    try {
        // Write headers if requested
        if (includeHeaders) {
            fileWriter.write(headers.join(','))
            fileWriter.write('\n')
        }
        
        // Write data rows
        results.each { item ->
            try {
                def row = []
                headers.each { field ->
                    def value = getFieldValue(item, field)
                    // Escape CSV values
                    if (value && value.toString().contains(',')) {
                        value = '"' + value.toString().replace('"', '""') + '"'
                    }
                    row.add(value ?: '')
                }
                
                fileWriter.write(row.join(','))
                fileWriter.write('\n')
                exportedCount++
                
            } catch (Exception e) {
                errors.add("Error processing item $item.pk: $e.message")
            }
        }
        
    } finally {
        fileWriter.close()
    }
    
    println "Exported $exportedCount records to $outputPath"
    if (errors) {
        println "Errors encountered:"
        errors.each { println "  - $it" }
    }
    
} catch (Exception e) {
    errors.add("Data export failed: $e.message")
}

def getFieldValue(item, fieldName) {
    try {
        def field = item.getClass().getDeclaredField(fieldName)
        field.setAccessible(true)
        return field.get(item)
    } catch (Exception e) {
        // Try getter method
        try {
            def methodName = 'get' + fieldName.capitalize()
            def method = item.getClass().getMethod(methodName)
            return method.invoke(item)
        } catch (Exception ex) {
            return null
        }
    }
}

Script Information

Author:SAP Commerce Team
Execution Time:1-10 minutes
Rating:4.2/5
Downloads:850
Last Updated:2024-01-11
Version:1.1.0

Tags

export csv data utility file

Библиотека Groovy-скриптов

Полная коллекция Groovy-скриптов для разработки на SAP Commerce

Возможности

  • 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

Как использовать

  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.

Советы и лучшие практики

  • 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.

Вопросы и ответы

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.