> ## Documentation Index
> Fetch the complete documentation index at: https://code.dcycle.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Examples & Workflows

> Practical automation examples and workflow patterns for the Dcycle CLI

<Note>
  **Early Access** - The Dcycle CLI is currently available for enterprise customers.
  [Contact us](/docs/support) to learn more about access.
</Note>

# Examples & Workflows

Learn how to automate operational data management with practical, production-ready examples.

## Featured Examples

<CardGroup cols={1}>
  <Card title="CI/CD Pipeline Integration" icon="rotate" href="/cli/examples/ci-cd-pipeline">
    Automate uploads with GitHub Actions, GitLab CI, and other CI/CD tools. Includes validation, notifications, and best practices for reliable pipelines.
  </Card>

  <Card title="Multi-Organization Consolidated Reporting" icon="sitemap" href="/cli/examples/multi-org-reporting">
    Generate consolidated sustainability reports across holdings, subsidiaries, and business units. Compare performance and track group-wide targets.
  </Card>

  <Card title="Logistics Data Automation" icon="truck" href="/cli/examples/logistics-automation">
    Daily automation for transport companies: upload trip data (viajes) and fuel consumption (consumos). Integration with TMS/ERP systems.
  </Card>
</CardGroup>

***

## Quick Start

### Interactive Login

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 1. Login with your browser
dcy auth login

# 2. List your organizations
dcy org list

# 3. Set active organization
dcy org set <your-org-id>

# 4. Explore your data
dcy facility list
dcy vehicle list
```

### API Key Login (for scripts and CI/CD)

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Set environment variables — no interactive login needed
export DCYCLE_API_KEY=dcy_live_abc123...
export DCYCLE_ORG_ID=550e8400-e29b-41d4-a716-446655440000
export DCYCLE_FORMAT=json

# Commands authenticate automatically
dcy facility list
dcy vehicle list
```

<Tip>
  API keys are created by organization admins in the Dcycle web interface
  under **Settings → API Keys**. Use them for CI/CD pipelines and scheduled scripts
  where interactive OAuth login isn't possible.
</Tip>

### Verify Setup

Run `dcy doctor` to check everything is configured correctly:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy doctor
```

Output:

```
CLI Health Check

  ✓ Config file — /home/jane/.config/dcy/config.yaml
  ✓ API host — https://api.dcycle.io (production)
  ✓ Authentication — API key
  ✓ Organization — Acme Corp (550e8400-...)
  ✓ API connectivity — authenticated as jane@company.com
  ✓ Version — 0.0.45 (latest)

All checks passed.
```

***

## Cross-Module Workflows

### Complete Data Import Pipeline

Use the guided import flow to upload CSV/Excel data with column mapping and validation:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
#!/bin/bash
set -euo pipefail

FACILITY_ID="550e8400-e29b-41d4-a716-446655440000"
FILE="invoices-q1-2025.xlsx"

# 1. Create import session
IMPORT_ID=$(dcy imports create \
  --template invoices \
  --file "$FILE" \
  --facility "$FACILITY_ID" \
  --format json | jq -r '.id')
echo "Import session: $IMPORT_ID"

# 2. Get AI-suggested column mapping
dcy imports suggest-mapping "$IMPORT_ID"

# 3. Review suggestions, then confirm
dcy imports confirm-mapping "$IMPORT_ID"

# 4. Validate rows against template rules
ERRORS=$(dcy imports validate "$IMPORT_ID" --format json | jq '.error_count')
if [ "$ERRORS" -gt 0 ]; then
  echo "Found $ERRORS validation errors — review and patch"
  dcy imports status "$IMPORT_ID"
  exit 1
fi

# 5. Submit for processing
dcy imports submit "$IMPORT_ID"
echo "Import submitted successfully"
```

### File Upload and Processing

Upload documents (invoices, contracts) and create records from extracted readings:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
#!/bin/bash
# Upload energy invoices and create records from parsed data

