# Conditional Data Icons

## Overview

When creating Data Objects in our data model. We can choose various icons and colors for that object. You can create various sets of icons and determine which to render by using conditional logic defined in JSON logic.

This guide explains how to write JSONlogic expressions for dynamic icon display in the Cloneable Cloud Platform. Icon conditionals allow you to display different icons based on the values of data object fields, providing visual feedback about data status in real-time.

## Table of Contents

1. [Basic Concepts](#basic-concepts)
2. [JSONlogic Syntax](#jsonlogic-syntax)
3. [Field Value Access](#field-value-access)
4. [Common Operators](#common-operators)
5. [Practical Examples](#practical-examples)
6. [Utility Industry Use Cases](#utility-industry-use-cases)
7. [Best Practices](#best-practices)
8. [Troubleshooting](#troubleshooting)

## Basic Concepts

### How Icon Conditionals Work

When you create a data object template with multiple icons, the system:

1. **Evaluates conditionals** in the order they appear
2. **Returns the first matching icon** where the conditional evaluates to `true`
3. **Falls back to default icon** if no conditionals match
4. **Uses the first icon** as final fallback

### Icon Configuration Structure

```json
{
  "id": "unique-icon-id",
  "name": "Icon Name",
  "encoded": "data:image/svg+xml;base64,PHN3ZnPg==",
  "icon_key": "house",
  "fill_color": "green",
  "stoke_color": "black",
  "conditional": "{\"==\":[{\"var\":\"status\"},\"completed\"]}"
}
```

### Default vs Conditional Icons

* **Default icons**: No conditional or empty conditional (`{}` or `""`)
* **Conditional icons**: Have a valid JSONlogic expression in the `conditional` field

## JSONlogic Syntax

JSONlogic uses JSON objects to represent logical expressions. The basic structure is:

```json
{
  "operator": [operand1, operand2, ...]
}
```

### Basic Structure Examples

```json
// Simple equality check
{"==": [{"var": "status"}, "completed"]}

// Logical AND
{"and": [
  {"!=": [{"var": "done"}, null]},
  {"==": [{"var": "done"}, "true"]}
]}

// Logical OR
{"or": [
  {"==": [{"var": "priority"}, "high"]},
  {"==": [{"var": "urgent"}, "true"]}
]}
```

## Field Value Access

### Accessing Field Values

Use the `var` operator to access field values from your data object:

```json
{"var": "field_name"}
```

### Important Notes About Field Values

* **String values**: Simple values like `"true"`, `"false"`, numbers are kept as strings
* **JSON objects**: Complex values starting with `{` or `[` are parsed as JSON
* **Null handling**: Use `null` (not `"null"`) in conditionals for null checks

### Example Field Value Processing

```javascript
// Data object field values are processed as:
{
  "status": "completed",           // String - stays as string
  "priority": "1",                 // Number - stays as string
  "done": "true",                  // Boolean - stays as string
  "measurements": "[1,2,3]",       // JSON array - parsed to [1,2,3]
  "config": "{\"key\":\"value\"}"  // JSON object - parsed to {key: "value"}
}
```

## Common Operators

### Comparison Operators

```json
// Equality
{"==": [{"var": "status"}, "completed"]}

// Inequality
{"!=": [{"var": "status"}, "pending"]}

// Greater than
{">": [{"var": "priority"}, "2"]}

// Less than
{"<": [{"var": "score"}, "50"]}

// Greater than or equal
{">=": [{"var": "confidence"}, "0.8"]}

// Less than or equal
{"<=": [{"var": "attempts"}, "3"]}
```

### Logical Operators

```json
// AND - all conditions must be true
{"and": [
  {"==": [{"var": "status"}, "completed"]},
  {"!=": [{"var": "errors"}, null]}
]}

// OR - at least one condition must be true
{"or": [
  {"==": [{"var": "priority"}, "high"]},
  {"==": [{"var": "urgent"}, "true"]}
]}

// NOT - negates the result
{"!": [{"==": [{"var": "archived"}, "true"]}]}
```

### Null and Existence Checks

```json
// Check if field exists and is not null
{"!=": [{"var": "measurements"}, null]}

// Check if field is null or doesn't exist
{"==": [{"var": "measurements"}, null]}

// Check if field exists (including empty strings)
{"!=": [{"var": "field_name"}, null]}
```

### Array and Object Operations

```json
// Check if array contains value
{"in": ["completed", {"var": "status_history"}]}

// Check array length
{">": [{"var": "attachments.length"}, 0]}

// Access nested object properties
{"==": [{"var": "config.enabled"}, true]}
```

## Practical Examples

### Example 1: Simple Status-Based Icons

```json
// Green checkmark for completed items
{"==": [{"var": "status"}, "completed"]}

// Red X for failed items
{"==": [{"var": "status"}, "failed"]}

// Yellow warning for in-progress items
{"==": [{"var": "status"}, "in_progress"]}

// Default gray icon for everything else
{}
```

### Example 2: Complex Multi-Condition Logic

```json
// High priority urgent items (red alert icon)
{"and": [
  {"==": [{"var": "priority"}, "high"]},
  {"==": [{"var": "urgent"}, "true"]}
]}

// Completed with measurements (green success icon)
{"and": [
  {"==": [{"var": "status"}, "completed"]},
  {"!=": [{"var": "measurements"}, null]},
  {">": [{"var": "confidence"}, "0.8"]}
]}

// Items needing attention (yellow warning icon)
{"or": [
  {"==": [{"var": "status"}, "review_needed"]},
  {"and": [
    {"==": [{"var": "status"}, "completed"]},
    {"<": [{"var": "confidence"}, "0.5"]}
  ]}
]}
```

### Example 3: Data Quality Indicators

```json
// Complete data (all required fields filled)
{"and": [
  {"!=": [{"var": "pole_height"}, null]},
  {"!=": [{"var": "measurements"}, null]},
  {"!=": [{"var": "images"}, null]},
  {">": [{"var": "confidence_score"}, "0.9"]}
]}

// Incomplete data (missing required fields)
{"or": [
  {"==": [{"var": "pole_height"}, null]},
  {"==": [{"var": "measurements"}, null]},
  {"==": [{"var": "images"}, null]}
]}

// Low confidence data (needs review)
{"and": [
  {"!=": [{"var": "measurements"}, null]},
  {"<": [{"var": "confidence_score"}, "0.7"]}
]}
```

## Utility Industry Use Cases

### Pull Inspection Status

```json
// Inspection completed successfully
{"and": [
  {"==": [{"var": "inspection_status"}, "completed"]},
  {"!=": [{"var": "pole_measurements"}, null]},
  {"!=": [{"var": "span_measurements"}, null]}
]}

// Inspection in progress
{"==": [{"var": "inspection_status"}, "in_progress"]}

// Inspection failed or needs rework
{"or": [
  {"==": [{"var": "inspection_status"}, "failed"]},
  {"==": [{"var": "needs_rework"}, "true"]}
]}
```

### Pole Condition Assessment

```json
// Pole in good condition
{"and": [
  {"!=": [{"var": "pole_condition"}, null]},
  {"==": [{"var": "pole_condition"}, "good"]},
  {"<": [{"var": "lean_angle"}, "3"]}
]}

// Pole needs attention
{"or": [
  {"==": [{"var": "pole_condition"}, "fair"]},
  {"and": [
    {">=": [{"var": "lean_angle"}, "3"]},
    {"<": [{"var": "lean_angle"}, "5"]}
  ]}
]}

// Pole requires immediate action
{"or": [
  {"==": [{"var": "pole_condition"}, "poor"]},
  {">=": [{"var": "lean_angle"}, "5"]},
  {"==": [{"var": "safety_concern"}, "true"]}
]}
```

### Project Progress Tracking

```json
// Project completed
{"and": [
  {"==": [{"var": "project_status"}, "completed"]},
  {"==": [{"var": "exported_to_katapult"}, "true"]}
]}

// Project in progress with good completion rate
{"and": [
  {"==": [{"var": "project_status"}, "in_progress"]},
  {">": [{"var": "completion_percentage"}, "75"]}
]}

// Project behind schedule
{"and": [
  {"==": [{"var": "project_status"}, "in_progress"]},
  {"<": [{"var": "completion_percentage"}, "50"]},
  {"<": [{"var": "days_remaining"}, "7"]}
]}
```

## Best Practices

### 1. Use Descriptive Icon Names

```json
// Good
{"name": "Inspection Complete - High Confidence"}

// Avoid
{"name": "Icon 1"}
```

### 2. Order Icons by Specificity

Place more specific conditions first, general conditions last:

```json
// 1. Most specific: High priority AND urgent
{"and": [{"==": [{"var": "priority"}, "high"]}, {"==": [{"var": "urgent"}, "true"]}]}

// 2. Moderately specific: Just high priority
{"==": [{"var": "priority"}, "high"]}

// 3. General: Any priority
{"!=": [{"var": "priority"}, null]}

// 4. Default: No conditional
{}
```

### 3. Handle Edge Cases

```json
// Check for field existence before comparison
{"and": [
  {"!=": [{"var": "status"}, null]},
  {"==": [{"var": "status"}, "completed"]}
]}
```

## Troubleshooting

### Common Issues

#### 1. Conditional Always Returns False

**Problem**: Icon never appears even when condition should be true

**Solutions**:

* Check field name spelling in `{"var": "field_name"}`
* Verify field value format (string vs parsed JSON)
* Add null check: `{"!=": [{"var": "field_name"}, null]}`

#### 2. JSON Parse Error

**Problem**: Invalid JSON syntax in conditional

**Solutions**:

* Use double quotes for all strings
* Escape quotes in nested JSON: `\"`
* Validate JSON with online tools

#### 3. Wrong Icon Displayed

**Problem**: Unexpected icon appears

**Solutions**:

* Check icon order (first match wins)
* Add more specific conditions
* Verify logical operators (`and` vs `or`)

#### 4. No Icon Displayed

**Problem**: No icon appears at all

**Solutions**:

* Ensure at least one icon has empty conditional (`{}`)
* Check icon encoding format
* Verify icon array is not empty

### Debug Examples

```json
// Debug: Log all field values
{"var": ""}  // Returns entire data object

// Debug: Check field existence
{"!=": [{"var": "field_name"}, null]}

// Debug: Multiple fallback conditions
{"or": [
  {"==": [{"var": "status"}, "completed"]},
  {"==": [{"var": "status"}, "done"]},
  {"==": [{"var": "status"}, "finished"]}
]}
```

### Validation Tools

Use these tools to validate your JSONlogic:

1. **JSON Validator**: Ensure valid JSON syntax
2. **JSONlogic Playground**: Test expressions online
3. **Browser Console**: Test with real data
4. **Icon Customizer**: Built-in validation in the platform

## Advanced Examples

### Complex Utility Workflows

```json
// Pole inspection with multiple criteria
{"and": [
  {"==": [{"var": "inspection_complete"}, "true"]},
  {"!=": [{"var": "pole_height"}, null]},
  {"!=": [{"var": "lean_measurements"}, null]},
  {"!=": [{"var": "attachment_count"}, null]},
  {">": [{"var": "image_count"}, "2"]},
  {"<": [{"var": "safety_score"}, "3"]}
]}

// Span measurement validation
{"and": [
  {"==": [{"var": "span_measured"}, "true"]},
  {"!=": [{"var": "sag_measurement"}, null]},
  {"!=": [{"var": "clearance_measurement"}, null]},
  {">": [{"var": "clearance_measurement"}, "15"]},
  {"<": [{"var": "sag_measurement"}, "10"]}
]}

// Project export readiness
{"and": [
  {"==": [{"var": "all_poles_inspected"}, "true"]},
  {"==": [{"var": "all_spans_measured"}, "true"]},
  {"==": [{"var": "quality_check_passed"}, "true"]},
  {"==": [{"var": "exported_to_katapult"}, "false"]}
]}
```

## Conclusion

JSONlogic provides powerful conditional logic for dynamic icon display in the Cloneable Cloud Platform. By following this guide, you can create sophisticated visual indicators that help utility workers quickly understand data status, quality, and progress at a glance.

Remember to:

* Start with simple conditions and build complexity gradually
* Test thoroughly with real data
* Use meaningful colors and icons
* Handle edge cases and null values
* Order conditions from most specific to most general

For additional support, refer to the test examples in the codebase or consult the JSONlogic documentation at jsonlogic.com.
