# Basic Concepts

Understanding the core concepts behind Entity Builder.

## Definition-Centric Workflow

Entity Builder uses a **definition-centric** workflow where YAML files are first imported as reusable definitions, then applied to create Drupal entities.

```mermaid
flowchart LR
    YAML[YAML File] -->|Import| DEF[(EbDefinition)]
    DEF -->|Apply| Drupal[Drupal Entities]
    DEF -->|Export| YAML2[YAML File]
```

**Benefits:**

- Definitions can be applied multiple times
- Changes can be previewed before execution
- Full rollback support
- Audit trail of all operations

## Flat YAML Format

Unlike nested hierarchical formats, Entity Builder uses a **flat format** where each item (bundle, field, group) is a self-contained row.

**Flat Format (Entity Builder):**
```yaml
bundle_definitions:
  - entity_type: node
    bundle_id: article
    label: Article

field_definitions:
  - entity_type: node
    bundle: article
    field_name: field_body
    field_type: text_long
    label: Body
```

**Benefits:**

- Easy to edit in spreadsheets
- Simple copy/paste operations
- Clear dependencies
- No nesting confusion

## Automatic Dependency Resolution

Entity Builder automatically detects and orders operations based on dependencies:

```yaml
# You write in any order:
field_definitions:
  - entity_type: node
    bundle: article
    field_name: field_category
    field_type: entity_reference
    field_storage_settings:
      target_type: taxonomy_term

bundle_definitions:
  - entity_type: taxonomy_term
    bundle_id: category
    label: Category

  - entity_type: node
    bundle_id: article
    label: Article
```

**Entity Builder automatically reorders:**

1. `create_bundle taxonomy_term:category` (no dependencies)
2. `create_bundle node:article` (no dependencies)
3. `create_field field_category` (depends on both bundles)

### Detected Dependencies

| Source | Depends On |
|--------|------------|
| Field | Bundle it belongs to |
| Entity Reference Field | Target bundle |
| Display Configuration | Field it configures |
| Field Group | Bundle, display, child fields |
| Menu Link | Menu |

## Sync Mode

Sync mode enables **idempotent** imports - you can run the same YAML multiple times safely.

| Entity State | YAML State | Action |
|--------------|------------|--------|
| Missing | Defined | **Create** |
| Exists, different | Defined | **Update** |
| Exists, same | Defined | **Skip** |

**Example:**

First import:
```
✓ Create bundle node:article
✓ Create field field_body
✓ Create field field_image
```

Second import (no changes):
```
○ Skip bundle node:article (unchanged)
○ Skip field field_body (unchanged)
○ Skip field field_image (unchanged)
```

Third import (field label changed):
```
○ Skip bundle node:article (unchanged)
✓ Update field field_body (label changed)
○ Skip field field_image (unchanged)
```

## Two-Stage Validation

Entity Builder validates definitions in two stages:

### Stage 1: Operation Validation

Each operation validates its own requirements:

- `create_field`: Field type exists?
- `create_bundle`: Entity type supports bundles?
- `configure_form_mode`: Widget exists and compatible?

### Stage 2: Cross-Cutting Validation

Validator plugins check rules across all operations:

| Validator | Checks |
|-----------|--------|
| DependencyValidator | Entity/bundle/field existence |
| RequiredFieldsValidator | All required fields present |
| UniqueNameValidator | No naming conflicts |
| FieldTypeValidator | Field type plugin exists |
| WidgetCompatibilityValidator | Widget supports field type |
| FormatterCompatibilityValidator | Formatter supports field type |
| CircularDependencyValidator | No circular dependencies |

### Batch Context

Validators understand what will be created in the same batch:

```yaml
bundle_definitions:
  - entity_type: node
    bundle_id: article  # Created at index 0

field_definitions:
  - entity_type: node
    bundle: article     # References bundle at index 0 ✓
    field_name: field_body
```

The field can reference the bundle even though it doesn't exist yet - because it will be created in the same batch.

## Operations

Operations are the atomic units of work. Each operation does one thing.

### Core Operations

