
# Catchments

[Bearer authentication](authentication.md) and `Content-Type: application/json` are required. Limits are 4096 request bytes, 8 MiB response bytes, and 30 seconds. Query parameters and extra fields fail. Responses use `Cache-Control: private, no-store`.

| Method | Endpoint | Body |
| --- | --- | --- |
| POST | `/api/v1/catchments/analyze` | `point`, optional `datasetId` and `snapRadiusM` |
| POST | `/api/v1/catchments/compare` | Exact references `a` and `b` |

## Analyze

| Field | Type and constraints |
| --- | --- |
| `point` | Exactly two numbers, WGS84 `[longitude,latitude]` degrees, bounded by ±180° and ±90°. |
| `datasetId` | Optional string matching `^[A-Za-z0-9-]{1,256}$`. Omission selects the installed national release. An explicit ID must match it. |
| `snapRadiusM` | Number, inclusive 0–1000 metres, default 100. |

Omit the release selector to use the installed data.

```json
{
	"point": {"longitude":19,"latitude":52}
}
```

Every `200` response has `status`, `datasetId`, `generation`, and `requestedPoint`.

| Status | Additional fields |
| --- | --- |
| `matched` | `outlet.point`, `outlet.cell.{row,column,contributingCells}`, `snapDistanceM`, `statistics`, `river`, `estimates` |
| `no_match` | `reason` is `outside_dataset`, `no_eligible_outlet`, or `selected_outlet_outside_radius`. Only the last includes `outlet` and `snapDistanceM`. |

Response excerpt, with identity fields omitted.

```json
{"status": "no_match", "reason": "no_eligible_outlet"}
```

`snapDistanceM` measures projected distance from the submitted point to the selected cell centre. Selection starts around the containing cell centre. Rejection does not exclude another outlet within the radius.

The containing native cell is selected after conversion to EPSG:2180. Native search uses `ceil(snapRadiusM / cellSize + sqrt(0.5))` cells and the release's contributing-cell threshold.
It minimizes distance from that cell centre, breaking ties by greater contributing count and then row/column order. The final radius check uses the original submitted coordinate; a rejected selected outlet does not trigger another search. Zero radius requires zero displacement.

Rows increase southward and columns eastward. Decimal-string cell counts preserve integer precision.
Dataset and generation are checked across native responses. `statistics.outlet` and contributing count agree with the selected outlet; native cell count times cell area gives `statistics.areaM2`.
Elevation and slope describe the installed model and its elevation reference, with null for unavailable facts.

`statistics` contains `outlet`, decimal-string `contributingCells`, `areaM2`, nullable `elevationMetres.{minimum,maximum,mean}`, nullable `meanSlopeDegrees`, one `coverage` entry per covered land-cover class with `classId`, `code`, `cells`, `areaM2`, `percentage`, and nullable `sourceLabel`, plus `landCoverClassification.{name,references}`. Optional reference statistics are `soil`, `lambda`, `alpha`, and `rainfall`.

`river` contains nullable `outletElevationMetres`, `farthestHead` and `highestHead` with `row`, `column`, `elevationMetres`, and `pathLengthMetres`, plus `totalStreamLengthMetres` and `streamDensityKmPerKm2`.

`estimates` contains empty `choices` and `overrides`, and `result` with `parameters`, `lambda`, `regionChoices`, `flows`, and `warnings`. Flow names are `probabilisticPeakFlow`, `meanAnnualFlow`, `meanLowFlow`, `rainfallPeakRunoff`, and `annualRunoffVolume`. With `status: "ok"`, `probabilisticPeakFlow` uses `values[].{probabilityPercent,qM3s}`, scalar discharges use `valueM3s`, and annual volume uses `valueM3PerYear`. Unavailable flows have `status: "unavailable"`, `code`, and `reason` with optional evidence.

## Compare

Each reference contains integer `row` and `column` from 0 to 9007199254740991. References identify eligible cells from matched analyses in the installed dataset and generation. Optional `datasetId` and `generation` pin those identities; omitted values select the installed release.

