# Mappings

Mappings are JSONata transformations that convert JSON from one shape to another. Every mapping has a direction, chosen when it is created:

- **Outbound** mappings convert your source JSON into the format required by a trading partner's EDI implementation. Outbound flows use them to generate EDI documents from your API submissions.
- **Inbound** mappings normalize the JSON translated from a partner's EDI into a canonical shape you define, so your system receives one consistent structure from every partner. See the Inbound Mappings section below.

Both directions work in Tediware's representation of an EDI transaction set, which an outbound mapping must produce and an inbound mapping starts from. [JSON Format](/resources/docs/json-format) describes it.

## The Mapping Editor

The mapping editor has four tabs - **Source**, **Transform**, **Output**, and **Validate** - that represent each stage of the transformation process. Click a tab to view it. Pin a tab to keep it visible while you switch between others, letting you view multiple panes side-by-side.

At the top of the editor:

- **Implementation** selector: choose the target EDI implementation. The mapping's output must conform to this implementation's JSON schema. Click **View** to open the full implementation guide in a dialog.
- **Settings**: update the mapping's name, description, and tags.
- **Save**: persists changes to the transformation, implementation selection, source, and any settings changes. The button highlights when there are unsaved changes. Navigating away with unsaved changes triggers a confirmation prompt.

## Source

The Source pane manages the sample JSON data used to test your transformation.

A source is a representative example of the JSON your system will submit to the partner API endpoint. Sources are reusable: a single source can be shared across multiple mappings. When you update a shared source, Tediware warns you and lists the other mappings that will be affected.

- **Select**: choose an existing source.
- **New**: create a blank source.
- **Generate**: have the AI assistant propose a source shaped around the target implementation. You can optionally provide a sample of your own data (CSV, SQL schema, field list, or XML/JSON) for it to follow, or instructions to steer the result. Generation requires an implementation to be selected. Review the proposal, refine it, then accept it into the Source pane and save. Available for outbound mappings only; inbound sources come from real translated EDI (see Inbound Mappings below).
- **Save As New**: duplicate the current source as a new source with a different name.

Sources should be short and *representative* of the data your system outputs. If you're outputting the source for an 856, for example, your source should not contain hundreds of items. It should contain just enough items to be a representative example.

### Semantics

Semantics are optional markdown descriptions of the fields in your source. They help the AI assistant understand what each field represents, which is especially useful when your JSON keys are abbreviated or opaque (e.g., `ord_ln_qty` instead of `orderLineQuantity`).

You can write semantics manually using the **Edit** toggle, or click **Generate** to have the AI assistant produce them automatically. Generation requires an implementation to be selected. Review and adjust generated semantics as needed. Semantics generation is available for outbound mappings only; an inbound source is translated EDI whose keys already describe their own meaning.

## Transform

The Transform pane contains the JSONata expression editor where you write (or generate) the transformation logic.

- **Execute**: runs the transformation against the source sample. Results appear in the Output pane, and validation runs automatically.
- **Generate** / **Refine**: opens the AI assistant. When the transformation is empty, the button reads **Generate**; otherwise it reads **Refine**.
- **History**: opens the version history panel.

An implementation must be selected and saved before you can execute a transformation.

Beyond the standard JSONata library, Tediware registers custom functions available in any transformation: `$convertDateTime(value, sourceFormat, targetFormat)` converts between date formats (`"RFC3339Millis"`, `"EDIDate"`, `"EDIDateLong"`); `$buildHL(source, levels)` builds nested HL loop hierarchies with sequential IDs; `$placeholder(value, reason)` marks a value the author is not confident in for later review; `$code(value)` extracts the bare X12 code from a decoded translation value (`$code("each_EA")` returns `"EA"`), for inbound mappings whose canonical shape carries bare codes. Apply `$code` only to qualifier and code elements, never to free-form text, where an underscore in ordinary data would truncate the value.

## Output

The Output pane shows the result of executing the transformation. It is read-only.

- **JSON** / **EDI** / **Inspector** toggle: switch between the JSON output, the generated EDI, and a human-readable version. The EDI and Inspector views require a selected implementation and valid output (passing schema validation).
- **Copy**: copies the current output to your clipboard.
- **Review** / **Fix**: opens the AI assistant. When errors are present, the button reads **Fix**; otherwise it reads **Review**. The assistant can automatically fix errors, as well as review the output for accuracy.

## Validate

The Validate pane checks the transformation output against the implementation's JSON schema using AJV (JSON Schema draft 2020-12).

When validation fails, each error shows:

- **Message**: what the error is.
- **Instance path**: where in the output the error occurred.
- **Keyword**: the JSON Schema keyword that failed (e.g., `required`, `type`, `enum`).
- **Schema path**: where in the schema the constraint is defined.

Transformation errors (JSONata syntax or runtime errors) are also displayed here, with position, error code, and token details when available.

Click **Fix** to open the AI assistant with error context pre-loaded. In most cases, using the assistant is the quickest and easiest way to resolve validation errors.

## AI Assistant

The mapping editor includes an AI assistant accessible from the assistant button in the header or from the contextual buttons on each pane.