| Operation | Description |
|-----------|-------------|
| `create_bundle` | Create content type, vocabulary, media type |
| `update_bundle` | Update bundle settings |
| `delete_bundle` | Delete bundle |
| `create_field` | Create field storage and instance |
| `update_field` | Update field configuration |
| `delete_field` | Delete field |
| `hide_field` | Hide field from display |
| `reorder_fields` | Change field display order |
| `configure_form_mode` | Configure widget settings |
| `configure_view_mode` | Configure formatter settings |
| `create_menu` | Create custom menu |
| `create_menu_link` | Add menu link |

### Extension Operations

| Module | Operations |
|--------|------------|
| eb_field_group | `create_field_group`, `update_field_group`, `delete_field_group` |
| eb_pathauto | `create_pathauto_pattern` |
| eb_auto_entitylabel | `configure_auto_entitylabel` |

## Rollback Support

Every operation stores rollback data, enabling full undo:

```mermaid
flowchart TB
    Apply[Apply Definition] --> |Stores| RB[(EbRollback)]
    RB --> |Contains| OP1[Operation 1 Data]
    RB --> |Contains| OP2[Operation 2 Data]
    RB --> |Contains| OP3[Operation 3 Data]

    Rollback[Execute Rollback] --> |Reads| RB
    Rollback --> |Reverses| OP3
    Rollback --> |Reverses| OP2
    Rollback --> |Reverses| OP1
```

**Key Features:**

- Operations rolled back in reverse order
- Original data restored
- New entities deleted
- Rollbacks can be executed via UI or Drush

## Entity Types

### EbDefinition (Config Entity)

Stores the YAML definition data:

- `id` - Machine name
- `label` - Human-readable label
- `uid` - Owner user ID
- `bundle_definitions` - Bundle configurations
- `field_definitions` - Field configurations
- `application_status` - draft | applied | failed

**Storage:** Config sync directory (exported with `drush config:export`)

### EbRollback (Content Entity)

Tracks rollback operations:

- `definition_id` - Source definition
- `status` - pending | completed | failed
- `operation_count` - Number of operations

**Storage:** Database only (NOT exported)

### EbLog (Content Entity)

Audit trail for apply/rollback actions:

- `action` - apply | rollback | import
- `status` - pending | success | partial | failed
- `started` / `completed` - Timestamps

**Storage:** Database only

## Extension System

Extensions add functionality through plugins:

### What Extensions Provide

| Capability | Example |
|------------|---------|
| YAML keys | `field_group_definitions` |
| Operations | `create_field_group` |
| Dependencies | Field group depends on fields |
| Change detection | Compare with existing groups |
| Config extraction | Export existing groups |

### Available Extensions

| Extension | Adds |
|-----------|------|
| eb_field_group | Field groups, tabs, fieldsets |
| eb_pathauto | URL alias patterns |
| eb_auto_entitylabel | Automatic entity labels |

## Permissions

Entity Builder uses a tiered permission system:

### Tier 3: Administrator

| Permission | Description |
|------------|-------------|
| `administer entity builder` | Full administrative access to all features. |

### Tier 2: Privileged Operations

These permissions control high-impact operations that modify site structure:

| Permission | Description |
|------------|-------------|
| `apply entity definitions` | Apply definitions created in the UI. |
| `import entity architecture` | Import and apply YAML files (also grants apply). |
| `export entity architecture` | Export full site architecture to YAML. |
| `rollback entity operations` | Rollback previously executed operations. |

### Tier 1: User Permissions

Ownership-based permissions for self-service definition management:

| Permission | Description |
|------------|-------------|
| `create entity definitions` | Create new definitions. |
| `edit own entity definitions` | Edit definitions you created. |
| `view own entity definitions` | View definitions you created. |
| `delete own entity definitions` | Delete definitions you created. |
| `preview entity definitions` | Preview changes without applying. |
| `export entity definitions` | Export own definitions to YAML. |
| `request definition review` | Submit definitions for review. |

Ownership is tracked via the `uid` field on EbDefinition.