Illustrative body. Actual references come from analysis responses.

```json
{
	"a": {"row": 0, "column": 0},
	"b": {"row": 1, "column": 0}
}
```

The response has `relation` of `same`, `a_contains_b`, `b_contains_a`, or `disjoint`. `a` and `b` have `ref`, decimal-string `cells`, and integer `areaM2`. `intersection` and `union` have `cells` and `areaM2`. `basis` is `native_cell_membership`. `drainageConnectivity` is `not_evaluated`.

Relations are `same`, `a_contains_b`, `b_contains_a`, or `disjoint`. They describe contributing cells in the qualified single-flow model. A containing catchment already includes the nested catchment's contributing area. `union.areaM2` counts each contributing cell once. Equal areas alone do not establish the same catchment.

Comparison supports the audited native `catchment-v2` single-owner D8 product, its `stream-catchment` generation, and the aligned one-metre EPSG:2180 grid. Unsupported grids fail explicitly. It does not use smoothed outlines or display-resolution pixel areas. The operation needs one info request and at most two bounded native mask requests, independent of catchment area.

Shared modelled area does not establish physical conveyance to a pond. Disjoint catchments do not make empirical peak estimates additive: timing, routing, losses, and model applicability remain separate. Comparison does not estimate dependable water supply.

## Errors

Errors contain `error` and `message`. Service failures never become `no_match`.

| HTTP | Codes |
| --- | --- |
| 400 | `invalid_request`, `invalid_hydrology_request` |
| 401, 403, 405 | `unauthorized`, `forbidden`, `method_not_allowed`, respectively |
| 409 | `dataset_mismatch`, `generation_mismatch` |
| 413, 415, 429 | `payload_too_large`, `unsupported_media_type`, `rate_limited`, respectively |
| 422 | `response_byte_limit_exceeded` |
| 502 | `service_unavailable`, `map_access_unavailable` |
| 503 | `hydrology_unavailable`, `hydrology_busy`, `hydrology_grid_unsupported`, `hydrology_release_mismatch`, `hydrology_outlet_mismatch`, `hydrology_comparison_invalid` |
| 504 | `service_unavailable` |

For retained project calculations, use [water-design query and commands](actions.md). These execute the same saved-calculation workflows as the app. Use [calculation discovery and stateless validation/evaluation](calculations.md) before saving; the reference also gives the saved-calculation and S_6 insertion sequence.

## Save and re-save a native catchment

A matched analysis also returns `calculationState`: the complete unified catchment state,
including the captured outlet/bundle identity, source facts, reference releases and default
choices. Pass this state to `save_catchment_analysis` through
[`POST /api/v1/actions/water-design/commands`](actions.md). The server fetches the
trusted grid for that bundle and derives the outlet point from its row and column. The save
request contains no `geometry`, `source.info`, grid origin or cell size.

Create with a new UUID `creationId`, optional `title`, and `state: analysis.calculationState`.
The result contains `calculation.calculationId`, `calculation.revision`, and the owned map
feature. Repeat the exact request and write envelope to recover a lost acknowledgement.

To change choices or overrides, read the saved calculation with the `calculation` query,
copy its state and change `state.source.choices` or `state.source.overrides`. Re-save with
`calculationId`, the calculation's `expectedRevision`, and the edited `state`. The captured
`state.source.capture` stays unchanged. The outlet stays fixed; a different outlet requires
a new calculation. `hydrology.gauges` is editable too: the captured IMGW stations, the chosen
`stationIds` (at most two) and the engineer's `compatibility` confirmation. A confirmed set
gives WWQ, SWQ and NNQ and the gauge alternative of SSQ and SNQ. The unified `update_calculation`
operation also accepts these edits while preserving the same immutable capture and outlet. `qn.k` and
`qd.isFishPond` can also change on re-save.