- **Chat**: ask questions about your mapping, source data, target schema, or JSONata syntax. The assistant can explain existing transformations, suggest approaches, and help debug issues.
- **Generate**: direct the assistant to create or modify a JSONata transformation. It analyzes your source data, target implementation schema, and any existing errors, then iteratively generates and validates a transformation. You can provide additional instructions to guide the output.

When the assistant produces a transformation, you can review and accept it to apply it directly to the editor. Chat history is preserved across interactions within the same session.

### Model Selection

You can choose which AI model the assistant uses for generation from the assistant settings. The available models are controlled by the platform and may change over time.

## Settings and Version History

### Settings

Click **Settings** to open the settings modal. You can update:

- **Name**: the display name for the mapping.
- **Description**: an optional description.
- **Tags**: organizational labels.

Changes made in the settings modal are staged locally until you click **Save** on the main editor.

### Version History

Tediware automatically creates a new version each time you save changes to the transformation. Open the version history panel by clicking **History** in the Transform pane.

From the version history you can:

- Browse all previous versions with timestamps and author names.
- View the full transformation for any version.
- **View Diff**: compare a previous version against the current transformation side-by-side.
- **Restore**: replace the current transformation with the selected version.
- **Edit notes**: add a note to any version for future reference.

## Inbound Mappings

Without a mapping, an inbound flow delivers the EDI-to-JSON translation as-is, and for many teams that is the right setup indefinitely: partners implementing the same document type often translate to similar or identical shapes, and you may onboard several before running into a difference at all. The shape is ultimately the partner's choice, though; partners can include different segments and fields, and different X12 releases can translate differently. When differences show up, they land as conditional parsing code in your system. An inbound mapping transforms each partner's translation JSON into a canonical shape you define once, so your system ingests one structure from every partner.

Inbound mappings are optional, and adopting them preemptively is usually premature: differences between partners are often absent or trivial (a renamed key). Handle shapes directly in your system until variation actually costs you something; starting without mappings does not lock you in later. They earn their keep when partner shapes have genuinely diverged, when partners span X12 releases that translate differently, or when new partners keep meaning new parsing code.

### The Canonical Implementation

An inbound mapping's target is an implementation you own that defines your canonical shape, for example "Canonical Inbound 850". The Validate pane checks mapped output against its schema, and the AI assistant uses it as the target when generating the transformation.

Do not build it from scratch: that requires detailed X12 knowledge and tempts you into specifying fields no partner sends. Duplicate the implementation of a real partner and rename the copy, so every field in it is one you actually receive. One canonical implementation serves partners across X12 releases: inbound mapping selection matches on the transaction set code (for example 850), not the release.

### Adopting Inbound Mappings

The recommended sequence, once variation has shown up (or you know it is coming):

1. Onboard your first partner and process sample documents.
2. Duplicate that partner's implementation as your canonical implementation.
3. Create an inbound mapping from the partner's translation JSON to the canonical implementation, and assign it on the partner's inbound transaction setting.
4. Build your system against the mapped shape.
5. As you add partners, give each one a mapping targeting the same canonical implementation. Your ingestion code does not change.

If your system already consumes a partner's unmapped translation JSON, the path is the same with one extra step: after assigning the first mapping, update your system for the canonical shape. That is a one-time change.

### How the Canonical Shape Differs from Translation JSON

Mapped output follows the canonical implementation's schema, which differs from raw translation JSON in consistent ways:

- **Code values are bare codes.** The translator decodes code values into descriptive labels (`"each_EA"`); the canonical shape carries the codes themselves (`"EA"`). The custom `$code` function does this conversion.
- **Segments that appear once are objects, not arrays.** The translator wraps most segments in arrays even when they occur a single time.
- **The mapping can drop segments your system does not use.**

### When a Mapping Fails

Delivery always happens, and every mapped document is validated against the canonical implementation's schema before delivery. A mapping can fail two ways, both flagged on the result's detail with `mappingFailed: true` and a `mappingError` whose `kind` distinguishes them: `"expression"` means the transformation failed to run, and the delivered output is the untransformed translation JSON; `"validation"` means the transformation ran but its output did not match the canonical shape, and the delivered output is that mapped document, with `mappingError.errors` listing the schema violations. Consumers of mapped documents should check the flag before parsing, store flagged documents for review, and use the result's translation artifact (the JSON the mapping received) to reproduce and fix the failure in the editor. When the flag is absent, the output passed validation and is the canonical shape.

### Inbound Mappings in the Editor

- The editor shows an **Inbound** badge; direction is set at creation.
- The source is a sample of the partner's translation JSON and must come from real translated EDI. Load one with **From sample EDI** in the Source pane (paste or upload partner sample EDI; Tediware translates it and inserts the transaction set, with a picker when the file contains several), or save one from a real processed document with **Create source** on any result payload view.
- **Generate** for sources and semantics is unavailable for inbound mappings.
- Sources are capped at 25KB; trim repeated line items down to a representative few entries.
- Placeholders are an outbound concept and do not apply.
- The Output pane shows JSON only; there is no EDI to preview for inbound.
- The AI assistant generates inbound transformations the same way as outbound, from the translation sample to the canonical implementation's schema.