# Upload files
for pdf in invoices/*.pdf; do
  echo "Uploading $pdf..."
  FILE_ID=$(dcy file upload "$pdf" --format json | jq -r '.id')
  echo "  Uploaded: $FILE_ID"

  # Wait for processing, then check readings
  sleep 5
  READINGS=$(dcy file reading list --file-id "$FILE_ID" --format json)
  COUNT=$(echo "$READINGS" | jq 'length')

  if [ "$COUNT" -gt 0 ]; then
    READING_ID=$(echo "$READINGS" | jq -r '.[0].id')
    echo "  Found $COUNT reading(s), creating records from $READING_ID..."
    dcy file reading create-records "$READING_ID"
  else
    echo "  No readings found yet — check later with: dcy file reading list --file-id $FILE_ID"
  fi
done
```

### Employee Survey Campaign

Send mobility surveys and track completion:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Send surveys to a list of employees
dcy survey send alice@company.com bob@company.com carol@company.com

# Check who hasn't responded
dcy survey list --format json | jq '.[] | select(.status == "pending") | .email'

# Resend to non-respondents
PENDING=$(dcy survey list --format json | jq -r '.[] | select(.status == "pending") | .email')
if [ -n "$PENDING" ]; then
  dcy survey resend $PENDING
  echo "Resent surveys to $(echo "$PENDING" | wc -w) employees"
fi
```

### Project Setup with Tasks

Create a carbon footprint project and assign tasks to team members:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
#!/bin/bash

# Create project
PROJECT_ID=$(dcy project create \
  --name "2025 Carbon Footprint" \
  --type carbon \
  --start 2025-01-01 \
  --end 2025-12-31 \
  --due 2026-03-31 \
  --format json | jq -r '.id')

echo "Project created: $PROJECT_ID"

# Get team member IDs
MEMBERS=$(dcy member list --format json)
ADMIN_ID=$(echo "$MEMBERS" | jq -r '.[] | select(.role == "admin") | .id' | head -1)

# Create tasks
dcy project task create "$PROJECT_ID" \
  --title "Collect energy invoices" \
  --assigned-to "$ADMIN_ID" \
  --due 2025-06-30

dcy project task create "$PROJECT_ID" \
  --title "Upload fleet data" \
  --assigned-to "$ADMIN_ID" \
  --due 2025-06-30

dcy project task create "$PROJECT_ID" \
  --title "Verify Scope 3 purchases" \
  --assigned-to "$ADMIN_ID" \
  --due 2025-09-30

# List all tasks
dcy project task list "$PROJECT_ID"
```

***

## Data Extraction with jq

### Vehicle Fleet Analysis

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Count vehicles by fuel type
dcy vehicle list --format json | \
  jq 'group_by(.fuel) | map({fuel: .[0].fuel, count: length})'

# Find vehicles without plate numbers
dcy vehicle list --format json | \
  jq '.[] | select(.plate == "" or .plate == null) | {id, name}'

# Export plates for external validation
dcy vehicle list --format json | jq -r '.[].plate' > plates.txt
```

### Facility Data Export

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# List all facility names and locations
dcy facility list --format json | \
  jq '.[] | {name, country, city, postal_code}'

# Count facilities by country
dcy facility list --format json | \
  jq 'group_by(.country) | map({country: .[0].country, count: length}) | sort_by(.count) | reverse'

# Find facilities with CUPS codes (Spanish electricity)
dcy facility list --format json | \
  jq '.[] | select(.cups_list != null and (.cups_list | length) > 0) | {name, cups: .cups_list}'
```

### Invoice Status Report

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Get all invoices for a facility
FACILITY_ID=$(dcy facility list --format json | jq -r '.[0].id')

# List enabled invoices with emissions
dcy invoice list --facility-id "$FACILITY_ID" --format json | \
  jq '.[] | select(.enabled == true) | {supplier: .supplier_name, period: .period, tco2e: .emissions_tco2e}'
```

### Organization Hierarchy

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Show full org tree
dcy org tree

# Get all child org IDs for batch operations
dcy org tree --format json | jq -r '.. | .id? // empty' | sort -u
```

***

## Bulk Operations

### Bulk Delete with Filter

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Delete all vehicles matching a condition
dcy vehicle list --format json | \
  jq -r '.[] | select(.fuel == "unknown") | .id' > delete-ids.txt

echo "Will delete $(wc -l < delete-ids.txt) vehicles"

# Delete one by one (with confirmation skip)
while read -r id; do
  dcy vehicle delete "$id" --yes
done < delete-ids.txt
```

### Bulk Delete with ID File

For commands that support `delete-bulk`, pass a file with one ID per line:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Own workforce bulk delete
dcy own-workforce list --format json | \
  jq -r '.[] | select(.contract_end_date < "2024-01-01") | .id' > expired.txt

dcy own-workforce delete-bulk expired.txt --yes

# Sold product bulk delete
dcy sold-product delete-bulk product-ids.txt --yes
```

### Batch Vehicle Upload

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Download template
dcy vehicle upload --template > vehicles-template.csv

# Fill template with your data (use Excel or any CSV editor)
# Then upload
dcy vehicle upload vehicles.csv

# Verify
dcy vehicle list --format json | jq 'length'
```

***

## Scripting Best Practices

### Error Handling with Retry

<Note>
  `dcy` automatically retries transient failures (429, 502, 503, 504) with exponential backoff.
  Shell-level retry is only needed to restart after non-retryable errors like timeouts.
  See [Automatic Retry](/cli/configuration#automatic-retry) for details.
</Note>

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
upload_with_retry() {
    local file=$1
    local type=$2
    local max_attempts=3

    for attempt in $(seq 1 $max_attempts); do
        echo "Attempt $attempt/$max_attempts: Uploading $file..."
        if dcy logistics upload "$file" --type "$type"; then
            echo "Success"
            return 0
        fi
        echo "Failed, retrying in 30s..."
        sleep 30
    done
    echo "ERROR: Upload failed after $max_attempts attempts"
    return 1
}

upload_with_retry viajes.csv requests
upload_with_retry consumos.csv recharges
```

### Pagination Loop

Some commands return paginated results. Loop through all pages:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
#!/bin/bash
# Collect all own-workforce records across pages
PAGE=1
SIZE=100
ALL_RECORDS="[]"

while true; do
  BATCH=$(dcy own-workforce list --page $PAGE --size $SIZE --format json)
  COUNT=$(echo "$BATCH" | jq 'length')

  if [ "$COUNT" -eq 0 ]; then
    break
  fi

  ALL_RECORDS=$(echo "$ALL_RECORDS $BATCH" | jq -s '.[0] + .[1]')
  echo "Page $PAGE: fetched $COUNT records (total: $(echo "$ALL_RECORDS" | jq 'length'))"

  if [ "$COUNT" -lt "$SIZE" ]; then
    break
  fi
  PAGE=$((PAGE + 1))
done

echo "$ALL_RECORDS" > all-workforce.json
echo "Total records: $(jq 'length' all-workforce.json)"
```

### Conditional Logic Based on Data

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
#!/bin/bash
# Alert if any vehicle has missing fuel type

MISSING=$(dcy vehicle list --format json | \
  jq '[.[] | select(.fuel == null or .fuel == "")] | length')

if [ "$MISSING" -gt 0 ]; then
  echo "WARNING: $MISSING vehicles have no fuel type set"
  dcy vehicle list --format json | \
    jq -r '.[] | select(.fuel == null or .fuel == "") | "\(.id)\t\(.plate)\t\(.name)"'
  exit 1
fi

echo "All vehicles have fuel types configured"
```

### Logging and Audit Trail

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
#!/bin/bash
# Wrapper that logs all CLI operations
LOG_FILE="dcycle-operations-$(date +%Y-%m-%d).log"

dcy_log() {
  local cmd="dcy $*"
  echo "[$(date -Iseconds)] CMD: $cmd" >> "$LOG_FILE"

  if output=$(dcy "$@" 2>&1); then
    echo "[$(date -Iseconds)] OK" >> "$LOG_FILE"
    echo "$output"
  else
    echo "[$(date -Iseconds)] FAIL: $output" >> "$LOG_FILE"
    echo "$output" >&2
    return 1
  fi
}

# Use the wrapper
dcy_log vehicle list --format json
dcy_log facility list
```

***

## Debugging

### Verbose Mode

Use `--verbose` to see HTTP requests and responses:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Show full API communication
dcy vehicle list --verbose
```

Output on stderr:

```
→ GET https://api.dcycle.io/v1/vehicles?page=1&size=100
← 200 OK (245ms)
```

<Tip>
  Verbose output goes to stderr, so it won't interfere with JSON piped to other tools:

  ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
  dcy vehicle list --format json --verbose 2>debug.log | jq '.'
  ```
</Tip>

### Save Debug Output

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Capture debug info separately from data
dcy purchase list --verbose --format json 2>debug.log 1>purchases.json

# Review what API calls were made
cat debug.log
```

### Check CLI Version

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Current version
dcy version

# Check if update is available
dcy version --check
```

***

## Environment Variables Reference

All settings can be controlled via environment variables — useful for CI/CD, Docker containers, and cron jobs:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Authentication
export DCYCLE_API_KEY=dcy_live_abc123...       # API key (skips OAuth)

# Context
export DCYCLE_ORG_ID=550e8400-...              # Active organization
export DCYCLE_HOST=https://api.dcycle.io       # API host override

# Output
export DCYCLE_FORMAT=json                       # Default output format
export DCYCLE_VERBOSE=1                         # Enable verbose logging
export NO_COLOR=1                               # Disable ANSI colors

# Timeouts
export DCYCLE_TIMEOUT=60                        # HTTP timeout in seconds
```

Command-line flags always take precedence over environment variables.

***

## More Resources

<CardGroup cols={2}>
  <Card title="Automation Guide" icon="gears" href="/guides/automation/overview">
    Comprehensive automation patterns and strategies
  </Card>

  <Card title="MCP Server" icon="robot" href="/mcp/overview">
    AI-assisted analysis with Claude
  </Card>

  <Card title="Data Imports" icon="upload" href="/cli/imports">
    Guided CSV/Excel import with validation
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    REST API for custom integrations
  </Card>
</CardGroup>