Both writes use the current water-design revision in `input.expectedRevision` and a
project-presentation write envelope. The re-save operation's `expectedRevision` is the
calculation revision; these are separate revision counters. For example, after reading
`saved` and the current water-design `revision` through public queries:

```python
import copy
import uuid

state = copy.deepcopy(saved['calculation']['state'])
state['source']['overrides'].setdefault('values', {})['annualPrecipitationMm'] = {'value': 700}
body = {
    'projectId': project_id,
    'input': {
        'expectedRevision': revision['revision']['revision'],
        'write': {
            'sessionId': str(uuid.uuid4()),
            'lane': 'project-presentation',
            'sequence': 1,
        },
        'command': {
            'kind': 'workflow',
            'operation': {
                'kind': 'save_catchment_analysis',
                'calculationId': saved['calculation']['calculationId'],
                'expectedRevision': saved['calculation']['revision'],
                'state': state,
            },
        },
    },
}
```

Submit `body` to the commands action. A successful re-save increments the calculation
revision, recomputes its results and dependent calculations, and emits the normal calculation
change event. A stale calculation or water-design revision returns HTTP 409. Missing grid
metadata fails the creation without saving a partial calculation or map feature.

## Source statistics and provenance

`statistics.coverage` lists the native land-cover classes the catchment covers; classes with no covered cells are left out. Each entry has `classId`, `code`, decimal-string `cells`, `areaM2`, `percentage`, and nullable `sourceLabel`. The label is the Polish BDOT10k source object-class name. It is not the category used to choose a runoff coefficient. Unknown or unverified labels remain null. `statistics.landCoverClassification` gives the classification name and source-reference URLs. Unknown land cover remains visible. Optional reference summaries are:

- `soil` has `source`, `classes`, and `uncovered`. Each class has `classId` and `total`, `direct`, and `inferred` coverage. Inferred coverage is a source-product completion, rather than a direct observation.
- `lambda` has `source`, `regions` containing `regionId` and `coverage`, and `uncovered` coverage.
- `alpha` has `source`, `applicability: "unresolved"`, `areas` containing `alphaAreaId` and `coverage`, `uncovered`, `reviewIntersections`, and `reviewUnion`. An intersection has `total` coverage and `alphaAreas`; individual review entries also have `flagIndex`. These overlap/review facts do not establish empirical-method applicability.
- `rainfall` has `status: "available"`, `source`, `referencePeriod`, `unit: "mm/year"`, `meanMmPerYear`, and `validCoverage`. The mean covers valid raster cells only and is null if none are covered. It is a reference mean, not event rainfall.

Each `source` names the published dataset (`name`) and its `edition`: GUGiK soil-agricultural map 2026, KZGW 2017 λ regions and α areas, and IMGW-PIB mean annual rainfall for the reference period. The release identities used to save the analysis stay inside `calculationState`.

Reference lists leave out entries with no covered cells, so an absent class, unit, region or α area covers nothing. `reviewIntersections` lists only flags that intersect the catchment, and `reviewUnion` is absent when no flag does.

Each reference coverage object contains decimal-string `cells`, `areaM2`, and `percentage`. Its denominator is the full catchment, including uncovered cells. An absent optional summary means that source fact is unavailable. Do not treat it as zero.

`river.outletElevationMetres` is nullable. `farthestHead` and `highestHead` each contain native `row`, `column`, `elevationMetres`, and `pathLengthMetres` to the outlet. `totalStreamLengthMetres` and `streamDensityKmPerKm2` describe the native stream model within the catchment. They do not establish a navigable or physically verified connected network.

## Estimates and uncertainty

`estimates.mode` is `"empirical"`. `choices` and `overrides` are empty objects. This API does not accept manual coefficients, probability choices, station selection, or observation overrides. It reuses Tarvena's catchment flow calculation defaults.

`estimates.result` contains:

- `soilMapping`, when soil data is used: the soil `source` and the publications the φ (`phi`) and hydrologic soil group (`hsg`) assignments follow.
- `parameters`, keyed by calculation parameter ID. Each available entry has `value`, `unit`, `quality`, `provenance` (what produced the value, with its inputs such as the rainfall `referencePeriod`) and `sourceLabel`, plus optional `assumedShare` as a fraction of the full catchment. Quality is `source`, `estimated`, `assumed`, or `manual`. An empty API override set never introduces a manual edit.
- `lambda`, an array of `probabilityPercent`, `value`, `quality`, and `sourceLabel`.
- `regionChoices`, with `regionId` and optional `areaShare` and `distanceM`.
- `flows.probabilisticPeakFlow`, probabilistic peak estimates. An `ok` result has `methodId` and `values` containing `probabilityPercent` and `qM3s`. Optional `falTime` records `tsCalculatedMin` and `tsUsedMin`.
- `flows.meanAnnualFlow` and `flows.meanLowFlow` are modelled mean annual and mean low flows. An `ok` result has `methodId` and `valueM3s`.
- `flows.rainfallPeakRunoff` is the existing rainfall-based empirical **peak runoff estimate, Qmax**. It is not current streamflow or a continuous supply rate. An `ok` result has `methodId` and `valueM3s`. This API uses the model's default probability parameter of 60%, annual reference precipitation, and its small/large variant boundary of 50 ha. This estimate has a different calculation and parameter selection from `flows.probabilisticPeakFlow`; preserve its applicability and audit warnings.
- `flows.annualRunoffVolume`, modelled annual runoff volume. An `ok` result has `valueM3PerYear`.
- `warnings`, an array of `code`, `parameterIds`, `flowIds`, and optional structured `evidence`. Evidence can give `coveredShare` or FAL times. Keep warnings with any quoted estimate.

A flow with `status: "unavailable"` has `code`, `reason`, and possibly `methodId`, `parameterIds`, or `evidence`. Preserve these fields; never replace an unavailable estimate with zero. Missing reference coverage can produce assumed parameter values. Method limits, unresolved regional choices, unverified applicability, and missing observations can leave a flow unavailable even when source catchment statistics exist.

These estimates are model outputs, not measured flows. Peak estimates do not imply an observed design flood. Do not multiply `flows.rainfallPeakRunoff` by days or years to estimate water supply. SSQ and annual runoff also come from separate estimators; they are not a reconciled water balance and need not imply the same annual volume. Annual runoff volume is not dependable abstraction or pond yield. These operations provide no pond water balance, storage sizing, network connectivity proof, catchment outline, or mask response.

## Use Python without private APIs

The standard-library example uses a bearer token obtained by your own client through [device sign-in](authentication.md). Supply it privately as `TARVENA_TOKEN` in the caller environment. It saves both responses and analyzes the first segment's downstream endpoint only as an example of candidate selection.

```python
import json
import os
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import HTTPRedirectHandler, Request, build_opener

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

origin = 'https://tarvena.pl'
token = os.environ['TARVENA_TOKEN']
opener = build_opener(NoRedirect())

def call(path, destination, body=None):
    headers = {'Authorization': 'Bearer ' + token}
    data = None if body is None else json.dumps(body).encode()
    if body is not None:
        headers['Content-Type'] = 'application/json'
    request = Request(origin + path, data=data, headers=headers)
    try:
        with opener.open(request, timeout=35) as response:
            payload = response.read(8 * 1024 * 1024 + 1)
    except HTTPError as error:
        Path(destination).write_bytes(error.read(4096))
        raise SystemExit(f'HTTP {error.code}; inspect {destination}') from None
    if len(payload) > 8 * 1024 * 1024:
        raise SystemExit('Response exceeds the documented limit')
    Path(destination).write_bytes(payload)
    return json.loads(payload)

streams = call('/api/v1/streams?' + urlencode({'bbox': '18.30,51.39,18.31,51.40'}),
    'streams.geojson')
if not streams['features']:
    raise SystemExit('No segments found in the display archive for this bbox')
candidate = streams['features'][0]['geometry']['coordinates'][-1]
analysis = call('/api/v1/catchments/analyze', 'catchment.json', {
    'point': candidate, 'snapRadiusM': 100})
print(analysis['status'])
```

