Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 93 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -434,9 +434,10 @@ for resource in client.resources(first):
```

It yields each entry whose search mode is `match`, or says none. A resource an `_include` or
`_revinclude` brought, and a search's own `OperationOutcome`, are not among them; `pages()` gives
every entry. From async code, `async for page in async_client.pages(first)` and `async for resource
in async_client.resources(first)`.
`_revinclude` brought, and a search's own `OperationOutcome`, are not among them: `outcomes()` reads
a page's `OperationOutcome`s (see "Pharmacies" below), and `pages()` gives every entry. From async
code, `async for page in async_client.pages(first)` and `async for resource in
async_client.resources(first)`.

`matches()` gives one page's matches of a type, typed, with no request, and `resolve()` finds the
resource a reference names in that page, such as one an `_include` brought:
Expand Down Expand Up @@ -561,6 +562,95 @@ matched Schedule as a `haau3.ScheduleView`, with its `locations`, `practitioner_
`slot_views()` and `schedule_views()` are plain functions as well, for a page read elsewhere, and
from async code the helpers are awaited while the views are not.

## Pharmacies

A pharmacy search answers a FHIR Bundle whose matches are `HealthcareService`s, one per pharmacy;
each pharmacy's `Organization` (its NPI) and its store's `Location` (its address) come in the same
Bundle when the search asks for them with `_include`. `search_healthcare_service_with_includes()`
sends both, and `pharmacy_views()` hands you one row per pharmacy: the values a list of pharmacies
shows, what Medicare Part D says of it, and the FHIR resources the API served.

```python
page = client.search_healthcare_service_with_includes(
service_category="pharm",
location_address_state="FL",
location_address_postalcode="33131",
active="true",
)

for row in client.pharmacy_views(page):
street = ", ".join(row.address.get("line", [])) if row.address else None
print(row.name, row.npi, street, row.phone, row.part_d.listed if row.part_d else None)
```

| Field | What it holds |
|---|---|
| `npi` | The NPI: the `Organization`'s identifier in `http://hl7.org/fhir/sid/us-npi`. |
| `name` | The service's name, or else the Organization's. |
| `address` | The store's address, a FHIR `Address`: the first of the service's Locations with one, or else the Organization's first. |
| `phone` | The first phone number of the service, then of its Locations, then of its Organization. |
| `active` | Whether the service is active, as it says. A pharmacy NPPES lists as deactivated is `False`; send `active="true"` for active pharmacies only. |
| `specialties` | The service's codes in NUCC's provider taxonomy (`http://nucc.org/provider-taxonomy`), each a `Coding`: its kinds of pharmacy. |
| `part_d` | What Medicare Part D says of it, from haau3's Part D Listing extension, as a `haau3.PartDListing`: `listed`, whether any Part D plan's pharmacy list names it; `as_of`, the month CMS's Part D file covers (`2026-11`); `contract_year`, the year that file's plans are for (`2027`). `None` means not known, never not listed. |
| `networks` | The networks that list it, each once, from NDH's Network Reference extension, each a `haau3.PharmacyNetwork`: its `id`, its `name`, and for a Part D network its `plan` and `kind`. |
| `preferred` | Whether the plan prefers it: `True` when one of its Part D networks is `preferred-retail` or `preferred-mail-order`, `False` when Part D networks are named and none is, and `None` when none is named. |
| `service` | The matched `HealthcareService`. |
| `organization` | The `Organization` that provides it. |
| `locations` | Its `Location`s, the store, each once, in the order the service names them. |

A Medicare Part D plan's pharmacies are a pharmacy search narrowed by one of the plan's networks.
A plan names up to four, one for each kind of pharmacy CMS's Part D files flag, each with the id
`Organization-part-d-{plan}-{kind}`: `retail`, `mail-order`, `preferred-retail` or
`preferred-mail-order`. Each row's `networks` then names every one of that plan's networks that
lists the pharmacy, so `preferred` says whether any of them is a preferred one, and each network's
`kind` says which:

```python
retail = client.search_healthcare_service_with_includes(
service_category="pharm",
network="Organization-part-d-H2406-013-000-retail",
location_address_postalcode="33131",
active="true",
)

for row in client.pharmacy_views(retail):
print(row.name, "preferred" if row.preferred else "standard")
for outcome in client.outcomes(retail):
for issue in outcome.get("issue", []):
print(issue.get("severity"), issue.get("details", {}).get("text"))
```

`outcomes()` reads a search page's own `OperationOutcome`s, the entries whose search mode is
`outcome`, which `matches()` and `pharmacy_views()` leave out. A pharmacy search answers one with
severity `information` when the plan lists no pharmacy of the network's kind, beside no matches, and
one with severity `warning` when the API could not read Medicare Part D's files: each row's `part_d`
is then `None`. Nothing is fetched and nothing is replaced in place.

A row is a frozen dataclass, `haau3.PharmacyView`, that compares by value and cannot be hashed (it
holds dicts). `pharmacy_views()` makes a row of every `HealthcareService` the page matched, and raises
a `Haau3Error` in three cases:

- A pharmacy names an `Organization` or `Location` the page does not hold, on a pharmacy search that
did not ask for its include, so the message says to search with
`search_healthcare_service_with_includes()`. The page's `self` link says what the search asked for,
and a page without one is read as a search that asked for nothing.
- The page holds it, but not where FHIR's rules for a Bundle find it from the reference: each entry
needs its full URL, on the same base as the entry that names it, as the API serves them.
- As `resolve()` does, two entries could each be the one a reference names.

Anything else is left out: a resource of another type than the reference's element allows, a
resource a search asked for and the page still lacks, and whatever a service that is not a pharmacy,
or a page from the directory's own search, names and the page does not hold. The API offers includes
on a pharmacy search only, one that sends `service_category="pharm"` or a NUCC pharmacy `specialty`,
and answers `400` when the directory's own search asks for one. A value of another shape than FHIR
gives it is read as absent, so one malformed record never fails a page.

The helper takes every keyword `search_healthcare_service()` takes but `include`, which Python
refuses before anything is sent, and it sends nothing else. To send your own includes, call
`search_healthcare_service()`. Nor does it take `summary`, which the API does not combine with an
include: to count matches, call `search_healthcare_service(summary="count")`. `pharmacy_views()` and `outcomes()` are plain functions as well, for a
page read elsewhere, and from async code the helper is awaited while the view is not.

## Reading a Parameters answer

FHIR operations answer with a `Parameters` resource whose parts are named: `$lookup`'s `display` and
Expand Down
52 changes: 43 additions & 9 deletions scripts/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,19 @@ def __post_init__(self) -> None:
("Schedule:actor", "PractitionerRole:practitioner", "HealthcareService:location"),
),
"searchSchedule": (("Schedule:actor",), ("PractitionerRole:practitioner", "HealthcareService:location")),
"searchHealthcareService": (("HealthcareService:organization", "HealthcareService:location"), ()),
}
"""The searches that get a helper, `<method>_with_includes`, sending every include they serve: its
`_include`, then its `_include:iterate`, and nothing else of its own. tests/test_views.py holds each
`_include`, then its `_include:iterate` when it takes one, and nothing else of its own. tests/test_views.py holds each
equal to every include the spec says the search serves, so an include served later fails it until the
helper sends it."""


LEAVES_OUT: dict[str, tuple[str, ...]] = {"searchHealthcareService": ("_summary",)}
"""The parameters a helper takes no keyword for beside its includes: the HealthcareService search does not
combine `_summary` with an include, so a helper that always sends one could never answer with it."""


@dataclass
class Helper:
"""A search helper: the search, its name, the includes it sends, and the search's query less them."""
Expand All @@ -176,8 +182,8 @@ def __init__(self, spec: Json) -> None:

def _helpers(self) -> dict[str, Helper]:
"""Each search helper of WITH_INCLUDES, by the operationId of its search. The generator stops when a
search is gone, takes no `_include` or `_include:iterate`, or does not serve an include its
helper sends, rather than writing a helper that sends what the API refuses."""
search is gone, takes no `_include`, takes no `_include:iterate` its helper sends, or does not
serve an include its helper sends, rather than writing a helper that sends what the API refuses."""
helpers: dict[str, Helper] = {}
for op_id, (include, iterate) in WITH_INCLUDES.items():
op = next((o for o in self.ops if o.id == op_id), None)
Expand All @@ -192,14 +198,21 @@ def _helpers(self) -> dict[str, Helper]:
schema = p.get("schema") or {}
served[p["name"]] = list((schema.get("items") or {}).get("enum") or schema.get("enum") or [])
for wire, sent in zip(INCLUDE_PARAMS, (include, iterate), strict=True):
# A search that takes no _include:iterate gets a helper that sends none.
if wire == "_include:iterate" and not sent and wire not in served:
continue
if wire not in served:
raise ValueError(f"The search helper of {op_id}: {op_id} takes no {wire}")
refused = [value for value in sent if value not in served[wire]]
if refused:
raise ValueError(
f"The search helper of {op_id} sends {wire}={refused[0]}, which {op_id} does not serve"
)
query = [p for p in op.query if p.wire not in INCLUDE_PARAMS]
left_out = LEAVES_OUT.get(op_id, ())
missing = [wire for wire in left_out if all(p.wire != wire for p in op.query)]
if missing:
raise ValueError(f"The search helper of {op_id} leaves out {missing[0]}, which {op_id} does not take")
query = [p for p in op.query if p.wire not in INCLUDE_PARAMS and p.wire not in left_out]
helpers[op_id] = Helper(
op=op, name=f"{op.name}_with_includes", include=include, iterate=iterate, query=query
)
Expand Down Expand Up @@ -547,6 +560,16 @@ def _options(op: Op) -> str:
"for view in client.schedule_views(page):\n"
' print([location.get("name") for location in view.locations])',
),
"searchHealthcareService": (
"each pharmacy's Organization (its NPI) and its store's Location (its address) come in the same Bundle",
None,
"pharmacy_views",
"page = {await}client.search_healthcare_service_with_includes(\n"
' service_category="pharm", location_address_state="FL", location_address_postalcode="33131", active="true"\n'
")\n"
"for pharmacy in client.pharmacy_views(page):\n"
" print(pharmacy.name, pharmacy.npi, pharmacy.phone)",
),
}
"""What each helper's docstring says beside its parameters: what comes in the page, the API's defaults
it keeps, the view that reads the page, and an example."""
Expand All @@ -565,14 +588,24 @@ def _helper_doc(helper: Helper, asynchronous: bool) -> str:
comes, defaults, views, example = HELPER_WORDS[helper.op.id]
resource = helper.op.id.removeprefix("search")
kept = f", so the API's own defaults hold: {defaults}" if defaults else ""
iterated = f", then `_include:iterate` of {_named(list(helper.iterate))}" if helper.iterate else ""
takes = (
"`include` or `include_iterate`, and Python refuses either"
if helper.iterate
else "`include`, and Python refuses one"
)
left_out = [p.python for p in helper.op.query if p.wire in LEAVES_OUT.get(helper.op.id, ())]
parts = [
f"The {resource} search, with every include it serves sent for you.",
f"{comes[:1].upper()}{comes[1:]}: `_include` of {_named(list(helper.include))}, then `_include:iterate` of "
f"{_named(list(helper.iterate))}. It takes every other parameter of `{helper.op.name}` and sends nothing "
f"else{kept}. `{views}()` reads the page with no request; `pages()` follows its `next` link.",
f"{comes[:1].upper()}{comes[1:]}: `_include` of {_named(list(helper.include))}{iterated}. It takes every "
f"other parameter of `{helper.op.name}` and sends nothing else{kept}. `{views}()` reads the page with no "
"request; `pages()` follows its `next` link.",
"```python\n" + example.replace("{await}", "await " if asynchronous else "") + "\n```",
f"It takes no `include` or `include_iterate`, and Python refuses either before anything is sent: to send "
f"your own, call `{helper.op.name}`.",
f"It takes no {takes} before anything is sent: to send your own, call `{helper.op.name}`."
+ "".join(
f" Nor does it take `{name}`, which the API does not combine with an include: call `{helper.op.name}` for it."
for name in left_out
),
f"`{helper.op.method} {helper.op.path}`, {helper.op.docs}",
]
if helper.query:
Expand All @@ -596,6 +629,7 @@ def _helper_method(helper: Helper, *, client: str, asynchronous: bool, with_resp
+ "".join(
f"({p.wire!r}, {sent[p.wire]!r}), " if p.wire in sent else f"({p.wire!r}, {p.python}), "
for p in helper.op.query
if p.wire in sent or any(kept.wire == p.wire for kept in helper.query)
)
+ ")"
)
Expand Down
12 changes: 12 additions & 0 deletions src/haau3/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from ._bundle_reads import matches as matches
from ._bundle_reads import resolve as resolve
from ._bundles import next_cursor as next_cursor
from ._bundles import outcomes as outcomes
from ._client import DEFAULT_BASE_URL as DEFAULT_BASE_URL
from ._client import DEFAULT_MAX_RETRIES as DEFAULT_MAX_RETRIES
from ._client import DEFAULT_TIMEOUT as DEFAULT_TIMEOUT
Expand Down Expand Up @@ -69,9 +70,14 @@
from ._terminology import validation_result as validation_result
from ._test_data import mark_as_test_data as mark_as_test_data
from ._version import __version__ as __version__
from ._views import PartDListing as PartDListing
from ._views import PartDNetworkKind as PartDNetworkKind
from ._views import PatientType as PatientType
from ._views import PharmacyNetwork as PharmacyNetwork
from ._views import PharmacyView as PharmacyView
from ._views import ScheduleView as ScheduleView
from ._views import SlotView as SlotView
from ._views import pharmacy_views as pharmacy_views
from ._views import schedule_views as schedule_views
from ._views import slot_views as slot_views

Expand Down Expand Up @@ -107,7 +113,11 @@
"LookupResult",
"NoAnswerError",
"NoAnswerReason",
"PartDListing",
"PartDNetworkKind",
"PatientType",
"PharmacyNetwork",
"PharmacyView",
"Property",
"QueryValue",
"RawResponse",
Expand All @@ -127,8 +137,10 @@
"mark_as_test_data",
"matches",
"next_cursor",
"outcomes",
"parameter",
"parameters",
"pharmacy_views",
"resolve",
"review_flags",
"schedule_views",
Expand Down
16 changes: 15 additions & 1 deletion src/haau3/_bundles.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from ._errors import Haau3Error

if TYPE_CHECKING:
from .fhir import Bundle, BundleEntry, Reference, Resource
from .fhir import Bundle, BundleEntry, OperationOutcome, Reference, Resource

# FHIR's RESTful address: a base, a resource type, an id, and a version after _history. Each is matched
# against the whole string (fullmatch), since `$` in Python also matches before a final newline.
Expand Down Expand Up @@ -187,6 +187,20 @@ def matches_in(page: Bundle, type: str | None = None) -> list[Resource]:
return found


def outcomes(page: Bundle) -> list[OperationOutcome]:
"""A search page's own OperationOutcomes, in page order: each entry whose search mode is `outcome` and
that holds an OperationOutcome, the way a FHIR search says something about the search itself rather
than a match. Empty when there is none."""
found: list[OperationOutcome] = []
for entry in _entries(page):
search: object = entry.get("search")
mode = cast("Mapping[str, object]", search).get("mode") if isinstance(search, dict) else None
resource = entry.get("resource")
if mode == "outcome" and isinstance(resource, dict) and _type_of(resource) == "OperationOutcome":
found.append(cast("OperationOutcome", resource))
return found


def next_cursor(page: Bundle) -> str | None:
"""The cursor of a search page's `next` link: its `page` value, or None on the last page.

Expand Down
Loading