# Survey form example

`form.xlsx` and `form-empty.xlsx` match `form.yaml`, version `2026.2`.
Both forms use the same layout, styles and Excel date system.

The populated workbook demonstrates valid records and validation findings.
The empty workbook provides the matching template without records.

## Workbook structure

| Sheet        | Data location | Contents                                  |
| ------------ | ------------- | ----------------------------------------- |
| Metadata     | C2:C5         | Submission, date, contact and comment     |
| Observations | A6:K9         | Three root records; row 7 is empty        |
| Samples      | A6:F9         | Children of observations; row 8 is empty  |
| Measurements | A6:E9         | Children of samples                       |
| Equipment    | A6:C7         | Independent equipment records             |
| Notes        | A6:E12        | Optional details attached to observations |
| Instructions | A1:A4         | Template content outside the model        |

Table headers are on row 5. Metadata uses fixed cell locations and an exact physical sheet size.

## Model capabilities

| Capability              | Declaration in the survey                                                |
| ----------------------- | ------------------------------------------------------------------------ |
| Field types             | Text, integer, number, Boolean, date, datetime, email and coordinates    |
| Required values         | Mandatory fields and units required when a measurement is supplied       |
| Allowed values          | Unit and quality enums; submission and observation identifier patterns   |
| Bounds                  | Numeric limits and sample minimum length bounded by maximum length       |
| Primary keys            | Composite observation, sample and measurement keys; equipment identifier |
| Parent keys             | Samples and Notes link to Observations; Measurements link to Samples     |
| Unique values           | Equipment serial numbers                                                 |
| Optional composite keys | Notes uses `[station, observation_id, category]`; incomplete keys pass   |
| Row completeness        | Notes requires category, count or confirmed; missing detail warns        |
| Grouped sequences       | Sample and reading numbers start at one within each parent group         |
| Reference lookups       | Named catalogue bindings for stations, observers and contact email       |

Notes has a parent key and a unique key, without a primary key.
Zero and false count as supplied values for its row-completeness check.

## Example records and findings

| Station | Observation | Samples | Measurements |
| ------- | ----------- | ------- | ------------ |
| ST01    | OBS-001     | 2       | 3            |
| ST02    | OBS-001     | 1       | 1            |
| ST01    | OBS-002     | 0       | 0            |

Observation identifiers repeat across stations while their composite keys remain unique.
Child records from different parents are interleaved.

Submission `001` is text and retains its leading zeros. Dates and Booleans use native Excel values.

| Sheet | Rows | Example                                | Expected result                        |
| ----- | ---- | -------------------------------------- | -------------------------------------- |
| Notes | 6–7  | Same parent and category               | Unique-key errors on both rows         |
| Notes | 8    | Same category under a different parent | No unique-key error                    |
| Notes | 9    | Parent identifiers with no detail      | Row-completeness warning               |
| Notes | 10   | Missing category, count is zero        | Uniqueness and row completeness pass   |
| Notes | 11   | Missing category, confirmed is false   | Uniqueness and row completeness pass   |
| Notes | 12   | Same parent with a different category  | No unique-key error                    |

All records and reference identifiers are synthetic, including `observer-1`, `observer-2` and `survey@example.org`.

Retrieve the populated form with `form_resource("examples/survey/form.xlsx", "form.model")`.

## Reference catalogues

The survey catalogue supplies the station, observer and contact values used in the form.
A second catalogue identifies the same stations and observers by technical IDs.
`mapping.yaml` translates those IDs into the codes used in the survey form.

## Reference files

```text
survey/
├── references.yaml
├── references-source.yaml
├── mapping.yaml
├── correspondences/
│   └── stations.csv
├── catalogue/
│   ├── code_lists/
│   │   ├── catalogue.csv
│   │   ├── catalogue.yaml
│   │   ├── catalogue_aliases.csv
│   │   ├── observers.csv
│   │   └── stations.csv
│   └── registries/
│       ├── catalogue.csv
│       ├── catalogue.yaml
│       ├── catalogue_aliases.csv
│       └── contacts.csv
└── catalogue-source/
    └── code_lists/
        ├── catalogue.csv
        ├── catalogue.yaml
        ├── catalogue_aliases.csv
        ├── observers.csv
        └── stations.csv
```

Each catalogue directory is a complete source containing these files:

| File                    | Purpose                                          |
|-------------------------|--------------------------------------------------|
| `catalogue.csv`         | Table IDs, paths, versions, dates and checksums. |
| `catalogue.yaml`        | Catalogue publication timestamp and checksum.    |
| `catalogue_aliases.csv` | Alternative values accepted by table lookups.    |
| Other CSV files         | Reference data, read as text to preserve codes.  |

The survey uses the following tables and lookup columns:

| Catalogue  | Table       | Lookup columns  | Example value       |
|------------|-------------|-----------------|---------------------|
| Code lists | `stations`  | `code`          | `001`               |
| Code lists | `observers` | `code`, `name`  | `ALICE`             |
| Registries | `contacts`  | `email`, `name` | `alice@example.org` |

## Configuration and use

`references.yaml` connects the named catalogues to their sources and defines their lookup settings.

- `schema_version` selects the configuration schema.
- Source paths are relative to the configuration file.
- Cache paths are omitted, so caches use the R session's temporary directory.
- Runnable examples remove their temporary caches afterwards.
- Table and lookup names match the bindings declared in the form model.

`read_reference_configuration()` checks this file before any reference data is retrieved.

The reference catalogues guide demonstrates how to prepare and use the survey lookups.

## Mapping the second catalogue

`references-source.yaml` declares source station IDs and observer IDs and names.

`mapping.yaml` selects its code lists as `source` and the existing configuration's code lists as `target`.

The existing contact registry remains available to the survey model.

- DIRECT: `station-north` maps through the CSV to station code `001`.
- REBOUND: `person-alice` supplies `Example Alice`, which matches target name `Alice Example` and returns `ALICE`.
- Unchanged input: an observer name goes directly to the target name lookup.

Select the observer alternative with `source_lookup = "id"` or `source_lookup = "name"`.

The station CSV includes a repeated pair, an old target code, an unknown target and conflicting correspondences.

The source observers include a missing name, an unknown person and a duplicated ID with two different names.

These deliberate data issues demonstrate unresolved results; they are not defaults or inferred correspondences.

The mapping vignette loads both catalogues once, then shows each behaviour in a separate runnable statement.

## Aliases

Each catalogue declares its alias file through a reserved entry in `catalogue.csv`:

| Column     | Value                   |
|------------|-------------------------|
| `domain`   | `catalogue`             |
| `id`       | `_aliases_`             |
| `csv_path` | `catalogue_aliases.csv` |

The alias file contains four columns:

| Column      | Meaning                                     |
|-------------|---------------------------------------------|
| `table`     | Table containing the canonical value.       |
| `column`    | Lookup column in that table.                |
| `alias`     | Alternative value accepted during matching. |
| `canonical` | Existing value to which the alias refers.   |

Aliases use the catalogue's authentication, checksum verification and cache.

- `prepare_model_references()` builds each required lookup with its own aliases.
- `reference_match_rows()` applies those aliases automatically.
- A lookup's `$aliases` exposes its mappings for inspection; the complete alias table is not returned.

## Updating or publishing the example

If you want to modify the example data:

1. Edit the relevant CSV file.
2. Update its version and source date in the corresponding `catalogue.csv`.
3. Refresh the catalogue checksums from the package root:

```sh
Rscript tools/update-example-catalogues.R
```