## Road drainage strip and design flow

### Draw the drained strip

Request the road axis through the ordered outlets in one call. Pass named EPSG:2180 points `{easting,northing}` or survey `{x,y}` (X=northing, Y=easting). Results use `{projection,easting,northing}`; GeoJSON keeps `[easting,northing]` arrays:

POST [`maps/roads/axis`](https://tarvena.pl/api/v1/actions/maps/roads/axis):

```json
{"points":[{"easting":576350,"northing":236130},{"easting":576950,"northing":236050}],"bufferM":10}
```

Replace the example points with all 20 outlets in road order. Retain the returned `buffer` as `catchment.geometry`. The response includes one continuous `axis`, `lengthM`, and `snapDistancesM` in input order. It searches a 100 m corridor between points and joins road vertices within 5 m. Review snap distances and road selection. Limits are 2–200 points, 2 km per leg, and 1024 distinct tiles checked before reads. `road_axis_gap_too_large`, `road_axis_tile_limit_exceeded`, or `road_axis_no_route` refuse the whole request; add real intermediate road points or shorten the requested section and retry.

Fallback: [`maps/roads/query`](https://tarvena.pl/api/v1/actions/maps/roads/query) returns raw tile-clipped fragments for manual road selection and local stitching/buffering.

### Promote an existing drawing

For an unowned Polygon or LineString drawn in `system:sketches` or on one of the project's own
drawing layers, use one `promote_sketch_to_catchment` command instead of creating a calculation and
importing its geometry. A Polygon becomes a manual catchment; a LineString becomes a road catchment
along it. Rectangles stored as Polygons qualify. Points, MultiPolygons, text labels, product-owned
features and drawings on other system layers do not. A sketch in `system:sketches` is consumed; a
drawing on an own layer stays where it is. The command requires both `map.edit` and
`calculations.catchment`.

Read the sketch with `maps/features/get`, retaining its `revision.revision` as
`mapFeaturesRevision`. Read `water-design/query` with `query:{kind:"revision"}`, retaining
`revision.revision` as `waterDesignRevision`. These revisions belong to different owners; sketch
edits advance the map revision independently. In the request below, replace the outer
`"<returned-revision>"` with `waterDesignRevision` and the inner one with `mapFeaturesRevision`.
Use the saved sketch ID. The example starts a fresh write session at sequence 1; an existing
session uses its next sequence.

POST [`water-design/commands`](https://tarvena.pl/api/v1/actions/water-design/commands):

```js
const promoteSketch = {
  projectId,
  input: {
    expectedRevision: "<returned-revision>",
    write: { sessionId: "<fresh-uuid-2>", lane: "project-presentation", sequence: 1 },
    command: {
      kind: "workflow",
      operation: {
        kind: "promote_sketch_to_catchment",
        sketchFeatureId: "<sketch-feature-id>",
        expectedMapFeaturesRevision: "<returned-revision>",
        creationId: crypto.randomUUID(), // Mint once at submission.
      },
    },
  },
};
```

The acknowledgement's `result.kind` is `sketch_promoted_to_catchment`. It names
`calculationId` and `featureId` as `manual:<creationId>`, `layerId` as `system:calculations`, and the
promoted `sketchFeatureId`. `result.revision` is the calculation revision; `change.revision` is the
Water Design revision. Creation, outline projection, sketch removal and receipt settlement commit
atomically. The outline and name survive; an unnamed drawing becomes `Zlewnia`.

Freeze the entire request for a resend, including both revisions, the creation ID and the write
envelope. Replaying it after the sketch disappears returns the original receipt without creating
another catchment. A new submission against the consumed sketch is refused. A replay carries no
live `calculation`: read the calculation and map state again to reconcile it.

The first live response includes the exact area and pending coverage. Read the calculation as
described below until coverage settles. A coverage refusal keeps the valid catchment, its outline
and its area; pending or failed coverage is not a zero result. Retry coverage with
`update_catchment_geometry`, using current revisions. The outline must be closed, topologically
valid, contain at most 16,384 positions including closures, and have a positive area no greater
than 125 km². No clipping or simplification occurs. Coverage acquisition starts after commit and
can refuse its own extent or detail limits asynchronously.

### Import the catchment

POST `calculations/types/get` with `{"type":"catchment"}`. Retain `type.defaultState` as `catchmentDefaultState` for creation. It contains labelled examples; import the real outline before using any results.

POST [`water-design/commands`](https://tarvena.pl/api/v1/actions/water-design/commands):

```js
const createCatchment = {projectId, input:{command:{kind:"workflow",operation:{kind:"create_calculation",type:"catchment",title:"Zlewnia odwodnienia drogi",state:catchmentDefaultState,dependencies:[]}},expectedRevision:"<returned-revision>",write:{sessionId:"<fresh-uuid-1>",lane:"project-presentation",sequence:6}}};
```

Retain `result.calculationId` as `catchmentCalculationId` and its calculation revision. Use the current outer water-design revision and next sequence for every command; sequences here continue the outlets example.

POST [`water-design/commands`](https://tarvena.pl/api/v1/actions/water-design/commands):

```js
const importCatchment = {projectId,input:{command:{kind:"workflow",operation:{kind:"import_catchment",calculationId:catchmentCalculationId,expectedRevision:"<returned-revision>",geometry:{format:"geojson",projection:"EPSG:2180",geometry:catchment.geometry}}},expectedRevision:"<returned-revision>",write:{sessionId:"<fresh-uuid-1>",lane:"project-presentation",sequence:7}}};
```

The `import_catchment` operation’s inner `expectedRevision` is the calculation’s revision; the outer `input.expectedRevision` is the water-design revision.

Import replaces example terrain inputs and returns immediately with `state.source.facts.coverageState:{status:"pending",settled:false}`. Poll the catchment until `status:"ready",settled:true` (usually under a second with cached tiles; allow 10–30 s for a first-time cold area); `status:"failed",settled:true` includes `reason`. Read it with `water-design/query`, `{"projectId":"<projectId>","query":{"kind":"calculation","calculationId":"<catchmentCalculationId>"}}`. Coverage arriving commits in the background and advances both the catchment’s and the water-design revision, so the import response’s revisions are stale: take both from this ready read before the next command.

### Evaluate and save design flow

Use Tarvena’s point lookup for the imported catchment: choose its outlet or a representative point, expressed in WGS84 (convert the supplied EPSG:2180 coordinates). No hydrology bundle or outlet cell is needed. Convert a point with `maps/geometry/transform`: `{fromProjection:"EPSG:2180",toProjection:"EPSG:4326",geometry:{format:"geojson",projection:"EPSG:2180",geometry:{type:"Point",coordinates:[easting,northing]}}}`. Its returned `geometry.geometry.coordinates` is `[longitude,latitude]`.

POST [`reference-data/imgw/design-rainfall`](https://tarvena.pl/api/v1/actions/reference-data/imgw/design-rainfall):

```json
{"projectId":"<projectId>","point":{"latitude":50.0,"longitude":20.0}}
```

Replace the example point with the chosen location. Retain the response as `designRainfall`; require `status:"available"`. It contains PMAXTP depths by duration/probability, source URL, retrieval time, hash and point qualification. These are point design depths, not measured or catchment-average rainfall. Never substitute the illustrative 15 mm when the lookup fails.

To get a SWMM rain file for the same point, choose the duration and exceedance probability:

POST [`reference-data/imgw/design-hyetograph`](https://tarvena.pl/api/v1/actions/reference-data/imgw/design-hyetograph):

```json
{"projectId":"<projectId>","point":{"latitude":50.0,"longitude":20.0},"durationMin":60,"probabilityPercent":10,"format":"swmm"}
```

Require `status:"available"` and save `file.text` as UTF-8 under `file.name`, preserving its line endings. The response includes 5-minute steps, `totalMm` and the same source qualification as the depth lookup. Euler II is the default; set `pattern:"dvwk"` for DVWK. Use an SI-unit SWMM project with rain gage Rain Format **VOLUME** and Time Interval **0:05**. Request `format:"csv"` for the popup's hyetograph CSV or omit `format` for JSON steps. Fetch the action schema for supported IMGW durations (15 minutes–24 hours) and probabilities.

Before evaluation, bind `catchmentRevision` to the imported calculation revision from the latest read and `rainfallPoint` to the selected EPSG:2180 point as `{projection:"EPSG:2180",easting,northing}`. Empty `surfaces` uses the linked catchment coverage.

Initialize travel time once from the latest saved catchment read. Retain its calculation as
`catchmentCalculation`. For a native catchment only, take `tc` in seconds from
`results["catchment/characteristics"].value.parameters.concentrationTimeSeconds.value`
when that result has `status:"ok"` and `inputs.input.origin:"native"`.
Use `max(tc / 60, 10)` minutes, or the 20-minute assumption if `tc` is absent.
A road, imported or manual catchment has no modelled
value for this purpose: use the editable 20-minute assumption, even if its example
parameters contain a concentration time. Preserve the source together with the value.
This is initialization, not an instruction to recalculate saved or engineer-entered values.

The following client-side derivation implements the calculation-core default rule. For example,
a native `tc = 1800 s` gives 30 min; `tc = 300 s` gives 10 min; a road catchment
gives 20 min. An engineer override replaces `travelTimeMin`, sets
`travelTimeOrigin:"engineer"`, and removes `travelTimeSource`.

```js
const characteristics = catchmentCalculation.results["catchment/characteristics"];
const modelledTcSeconds = characteristics?.status === "ok" && characteristics.inputs.input.origin === "native"
  ? characteristics.value.parameters.concentrationTimeSeconds?.value
  : undefined;
const travelTime = modelledTcSeconds == null
  ? {value:20,source:"Edytowalne założenie: 20 min — brak modelowanego czasu koncentracji zlewni."}
  : {value:Math.max(modelledTcSeconds / 60,10),source:"Edytowalna wartość domyślna: czas koncentracji zlewni z modelu; nie mniej niż 10 min (minimalny czas deszczu)."};
```

POST [`calculations/evaluate`](https://tarvena.pl/api/v1/actions/calculations/evaluate):

```js
const evaluateFlow = {projectId,type:"surface-runoff",state:{peakMethod:"designStorm",returnPeriodYears:5,travelTimeMin:travelTime.value,travelTimeSource:travelTime.source,travelTimeOrigin:"default",minimumDurationMin:10,rainfall:{kind:"depth"},rainfallContext:{locationKey:JSON.stringify(rainfallPoint),source:{kind:"catchment",calculationId:catchmentCalculationId,revision:catchmentRevision},design:{rows:Object.entries(designRainfall.matrix.depths).map(([duration,depthsMm])=>({durationMin:Number(duration),depthsMm})),reference:{code:"PMAXTP_STORM_RAINFALL",point:rainfallPoint,sourceUrl:designRainfall.source.sourceUrl,retrievedAt:designRainfall.source.retrievedAt,responseSha256:designRainfall.source.responseSha256,qualification:designRainfall.source.qualification}}},surfaces:[],catchment:{mode:"linked"}},dependencies:[{slotKey:"catchment",sourceCalculationId:catchmentCalculationId,valueKey:"catchment/inputs",selector:null}]};
```

Require `results["surface-runoff/peak"].status:"ok"` and `inputs.stormRainfallReference.code:"PMAXTP_STORM_RAINFALL"` on that result before adopting the default; otherwise inspect the rainfall context and requested duration/probability. Q is its `value.dischargeM3s` (m³/s), or `dischargeLps` (l/s). Retain this request’s state/dependencies as `flowState`/`flowDependencies` and response `evaluationBasis` as `flowBasis`.

POST [`water-design/commands`](https://tarvena.pl/api/v1/actions/water-design/commands):

```js
const saveFlow = {projectId,input:{command:{kind:"workflow",operation:{kind:"create_calculation",type:"surface-runoff",title:"Odpływ z odwodnienia drogi",state:flowState,dependencies:flowDependencies,evaluationBasis:flowBasis}},expectedRevision:"<returned-revision>",write:{sessionId:"<fresh-uuid-1>",lane:"project-presentation",sequence:8}}};
```

Read the saved calculation by its returned `result.calculationId`; use its saved peak Q. [Write recovery](calculations.md#save-an-evaluated-calculation).

#### Annual volume

The public HTTP API has no supported action for acquiring the local IMGW annual-rainfall
capture. `reference-data/imgw/design-rainfall` supplies design storms, not annual precipitation.
For local IMGW evidence, hand off to the signed-in MCP `annual-rainfall` operation with the explicit named request
`{point:{projection:"EPSG:2180",easting:rainfallPoint.easting,northing:rainfallPoint.northing}}`.
Do not reinterpret this as survey X/Y. Its `status:"ready"` response supplies `annual`; retain the labelled example while it is
unavailable. Do not call the internal dataset endpoint through the public actions API.

When that handoff supplies a capture, copy its whole `annual` object into
`flowState.rainfallContext.annual`. Both the returned `annual.reference.point` and HTTP state
require exactly `{projection:"EPSG:2180",easting:number,northing:number}`; no axis conversion
is needed. Preserve `valueMm` and all `reference` fields: code
`IMGW_ANNUAL_RAINFALL`, model, qualification, EPSG:2180 point, releaseId, referencePeriod and
sourceUrl. Bind `rainfallContext.locationKey` to `JSON.stringify(rainfallPoint)` and its `source`
to `{kind:"catchment",calculationId:catchmentCalculationId,revision:catchmentRevision}` from the
latest catchment read, as in the evaluation request above. Reacquire evidence if the point or
catchment changes; do not relabel an old capture with a new revision. For a manual, unlinked
surface-runoff input, use `source:{kind:"project"}` instead.

The handoff below uses the MCP response as `annualResponse`. Evaluate this state before saving:

```js
const annualHandoff = {...flowState,rainfallContext:{...flowState.rainfallContext,annual:annualResponse?.status === "ready" ? annualResponse.annual : flowState.rainfallContext.annual}};
```

Alternatively, an engineer can supply a justified annual precipitation in mm/year. This example
uses **700 mm/year as an editable example**, not an acquired local IMGW value. Keep the engineer's
source and reference period with the calculation description.

POST [`calculations/evaluate`](https://tarvena.pl/api/v1/actions/calculations/evaluate):

```js
const engineerAnnual = {projectId,type:"surface-runoff",state:{...flowState,annualPrecipitationMm:700},dependencies:flowDependencies};
```

Before presenting annual volume, require `results["surface-runoff/annual"].status:"ok"` and inspect
its `inputs.annualPrecipitationMm` and `inputs.annualRainfallReference`. The volume is
`value.volumeM3PerYear` (m³/year). A reference code `EXAMPLE_ANNUAL_RAINFALL` or
`EXAMPLE_CATCHMENT_ANNUAL_RAINFALL` means an illustrative result, normally based on 600 mm/year.
Label it as such even when the peak result has valid PMAXTP provenance. An
`IMGW_ANNUAL_RAINFALL` reference must match the adopted capture and its binding. An absent reference
can mean an explicit engineer value or an existing catchment value; check that input's recorded
source before calling it local rainfall. An override takes precedence over a capture. A numeric
result alone never proves provenance. Reevaluate with the adopted evidence, then save that exact
state, dependencies and returned evaluationBasis as above.
