diff --git a/README.md b/README.md index 7ba89d0..fecd5c3 100644 --- a/README.md +++ b/README.md @@ -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: @@ -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 diff --git a/scripts/generate.py b/scripts/generate.py index 21ea66d..758b735 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -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, `_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.""" @@ -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) @@ -192,6 +198,9 @@ 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]] @@ -199,7 +208,11 @@ def _helpers(self) -> dict[str, Helper]: 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 ) @@ -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.""" @@ -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: @@ -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) ) + ")" ) diff --git a/src/haau3/__init__.py b/src/haau3/__init__.py index 07cd3ab..506c038 100644 --- a/src/haau3/__init__.py +++ b/src/haau3/__init__.py @@ -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 @@ -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 @@ -107,7 +113,11 @@ "LookupResult", "NoAnswerError", "NoAnswerReason", + "PartDListing", + "PartDNetworkKind", "PatientType", + "PharmacyNetwork", + "PharmacyView", "Property", "QueryValue", "RawResponse", @@ -127,8 +137,10 @@ "mark_as_test_data", "matches", "next_cursor", + "outcomes", "parameter", "parameters", + "pharmacy_views", "resolve", "review_flags", "schedule_views", diff --git a/src/haau3/_bundles.py b/src/haau3/_bundles.py index fb18471..7b83d7f 100644 --- a/src/haau3/_bundles.py +++ b/src/haau3/_bundles.py @@ -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. @@ -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. diff --git a/src/haau3/_client.py b/src/haau3/_client.py index 2d67e5c..31e7bb7 100644 --- a/src/haau3/_client.py +++ b/src/haau3/_client.py @@ -13,6 +13,7 @@ from ._app_info import AppInfo, user_agent from ._body import Hidden, Secret from ._bundles import next_cursor as _next_cursor +from ._bundles import outcomes as _outcomes from ._encode import QueryValue, checked_base_url, origin from ._env_file import unloaded_env_file from ._errors import Haau3Error, NoAnswerError @@ -28,14 +29,15 @@ from ._terminology import lookup_result as _lookup_result from ._terminology import validation_result as _validation_result from ._transport import AsyncEngine, Config, SyncEngine -from ._views import ScheduleView, SlotView +from ._views import PharmacyView, ScheduleView, 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 if TYPE_CHECKING: from typing_extensions import Self - from .fhir import Bundle, Dosage, Parameters, ParametersParameter, Resource + from .fhir import Bundle, Dosage, OperationOutcome, Parameters, ParametersParameter, Resource Environment = Literal["production", "sandbox"] """The API's two environments: `production` at https://api.haau3.com, and `sandbox` at @@ -700,6 +702,59 @@ def schedule_views(self, page: Bundle) -> list[ScheduleView]: """ return _schedule_views(page) + def pharmacy_views(self, page: Bundle) -> list[PharmacyView]: + """Each HealthcareService a search page matched, as a `PharmacyView`, with no request. + + One row per pharmacy: its NPI, name, address, phone, whether it is active and its NUCC codes, read + from the service and the Organization and store the page holds for it; what Medicare Part D says + of it, from haau3's Part D Listing extension; the networks that list it, from NDH's Network + Reference extension, and whether the plan prefers it; and the three FHIR resources as the API + served them. Nothing is replaced in place. The plain function `haau3.pharmacy_views()` does the + same with no client. + + ```python + page = client.search_healthcare_service_with_includes( + service_category="pharm", + network="Organization-part-d-H2406-013-000-retail", + location_address_postalcode="33131", + active="true", + ) + for pharmacy in client.pharmacy_views(page): + print(pharmacy.name, pharmacy.address, "preferred" if pharmacy.preferred else "") + ``` + + Raises a `Haau3Error` when a pharmacy names its Organization or store and a pharmacy search's page + does not hold it, from a search that did not ask for its include (the page's self link says what + was asked), naming the fix; when the page holds it, but not where FHIR's rules for a Bundle find it + from the reference; and when two entries could each be the one a reference names. A page from any + other search, and a service that is not a pharmacy, leave out what the page does not hold, and + nothing is fetched for it. A `part_d` of None means not + known, never not listed: `outcomes()` says why. Paging: call it on each page `pages()` gives. + """ + return _pharmacy_views(page) + + def outcomes(self, page: Bundle) -> list[OperationOutcome]: + """A search page's own OperationOutcomes, with no request: each entry whose search mode is `outcome`. + + The way a FHIR search says something about the search itself rather than a match. Empty when there + is none; `matches()` never includes them. The plain function `haau3.outcomes()` does the same with + no client. + + ```python + page = client.search_healthcare_service_with_includes( + service_category="pharm", network="Organization-part-d-H2406-013-000-mail-order" + ) + for outcome in client.outcomes(page): + for issue in outcome.get("issue", []): + print(issue.get("severity"), issue.get("details", {}).get("text")) + ``` + + A pharmacy search answers one when a Part D plan lists no pharmacy of the network's kind + (`information`, with no matches), and when the API could not read Medicare Part D's files + (`warning`, and no pharmacy carries its Part D listing). + """ + return _outcomes(page) + def _held_pages(self, page: Hidden[object], options: Options) -> Iterator[Hidden[object]]: """Each page, held, following `next` links on the client's own host to a page not yet read.""" followed: set[str] = set() @@ -1043,6 +1098,59 @@ def schedule_views(self, page: Bundle) -> list[ScheduleView]: """ return _schedule_views(page) + def pharmacy_views(self, page: Bundle) -> list[PharmacyView]: + """Each HealthcareService a search page matched, as a `PharmacyView`, with no request. + + One row per pharmacy: its NPI, name, address, phone, whether it is active and its NUCC codes, read + from the service and the Organization and store the page holds for it; what Medicare Part D says + of it, from haau3's Part D Listing extension; the networks that list it, from NDH's Network + Reference extension, and whether the plan prefers it; and the three FHIR resources as the API + served them. Nothing is replaced in place. The plain function `haau3.pharmacy_views()` does the + same with no client. + + ```python + page = await client.search_healthcare_service_with_includes( + service_category="pharm", + network="Organization-part-d-H2406-013-000-retail", + location_address_postalcode="33131", + active="true", + ) + for pharmacy in client.pharmacy_views(page): + print(pharmacy.name, pharmacy.address, "preferred" if pharmacy.preferred else "") + ``` + + Raises a `Haau3Error` when a pharmacy names its Organization or store and a pharmacy search's page + does not hold it, from a search that did not ask for its include (the page's self link says what + was asked), naming the fix; when the page holds it, but not where FHIR's rules for a Bundle find it + from the reference; and when two entries could each be the one a reference names. A page from any + other search, and a service that is not a pharmacy, leave out what the page does not hold, and + nothing is fetched for it. A `part_d` of None means not + known, never not listed: `outcomes()` says why. Paging: call it on each page `pages()` gives. + """ + return _pharmacy_views(page) + + def outcomes(self, page: Bundle) -> list[OperationOutcome]: + """A search page's own OperationOutcomes, with no request: each entry whose search mode is `outcome`. + + The way a FHIR search says something about the search itself rather than a match. Empty when there + is none; `matches()` never includes them. The plain function `haau3.outcomes()` does the same with + no client. + + ```python + page = await client.search_healthcare_service_with_includes( + service_category="pharm", network="Organization-part-d-H2406-013-000-mail-order" + ) + for outcome in client.outcomes(page): + for issue in outcome.get("issue", []): + print(issue.get("severity"), issue.get("details", {}).get("text")) + ``` + + A pharmacy search answers one when a Part D plan lists no pharmacy of the network's kind + (`information`, with no matches), and when the API could not read Medicare Part D's files + (`warning`, and no pharmacy carries its Part D listing). + """ + return _outcomes(page) + async def _held_pages(self, page: Hidden[object], options: Options) -> AsyncIterator[Hidden[object]]: """Each page, held, as `Haau3._held_pages` gives them.""" followed: set[str] = set() diff --git a/src/haau3/_methods.py b/src/haau3/_methods.py index f072354..c197c62 100644 --- a/src/haau3/_methods.py +++ b/src/haau3/_methods.py @@ -803,6 +803,85 @@ def search_healthcare_service( Options(timeout, max_retries, correlation_id, extra_headers), ).data + def search_healthcare_service_with_includes( + self, + *, + location: str | None = None, + network: str | None = None, + service_category: str | None = None, + specialty: str | None = None, + location_address_state: str | None = None, + location_address_postalcode: str | None = None, + location_address_city: str | None = None, + name: str | None = None, + organization: str | None = None, + organization_identifier: str | None = None, + active: bool | Literal["true", "false"] | None = None, + id: str | None = None, + count: int | None = None, + page: str | None = None, + timeout: float | None = None, + max_retries: int | None = None, + correlation_id: str | None = None, + extra_headers: Mapping[str, str] | None = None, + ) -> fhir.Bundle: + """The HealthcareService search, with every include it serves sent for you. + + Each pharmacy's Organization (its NPI) and its store's Location (its address) come in the same Bundle: `_include` of `HealthcareService:organization` and `HealthcareService:location`. It takes every other parameter of `search_healthcare_service` and sends nothing else. `pharmacy_views()` reads the page with no request; `pages()` follows its `next` link. + + ```python + page = client.search_healthcare_service_with_includes( + service_category="pharm", location_address_state="FL", location_address_postalcode="33131", active="true" + ) + for pharmacy in client.pharmacy_views(page): + print(pharmacy.name, pharmacy.npi, pharmacy.phone) + ``` + + It takes no `include`, and Python refuses one before anything is sent: to send your own, call `search_healthcare_service`. Nor does it take `summary`, which the API does not combine with an include: call `search_healthcare_service` for it. + + `GET /v1/fhir/r4/HealthcareService`, https://docs.haau3.com/api-reference/provider-directory/find-healthcare-services-and-pharmacies + + Query parameters, each with its name in the API: + + - `location`: The services offered at one location. Give a Location id, `Location/{id}`, or the `fullUrl` this service returned. An address on another server is refused. + - `network`: The services in one insurance network, one network a search. On the directory's own search, the services the directory lists in the network; there it cannot be used on its own, so send it beside `location`. On a pharmacy search, the pharmacies one of a Medicare Part D plan's networks lists. A Part D plan names up to four networks, one for each kind of pharmacy CMS's Part D files flag: `retail`, `mail-order`, `preferred-retail`, `preferred-mail-order`. A network's id is `Organization-part-d-{plan}-{kind}`, with the plan's id as `InsurancePlan` serves it: `Organization-part-d-H2406-013-000-preferred-retail`. A mail order network may be a pharmacy search's only criterion; a retail network narrows a search by place or name. Give a Organization id, `Organization/{id}`, or the `fullUrl` this service returned. An address on another server is refused. + - `service_category` (`service-category`): `pharm`, bare or as `http://terminology.hl7.org/CodeSystem/ndh-healthcare-service-category|pharm`: every pharmacy, of any kind. Starts a pharmacy search, as `specialty` does. A pharmacy search needs any one of: `location.address-postalcode` (a ZIP code or its first two or more digits), `location.address-state`, `name`, one pharmacy's `organization` or `organization.identifier`, or a Medicare Part D plan's mail order `network`. `location.address-city` narrows a search by state, and a retail `network` narrows a search by place or name. + - `specialty`: A NUCC pharmacy code, bare or as `http://nucc.org/provider-taxonomy|{code}`, or several separated by commas to find pharmacies of any of those kinds: for example `3336C0003X` (community or retail) or `3336M0002X` (mail order). Starts a pharmacy search. A pharmacy may carry only the general code 333600000X or only a specific one, so send `333600000X,3336C0003X` to find either, or `service-category=pharm` for every kind. Only pharmacy codes (333600000X, 3336C0002X, 3336C0003X, 3336C0004X, 3336H0001X, 3336I0012X, 3336L0003X, 3336M0002X, 3336M0003X, 3336N0007X, 3336S0011X, 332000000X, 332100000X, 332800000X) are served. A pharmacy search needs any one of: `location.address-postalcode` (a ZIP code or its first two or more digits), `location.address-state`, `name`, one pharmacy's `organization` or `organization.identifier`, or a Medicare Part D plan's mail order `network`. `location.address-city` narrows a search by state, and a retail `network` narrows a search by place or name. + - `location_address_state` (`location.address-state`): A pharmacy search's state: the two-letter code of the state the pharmacy's store is in. Stands alone on a pharmacy search, and is required beside `location.address-city`. + - `location_address_postalcode` (`location.address-postalcode`): Finds the pharmacies whose store's ZIP code starts with this: a ZIP code, ZIP+4, or its first two or more digits. Stands alone on a pharmacy search. + - `location_address_city` (`location.address-city`): Narrows a pharmacy search to stores in a city whose name starts with this, so `Miami` also finds Miami Beach. Two or more letters. Send it with `location.address-state`. + - `name`: Finds the pharmacies whose name, or a name they do business as, starts with this. Two or more letters. Stands alone on a pharmacy search. + - `organization`: One pharmacy: the organization that provides it, as a pharmacy search returned it (`Organization-pharmacy-{NPI}`). Stands alone on a pharmacy search. Give a Organization id, `Organization/{id}`, or the `fullUrl` this service returned. An address on another server is refused. + - `organization_identifier` (`organization.identifier`): One pharmacy by its NPI, as `{system}|{npi}` or a bare 10-digit value, under the same systems `Organization` accepts. Stands alone on a pharmacy search. + - `active`: `true` or `false`. Narrows a search; cannot be used on its own. On a pharmacy search, `true` keeps the pharmacies NPPES lists as active and `false` the ones it lists as deactivated since its November 2026 monthly file; without it, both are returned, each marked by `active`. + - `id` (`_id`): A HealthcareService id. Searching by id rather than reading it lets one request also bring the records an `_include` or `_revinclude` names. + - `count` (`_count`): Results are paged. `_count` sets the page size (1 to 100); a larger value is refused rather than quietly reduced. Follow `link` with relation `next` to continue. The cursor it carries is opaque and must not be constructed or modified. + - `page`: Continuation cursor. Opaque: follow the `next` link from a previous response, and never construct or modify it. Cursors expire. + """ + return self._engine.call( + SEARCH_HEALTHCARE_SERVICE, + (), + ( + ("location", location), + ("network", network), + ("service-category", service_category), + ("specialty", specialty), + ("location.address-state", location_address_state), + ("location.address-postalcode", location_address_postalcode), + ("location.address-city", location_address_city), + ("name", name), + ("organization", organization), + ("organization.identifier", organization_identifier), + ("active", active), + ("_include", ("HealthcareService:organization", "HealthcareService:location")), + ("_id", id), + ("_count", count), + ("page", page), + ), + None, + Options(timeout, max_retries, correlation_id, extra_headers), + ).data + def search_insurance_plan( self, *, @@ -3257,6 +3336,87 @@ async def search_healthcare_service( ) ).data + async def search_healthcare_service_with_includes( + self, + *, + location: str | None = None, + network: str | None = None, + service_category: str | None = None, + specialty: str | None = None, + location_address_state: str | None = None, + location_address_postalcode: str | None = None, + location_address_city: str | None = None, + name: str | None = None, + organization: str | None = None, + organization_identifier: str | None = None, + active: bool | Literal["true", "false"] | None = None, + id: str | None = None, + count: int | None = None, + page: str | None = None, + timeout: float | None = None, + max_retries: int | None = None, + correlation_id: str | None = None, + extra_headers: Mapping[str, str] | None = None, + ) -> fhir.Bundle: + """The HealthcareService search, with every include it serves sent for you. + + Each pharmacy's Organization (its NPI) and its store's Location (its address) come in the same Bundle: `_include` of `HealthcareService:organization` and `HealthcareService:location`. It takes every other parameter of `search_healthcare_service` and sends nothing else. `pharmacy_views()` reads the page with no request; `pages()` follows its `next` link. + + ```python + page = await client.search_healthcare_service_with_includes( + service_category="pharm", location_address_state="FL", location_address_postalcode="33131", active="true" + ) + for pharmacy in client.pharmacy_views(page): + print(pharmacy.name, pharmacy.npi, pharmacy.phone) + ``` + + It takes no `include`, and Python refuses one before anything is sent: to send your own, call `search_healthcare_service`. Nor does it take `summary`, which the API does not combine with an include: call `search_healthcare_service` for it. + + `GET /v1/fhir/r4/HealthcareService`, https://docs.haau3.com/api-reference/provider-directory/find-healthcare-services-and-pharmacies + + Query parameters, each with its name in the API: + + - `location`: The services offered at one location. Give a Location id, `Location/{id}`, or the `fullUrl` this service returned. An address on another server is refused. + - `network`: The services in one insurance network, one network a search. On the directory's own search, the services the directory lists in the network; there it cannot be used on its own, so send it beside `location`. On a pharmacy search, the pharmacies one of a Medicare Part D plan's networks lists. A Part D plan names up to four networks, one for each kind of pharmacy CMS's Part D files flag: `retail`, `mail-order`, `preferred-retail`, `preferred-mail-order`. A network's id is `Organization-part-d-{plan}-{kind}`, with the plan's id as `InsurancePlan` serves it: `Organization-part-d-H2406-013-000-preferred-retail`. A mail order network may be a pharmacy search's only criterion; a retail network narrows a search by place or name. Give a Organization id, `Organization/{id}`, or the `fullUrl` this service returned. An address on another server is refused. + - `service_category` (`service-category`): `pharm`, bare or as `http://terminology.hl7.org/CodeSystem/ndh-healthcare-service-category|pharm`: every pharmacy, of any kind. Starts a pharmacy search, as `specialty` does. A pharmacy search needs any one of: `location.address-postalcode` (a ZIP code or its first two or more digits), `location.address-state`, `name`, one pharmacy's `organization` or `organization.identifier`, or a Medicare Part D plan's mail order `network`. `location.address-city` narrows a search by state, and a retail `network` narrows a search by place or name. + - `specialty`: A NUCC pharmacy code, bare or as `http://nucc.org/provider-taxonomy|{code}`, or several separated by commas to find pharmacies of any of those kinds: for example `3336C0003X` (community or retail) or `3336M0002X` (mail order). Starts a pharmacy search. A pharmacy may carry only the general code 333600000X or only a specific one, so send `333600000X,3336C0003X` to find either, or `service-category=pharm` for every kind. Only pharmacy codes (333600000X, 3336C0002X, 3336C0003X, 3336C0004X, 3336H0001X, 3336I0012X, 3336L0003X, 3336M0002X, 3336M0003X, 3336N0007X, 3336S0011X, 332000000X, 332100000X, 332800000X) are served. A pharmacy search needs any one of: `location.address-postalcode` (a ZIP code or its first two or more digits), `location.address-state`, `name`, one pharmacy's `organization` or `organization.identifier`, or a Medicare Part D plan's mail order `network`. `location.address-city` narrows a search by state, and a retail `network` narrows a search by place or name. + - `location_address_state` (`location.address-state`): A pharmacy search's state: the two-letter code of the state the pharmacy's store is in. Stands alone on a pharmacy search, and is required beside `location.address-city`. + - `location_address_postalcode` (`location.address-postalcode`): Finds the pharmacies whose store's ZIP code starts with this: a ZIP code, ZIP+4, or its first two or more digits. Stands alone on a pharmacy search. + - `location_address_city` (`location.address-city`): Narrows a pharmacy search to stores in a city whose name starts with this, so `Miami` also finds Miami Beach. Two or more letters. Send it with `location.address-state`. + - `name`: Finds the pharmacies whose name, or a name they do business as, starts with this. Two or more letters. Stands alone on a pharmacy search. + - `organization`: One pharmacy: the organization that provides it, as a pharmacy search returned it (`Organization-pharmacy-{NPI}`). Stands alone on a pharmacy search. Give a Organization id, `Organization/{id}`, or the `fullUrl` this service returned. An address on another server is refused. + - `organization_identifier` (`organization.identifier`): One pharmacy by its NPI, as `{system}|{npi}` or a bare 10-digit value, under the same systems `Organization` accepts. Stands alone on a pharmacy search. + - `active`: `true` or `false`. Narrows a search; cannot be used on its own. On a pharmacy search, `true` keeps the pharmacies NPPES lists as active and `false` the ones it lists as deactivated since its November 2026 monthly file; without it, both are returned, each marked by `active`. + - `id` (`_id`): A HealthcareService id. Searching by id rather than reading it lets one request also bring the records an `_include` or `_revinclude` names. + - `count` (`_count`): Results are paged. `_count` sets the page size (1 to 100); a larger value is refused rather than quietly reduced. Follow `link` with relation `next` to continue. The cursor it carries is opaque and must not be constructed or modified. + - `page`: Continuation cursor. Opaque: follow the `next` link from a previous response, and never construct or modify it. Cursors expire. + """ + return ( + await self._engine.call( + SEARCH_HEALTHCARE_SERVICE, + (), + ( + ("location", location), + ("network", network), + ("service-category", service_category), + ("specialty", specialty), + ("location.address-state", location_address_state), + ("location.address-postalcode", location_address_postalcode), + ("location.address-city", location_address_city), + ("name", name), + ("organization", organization), + ("organization.identifier", organization_identifier), + ("active", active), + ("_include", ("HealthcareService:organization", "HealthcareService:location")), + ("_id", id), + ("_count", count), + ("page", page), + ), + None, + Options(timeout, max_retries, correlation_id, extra_headers), + ) + ).data + async def search_insurance_plan( self, *, @@ -5485,6 +5645,53 @@ def search_healthcare_service( Options(timeout, max_retries, correlation_id, extra_headers), ) + def search_healthcare_service_with_includes( + self, + *, + location: str | None = None, + network: str | None = None, + service_category: str | None = None, + specialty: str | None = None, + location_address_state: str | None = None, + location_address_postalcode: str | None = None, + location_address_city: str | None = None, + name: str | None = None, + organization: str | None = None, + organization_identifier: str | None = None, + active: bool | Literal["true", "false"] | None = None, + id: str | None = None, + count: int | None = None, + page: str | None = None, + timeout: float | None = None, + max_retries: int | None = None, + correlation_id: str | None = None, + extra_headers: Mapping[str, str] | None = None, + ) -> Response[fhir.Bundle]: + """`Haau3.search_healthcare_service_with_includes`, returning a `Response` with the request id and timing as well as the answer.""" + return self._engine.call( + SEARCH_HEALTHCARE_SERVICE, + (), + ( + ("location", location), + ("network", network), + ("service-category", service_category), + ("specialty", specialty), + ("location.address-state", location_address_state), + ("location.address-postalcode", location_address_postalcode), + ("location.address-city", location_address_city), + ("name", name), + ("organization", organization), + ("organization.identifier", organization_identifier), + ("active", active), + ("_include", ("HealthcareService:organization", "HealthcareService:location")), + ("_id", id), + ("_count", count), + ("page", page), + ), + None, + Options(timeout, max_retries, correlation_id, extra_headers), + ) + def search_insurance_plan( self, *, @@ -6759,6 +6966,53 @@ async def search_healthcare_service( Options(timeout, max_retries, correlation_id, extra_headers), ) + async def search_healthcare_service_with_includes( + self, + *, + location: str | None = None, + network: str | None = None, + service_category: str | None = None, + specialty: str | None = None, + location_address_state: str | None = None, + location_address_postalcode: str | None = None, + location_address_city: str | None = None, + name: str | None = None, + organization: str | None = None, + organization_identifier: str | None = None, + active: bool | Literal["true", "false"] | None = None, + id: str | None = None, + count: int | None = None, + page: str | None = None, + timeout: float | None = None, + max_retries: int | None = None, + correlation_id: str | None = None, + extra_headers: Mapping[str, str] | None = None, + ) -> Response[fhir.Bundle]: + """`AsyncHaau3.search_healthcare_service_with_includes`, returning a `Response` with the request id and timing as well as the answer.""" + return await self._engine.call( + SEARCH_HEALTHCARE_SERVICE, + (), + ( + ("location", location), + ("network", network), + ("service-category", service_category), + ("specialty", specialty), + ("location.address-state", location_address_state), + ("location.address-postalcode", location_address_postalcode), + ("location.address-city", location_address_city), + ("name", name), + ("organization", organization), + ("organization.identifier", organization_identifier), + ("active", active), + ("_include", ("HealthcareService:organization", "HealthcareService:location")), + ("_id", id), + ("_count", count), + ("page", page), + ), + None, + Options(timeout, max_retries, correlation_id, extra_headers), + ) + async def search_insurance_plan( self, *, diff --git a/src/haau3/_views.py b/src/haau3/_views.py index d231439..d7a9479 100644 --- a/src/haau3/_views.py +++ b/src/haau3/_views.py @@ -1,11 +1,12 @@ -"""The slot and schedule views: each Slot or Schedule a search page matched, with the resources the page -holds for it, side by side, each the FHIR resource the API served. +"""The slot, schedule and pharmacy views: each Slot or Schedule a search page matched, with the resources +the page holds for it, side by side, each the FHIR resource the API served; and each HealthcareService +a search page matched, as a pharmacy's row. Read with FHIR's rules for references in a Bundle (`_bundles.resolve_in`), page by page, with no request: FHIR adds included resources to each page. Nothing is replaced in place, so each resource stays a FHIR resource. Plain functions, with no client; the clients' methods of the same names call -them, and the search helpers (`search_slot_with_includes`, `search_schedule_with_includes`, generated) -send the includes these read. +them, and the search helpers (`search_slot_with_includes`, `search_schedule_with_includes`, +`search_healthcare_service_with_includes`, generated) send the includes these read. A value of another shape than FHIR gives it (a `physicalType` that is not an object, a code that is not a string) is read as absent, as TypeScript's optional chaining reads it, so one malformed record @@ -14,9 +15,11 @@ from __future__ import annotations +import re from collections.abc import Callable, Mapping, Sequence -from dataclasses import dataclass +from dataclasses import dataclass, replace from typing import ClassVar, Final, Literal, TypeVar, cast, final +from urllib.parse import parse_qs, urlsplit from ._bundles import matches_in, resolve_in from ._errors import Haau3Error @@ -24,9 +27,12 @@ # The FHIR types are imported when the module runs, not only for type checkers, so a framework that # reads the views' annotations at runtime (pydantic, and FastAPI through it) can resolve them. from .fhir import ( + Address, Bundle, + Coding, HealthcareService, Location, + Organization, Practitioner, PractitionerRole, Reference, @@ -54,6 +60,37 @@ _PATIENT_TYPES: Final[dict[str, PatientType]] = {code: code for code in ("newpt", "existptonly", "existptfam", "nopt")} +# The category a pharmacy's HealthcareService carries, as the API serves it: `pharm` in this code system. +_SERVICE_CATEGORY = "http://terminology.hl7.org/CodeSystem/ndh-healthcare-service-category" + +# haau3's Part D Listing extension, on each pharmacy's HealthcareService, and NDH's Network Reference. +_PART_D_LISTING = "https://fhir.haau3.com/platform/StructureDefinition/part-d-listing" +_NETWORK_REFERENCE = "http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-network-reference" + +# The NPI's identifier system, and NUCC's provider taxonomy, the code system of a pharmacy's kind. +_NPI_SYSTEM = "http://hl7.org/fhir/sid/us-npi" +_NUCC = "http://nucc.org/provider-taxonomy" + +PartDNetworkKind = Literal["retail", "mail-order", "preferred-retail", "preferred-mail-order"] +"""The kind of one of a Medicare Part D plan's networks, one for each kind of pharmacy CMS's Part D files +flag: `retail`, `mail-order`, `preferred-retail` or `preferred-mail-order`.""" + +_PART_D_NETWORK_KINDS: Final[dict[str, PartDNetworkKind]] = { + kind: kind for kind in ("retail", "mail-order", "preferred-retail", "preferred-mail-order") +} + +# A Part D network's id, as the API documents it: `Organization-part-d-`, the plan's id as InsurancePlan +# serves it (`H2406-013-000`), a dash and the kind. +_PART_D_NETWORK_ID = re.compile( + r"Organization-part-d-([A-Z][0-9]{4}-[0-9]{3}-[0-9]{3})-(retail|mail-order|preferred-retail|preferred-mail-order)", + re.ASCII, +) + +# An Organization's id in a reference, relative or absolute, with or without a version. +_ORGANIZATION_ID = re.compile( + r"(?:^|/)Organization/([A-Za-z0-9\-.]{1,64})(?:/_history/[A-Za-z0-9\-.]{1,64})?\Z", re.ASCII +) + @dataclass(frozen=True) class ScheduleView: @@ -107,6 +144,79 @@ class SlotView(ScheduleView): from another code system, or a code that system does not have.""" +@final +@dataclass(frozen=True) +class PartDListing: + """What Medicare Part D says of a pharmacy, from haau3's Part D Listing extension, each value as the + API served it.""" + + listed: bool + """Whether any Medicare Part D plan's pharmacy list names the pharmacy.""" + as_of: str + """The month CMS's Part D file covers, as a FHIR date: `2026-11`.""" + contract_year: str + """The year that file's plans are for, as a FHIR date: `2027`. From October it is the coming year.""" + + +@final +@dataclass(frozen=True) +class PharmacyNetwork: + """A network that lists a pharmacy, from NDH's Network Reference extension on its HealthcareService.""" + + id: str + """The network's Organization id: `Organization-part-d-H2406-013-000-retail`.""" + name: str | None + """The network's name, as the reference's display gives it.""" + plan: str | None + """The Part D plan's id (`H2406-013-000`), read from a Part D network's id; None for any other network.""" + kind: PartDNetworkKind | None + """The Part D network's kind, read from its id; None for any other network.""" + + +@final +@dataclass(frozen=True) +class PharmacyView: + """One matched HealthcareService of a search page, a pharmacy on a pharmacy search: the plain values a + row shows, read from it and from the Organization and store the page holds for it, what Medicare + Part D says of it, and the three FHIR resources as the API served them. + + Views compare by value, and cannot be hashed, since the resources they hold are dicts. + """ + + __hash__: ClassVar[None] = None # type: ignore[assignment] # pyright: ignore[reportIncompatibleMethodOverride] + + npi: str | None + """The NPI: the Organization's identifier in `http://hl7.org/fhir/sid/us-npi`.""" + name: str | None + """The service's name, or else the Organization's.""" + address: Address | None + """The first of its Locations with an address, the store's, or else the Organization's first address.""" + phone: str | None + """The first phone number of the service, then of its Locations, then of its Organization.""" + active: bool | None + """Whether the service is active, as it says; a pharmacy deactivated in NPPES is False.""" + specialties: tuple[Coding, ...] + """The service's codes in NUCC's provider taxonomy (`http://nucc.org/provider-taxonomy`): its kinds of + pharmacy.""" + part_d: PartDListing | None + """What Medicare Part D says of it, from haau3's Part D Listing extension. None means not known, never + not listed: the API could not read Part D's files, and says so in the page's OperationOutcome + (`outcomes()`), or the service is not a pharmacy.""" + networks: tuple[PharmacyNetwork, ...] + """The networks that list it, each once, from NDH's Network Reference extension. On a pharmacy search + narrowed by `network`, each of that Part D plan's networks that lists it, one to four.""" + preferred: bool | None + """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, as on a search not narrowed by `network`.""" + service: HealthcareService + """The matched HealthcareService.""" + organization: Organization | None + """The Organization that provides it, which holds the NPI.""" + locations: tuple[Location, ...] + """Its Locations, the pharmacy's store, each once, in the order the service names them.""" + + def _objects(value: object) -> list[Mapping[str, object]]: """The JSON objects of a JSON array; none when the value is not an array.""" if not isinstance(value, list): @@ -151,12 +261,21 @@ def _follow( Bundle, with no request. A contained resource resolves from the entry that contains it, as FHIR says. A resource of another type than the element allows is left out, as one the page does not hold is, and so is a reference that is not a Reference object.""" + found = _find(page, holders, reference, start) + if found is None or _object(found).get("resourceType") not in types: + return None + return found + + +def _find(page: Bundle, holders: _Holders, reference: object, start: Resource) -> Resource | None: + """The resource a reference names, of any type, found from `start` by FHIR's rules for a Bundle; None + for a reference that is not a Reference object.""" if not isinstance(reference, dict): return None given = cast("Mapping[str, object]", reference) holder = holders.get(start) found = resolve_in(page, cast("Reference", given), from_=holder) - if found is None or _object(found).get("resourceType") not in types: + if found is None: return None contained = (_text(given.get("reference")) or "").startswith("#") holders.note(found, holder if contained else found) @@ -219,9 +338,9 @@ def _is_virtual(location: Location) -> bool: return any(c.get("system") == _LOCATION_PHYSICAL_TYPE and c.get("code") == "vi" for c in codings) -def _extension_value(slot: Slot, url: str, read: Callable[[Mapping[str, object]], T | None]) -> T | None: +def _extension_value(holder: object, url: str, read: Callable[[Mapping[str, object]], T | None]) -> T | None: """The value of the first extension under `url` that carries the value it is read for.""" - for extension in _objects(_object(slot).get("extension")): + for extension in _objects(_object(holder).get("extension")): if extension.get("url") != url: continue value = read(extension) @@ -293,3 +412,261 @@ def slot_views(page: Bundle) -> list[SlotView]: ) ) return views + + +def _is_pharmacy(service: Mapping[str, object]) -> bool: + """Whether a HealthcareService says it is a pharmacy: category `pharm`, as the API serves every pharmacy.""" + return any( + coding.get("system") == _SERVICE_CATEGORY and coding.get("code") == "pharm" + for concept in _objects(service.get("category")) + for coding in _objects(concept.get("coding")) + ) + + +# The include that brings a pharmacy's Organization or its store. +_INCLUDE_OF: Final[dict[str, str]] = { + "Organization": "HealthcareService:organization", + "Location": "HealthcareService:location", +} + +# A reference's target type and id, when it names an entry by a RESTful address: the last type and id +# of the whole string. `\Z`, since `$` in Python also matches before a final newline. +_TYPED_TARGET = re.compile( + r"(?:^|/)([A-Z][A-Za-z]+)/([A-Za-z0-9\-.]{1,64})(?:/_history/[A-Za-z0-9\-.]{1,64})?\Z", re.ASCII +) + + +@dataclass(frozen=True) +class _SearchRun: + """What a page's self link, FHIR's record of the search that made it, says: whether it was a pharmacy + search, and the includes it asked for.""" + + pharmacy: bool + includes: tuple[str, ...] + + +def _search_run(page: Bundle) -> _SearchRun | None: + """The search run that made the page, from its self link; None when it has none that is a URL.""" + self_link = next((link for link in _objects(_object(page).get("link")) if link.get("relation") == "self"), None) + url = _text(self_link.get("url")) if self_link is not None else None + if url is None: + return None + try: + parts = urlsplit(url) + # Reading the port refuses one out of range, as a URL parser does. + _ = parts.port + query = parse_qs(parts.query, keep_blank_values=True) + except ValueError: + return None + return _SearchRun( + # The API's rule for a pharmacy search, the only search that takes these includes. + pharmacy="service-category" in query or "specialty" in query, + includes=tuple(part for value in query.get("_include", []) for part in value.split(",")), + ) + + +def _typed_target(reference: object) -> re.Match[str] | None: + """A reference's target type and id, read from the whole of its RESTful address.""" + target = _text(_object(reference).get("reference")) + return _TYPED_TARGET.search(target) if target is not None else None + + +def _names_an_entry_of(reference: object, type: str) -> bool: + """Whether a reference names an entry of `type` by its address, which a search's include brings: not + `#id`, not an identifier alone, not an entry of another type. A target whose type cannot be read from + its address, such as `urn:uuid:`, counts.""" + target = _text(_object(reference).get("reference")) + if target is None or target.strip() == "" or target.startswith("#"): + return False + named = _typed_target(reference) + return named is None or named.group(1) == type + + +def _holds_anywhere(page: Bundle, reference: object, type: str) -> bool: + """Whether the page holds a resource of `type` with the id a reference names, at any address.""" + named = _typed_target(reference) + if named is None: + return False + return any( + _object(entry.get("resource")).get("resourceType") == type + and _object(entry.get("resource")).get("id") == named.group(2) + for entry in _objects(_object(page).get("entry")) + ) + + +def _reach( + page: Bundle, + holders: _Holders, + run: _SearchRun | None, + reference: object, + service: Resource, + type: str, + pharmacy: bool, +) -> Resource | None: + """The resource a pharmacy names, of `type`. + + When a pharmacy names one the page holds no entry for, and the search that made the page was a + pharmacy search that did not ask for its include (or the page does not say what search made it), the + page was searched without its includes, and that raises, naming the fix. A page that holds the + resource where FHIR's rules for a Bundle do not resolve the reference raises, saying so. Anything else + is left out: a resource of another type, a service that is not a pharmacy, and a page from any other + search, which cannot ask for includes. + """ + found = _find(page, holders, reference, service) + if found is None and pharmacy and (run is None or run.pharmacy) and _names_an_entry_of(reference, type): + named = "an Organization" if type == "Organization" else "a Location" + if _holds_anywhere(page, reference, type): + raise Haau3Error( + f"A pharmacy in this page names {named} the page holds, 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, and the version a reference names, as the API serves them. resolve() follows the same rules." + ) + if run is None or _INCLUDE_OF[type] not in run.includes: + raise Haau3Error( + f"A pharmacy in this page names {named} the page does not hold. A pharmacy search with its " + "includes holds each pharmacy's Organization and store: search with " + "search_healthcare_service_with_includes, or send " + 'include=["HealthcareService:organization", "HealthcareService:location"].' + ) + if found is None or _object(found).get("resourceType") != type: + return None + return found + + +def _non_empty(value: object) -> str | None: + """A string with something in it besides spaces, as served; None for anything else.""" + return value if isinstance(value, str) and value.strip() != "" else None + + +def _first_phone(*holders: object) -> str | None: + """The first phone number among the holders' telecoms, in order.""" + for holder in holders: + for point in _objects(_object(holder).get("telecom")): + value = _non_empty(point.get("value")) + if point.get("system") == "phone" and value is not None: + return value + return None + + +def _part_d_listing(extension: Mapping[str, object]) -> PartDListing | None: + """The Part D Listing's three parts, when the extension carries all three.""" + parts = _objects(extension.get("extension")) + + def part(url: str) -> Mapping[str, object]: + return next((sub for sub in parts if sub.get("url") == url), _object(None)) + + listed = part("listed").get("valueBoolean") + as_of = _non_empty(part("asOf").get("valueDate")) + contract_year = _non_empty(part("contractYear").get("valueDate")) + if not isinstance(listed, bool) or as_of is None or contract_year is None: + return None + return PartDListing(listed=listed, as_of=as_of, contract_year=contract_year) + + +def _networks(service: Mapping[str, object]) -> tuple[PharmacyNetwork, ...]: + """The networks a service's Network References name, each once; a reference naming no Organization by id + is left out.""" + networks: list[PharmacyNetwork] = [] + for extension in _objects(service.get("extension")): + if extension.get("url") != _NETWORK_REFERENCE: + continue + reference = _object(extension.get("valueReference")) + target = _text(reference.get("reference")) + found = _ORGANIZATION_ID.search(target) if target is not None else None + if found is None: + continue + network_id = found.group(1) + name = _non_empty(reference.get("display")) + known = next((i for i, network in enumerate(networks) if network.id == network_id), None) + if known is not None: + # A network named once without a display takes the name a later reference gives. + if networks[known].name is None and name is not None: + networks[known] = replace(networks[known], name=name) + continue + part_d = _PART_D_NETWORK_ID.fullmatch(network_id) + networks.append( + PharmacyNetwork( + id=network_id, + name=name, + plan=part_d.group(1) if part_d else None, + kind=_PART_D_NETWORK_KINDS[part_d.group(2)] if part_d else None, + ) + ) + return tuple(networks) + + +def pharmacy_views(page: Bundle) -> list[PharmacyView]: + """Each HealthcareService a search page matched, in page order, as a pharmacy's row, with no request. + + Matches are entries whose search mode is `match` or says none, and of type HealthcareService. Raises a + `Haau3Error` when a pharmacy (category `pharm`) names an Organization or Location the page does not + hold on a pharmacy search that did not ask for its include, which means the page was searched without + its includes (the page's self link says what was asked; a page without one is read as a search that + asked for nothing); when the page holds it but not where FHIR's rules for a Bundle find it from the + reference; and when two entries could each be the one a reference names. Anything else is left out: a + resource of another type than its element allows, one 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. + """ + holders = _Holders() + run = _search_run(page) + views: list[PharmacyView] = [] + for matched in matches_in(page, "HealthcareService"): + service = cast("HealthcareService", matched) + fields = _object(service) + pharmacy = _is_pharmacy(fields) + organization = cast( + "Organization | None", + _reach(page, holders, run, fields.get("providedBy"), matched, "Organization", pharmacy), + ) + locations: list[Location] = [] + for reference in _objects(fields.get("location")): + location = _reach(page, holders, run, reference, matched, "Location", pharmacy) + if location is not None: + _once(locations, cast("Location", location)) + org = _object(organization) + npi = next( + ( + value + for identifier in _objects(org.get("identifier")) + if identifier.get("system") == _NPI_SYSTEM + and (value := _non_empty(identifier.get("value"))) is not None + ), + None, + ) + address = next( + ( + cast("Address", place) + for place in ( + *(_object(location).get("address") for location in locations), + *_objects(org.get("address")), + ) + if isinstance(place, dict) and place + ), + None, + ) + networks = _networks(fields) + kinds = [network.kind for network in networks if network.kind is not None] + active = fields.get("active") + views.append( + PharmacyView( + npi=npi, + name=_non_empty(fields.get("name")) or _non_empty(org.get("name")), + address=address, + phone=_first_phone(service, *locations, organization), + active=active if isinstance(active, bool) else None, + specialties=tuple( + cast("Coding", coding) + for concept in _objects(fields.get("specialty")) + for coding in _objects(concept.get("coding")) + if coding.get("system") == _NUCC + ), + part_d=_extension_value(service, _PART_D_LISTING, _part_d_listing), + networks=networks, + preferred=None if not kinds else any(kind.startswith("preferred-") for kind in kinds), + service=service, + organization=organization, + locations=tuple(locations), + ) + ) + return views diff --git a/src/haau3/types.py b/src/haau3/types.py index 203800c..05f2dd3 100644 --- a/src/haau3/types.py +++ b/src/haau3/types.py @@ -185,6 +185,25 @@ class SearchHealthcareServiceQuery(TypedDict, total=False): page: str +class SearchHealthcareServiceWithIncludesQuery(TypedDict, total=False): + """The query parameters of `search_healthcare_service_with_includes`, by their Python names, to pass as `**query`: those of `search_healthcare_service` less its includes, which it sends itself.""" + + location: str + network: str + service_category: str + specialty: str + location_address_state: str + location_address_postalcode: str + location_address_city: str + name: str + organization: str + organization_identifier: str + active: bool | Literal["true", "false"] + id: str + count: int + page: str + + SearchHealthcareServiceResponse: TypeAlias = fhir.Bundle """What `search_healthcare_service` answers with.""" diff --git a/tests/test_generate.py b/tests/test_generate.py index b64b73a..4122d40 100644 --- a/tests/test_generate.py +++ b/tests/test_generate.py @@ -402,12 +402,26 @@ def test_the_generator_refuses_a_search_helper_that_sends_an_include_the_search_ assert set(generate.Spec(SPEC).helpers) == set(generate.WITH_INCLUDES) -def test_a_search_helpers_query_is_its_searchs_less_the_includes() -> None: +def test_a_search_helpers_query_is_its_searchs_less_the_includes_and_what_it_leaves_out() -> None: spec = generate.Spec(SPEC) for op_id, helper in spec.helpers.items(): search = next(o for o in spec.ops if o.id == op_id) - assert [p.wire for p in helper.query] == [p.wire for p in search.query if p.wire not in generate.INCLUDE_PARAMS] + left_out = generate.LEAVES_OUT.get(op_id, ()) + assert [p.wire for p in helper.query] == [ + p.wire for p in search.query if p.wire not in generate.INCLUDE_PARAMS and p.wire not in left_out + ] assert helper.name == f"{search.name}_with_includes" + # The HealthcareService search does not combine _summary with an include. + assert generate.LEAVES_OUT == {"searchHealthcareService": ("_summary",)} + assert "_summary" in [p.wire for p in next(o for o in spec.ops if o.id == "searchHealthcareService").query] + + +def test_a_helper_that_leaves_out_a_parameter_its_search_does_not_take_stops_the_generator( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setitem(generate.LEAVES_OUT, "searchHealthcareService", ("_elements",)) + with pytest.raises(ValueError, match="leaves out _elements, which searchHealthcareService does not take"): + generate.Spec(SPEC) def test_a_list_parameter_takes_one_value_or_a_list() -> None: diff --git a/tests/test_operations.py b/tests/test_operations.py index a37f726..c308b9e 100644 --- a/tests/test_operations.py +++ b/tests/test_operations.py @@ -118,8 +118,11 @@ def test_the_clients_have_one_method_per_operation_and_nothing_else(cls: type) - "resolve", "slot_views", "schedule_views", + "pharmacy_views", + "outcomes", "search_slot_with_includes", "search_schedule_with_includes", + "search_healthcare_service_with_includes", "parameters", "parameter", "review_flags", @@ -139,7 +142,7 @@ def test_the_clients_have_one_method_per_operation_and_nothing_else(cls: type) - @pytest.mark.parametrize("cls", [haau3.SyncWithResponse, haau3.AsyncWithResponse]) def test_with_response_has_every_method_and_the_batch(cls: type) -> None: - helpers = {"search_slot_with_includes", "search_schedule_with_includes"} + helpers = {"search_slot_with_includes", "search_schedule_with_includes", "search_healthcare_service_with_includes"} assert _public(cls) == {naming.method_name(o[0]) for o in OPERATIONS} | {"batch"} | helpers @@ -149,11 +152,15 @@ def test_async_methods_are_coroutines_and_sync_ones_are_not() -> None: assert inspect.iscoroutinefunction(getattr(AsyncHaau3, name)) assert not inspect.iscoroutinefunction(getattr(Haau3, name)) # The search helpers send, so they are awaited too; the readers send nothing, so they are not. - for name in ("search_slot_with_includes", "search_schedule_with_includes"): + for name in ( + "search_slot_with_includes", + "search_schedule_with_includes", + "search_healthcare_service_with_includes", + ): assert inspect.iscoroutinefunction(getattr(AsyncHaau3, name)) assert inspect.iscoroutinefunction(getattr(haau3.AsyncWithResponse, name)) assert not inspect.iscoroutinefunction(getattr(Haau3, name)) - for name in ("slot_views", "schedule_views", "resolve", "matches", "next_cursor"): + for name in ("slot_views", "schedule_views", "pharmacy_views", "outcomes", "resolve", "matches", "next_cursor"): assert not inspect.iscoroutinefunction(getattr(AsyncHaau3, name)) diff --git a/tests/test_pharmacy_views.py b/tests/test_pharmacy_views.py new file mode 100644 index 0000000..1cb3002 --- /dev/null +++ b/tests/test_pharmacy_views.py @@ -0,0 +1,877 @@ +"""The pharmacy views: each matched HealthcareService as one row, with the plain values read from it and +from the Organization and store the page holds for it, what Medicare Part D says of it, and the networks +that list it; outcomes(), a search page's own OperationOutcomes; and the HealthcareService search +helper, which sends both includes a pharmacy search serves and nothing else.""" + +from __future__ import annotations + +import dataclasses +import inspect +import re +from typing import Any + +import generate +import pytest + +import haau3 +from haau3 import Haau3Error, PartDListing, PharmacyNetwork, PharmacyView, outcomes, pharmacy_views + +from .helpers import REQUEST_ID, Client, Recorder, answer, example_answer, spec_operation, sync_client + +BASE = "https://api.haau3.com/v1/fhir/r4" +CATEGORY = "http://terminology.hl7.org/CodeSystem/ndh-healthcare-service-category" +NPI = "http://hl7.org/fhir/sid/us-npi" +NUCC = "http://nucc.org/provider-taxonomy" +LISTING = "https://fhir.haau3.com/platform/StructureDefinition/part-d-listing" +NETWORK = "http://hl7.org/fhir/us/ndh/StructureDefinition/base-ext-network-reference" +EMPTY_SEARCH: Any = {"resourceType": "Bundle", "type": "searchset", "total": 0} +INCLUDES = ["HealthcareService:organization", "HealthcareService:location"] + + +def page(*entries: tuple[Any, str]) -> Any: + """A search page: each entry at its address on the base, with its search mode.""" + + def entry(resource: Any, mode: str) -> Any: + found: Any = {"resource": resource, "search": {"mode": mode}} + if isinstance(resource, dict) and resource.get("id"): + found["fullUrl"] = f"{BASE}/{resource['resourceType']}/{resource['id']}" + return found + + return {"resourceType": "Bundle", "type": "searchset", "entry": [entry(r, mode) for r, mode in entries]} + + +def pharmacy(npi: str, **more: Any) -> Any: + """A pharmacy's service, naming its Organization and store by the NPI given.""" + return { + "resourceType": "HealthcareService", + "id": f"HealthcareService-{npi}", + "active": True, + "category": [{"coding": [{"system": CATEGORY, "code": "pharm", "display": "Pharmacy"}]}], + "providedBy": {"reference": f"Organization/Organization-{npi}"}, + "location": [{"reference": f"Location/Location-{npi}"}], + "name": f"Corner Pharmacy {npi}", + **more, + } + + +def organization(npi: str, **more: Any) -> Any: + return { + "resourceType": "Organization", + "id": f"Organization-{npi}", + "identifier": [{"system": NPI, "value": npi}], + "name": f"Corner Pharmacy LLC {npi}", + **more, + } + + +def store(npi: str, **more: Any) -> Any: + return { + "resourceType": "Location", + "id": f"Location-{npi}", + "address": {"line": [f"{npi[-3:]} Main St"], "city": "Springfield", "state": "IL", "postalCode": "62701"}, + **more, + } + + +def held(service: Any, org: Any, location: Any) -> list[tuple[Any, str]]: + """A pharmacy with its Organization and store included, as a search with both includes answers it.""" + return [(service, "match"), (org, "include"), (location, "include")] + + +def one(service: Any, org: Any = None, location: Any = None) -> Any: + """One pharmacy's page, with its Organization and store.""" + return page(*held(service, org or organization("1000000001"), location or store("1000000001"))) + + +def row(service: Any, org: Any = None, location: Any = None) -> PharmacyView: + [found] = pharmacy_views(one(service, org, location)) + return found + + +def listing(*parts: Any) -> Any: + return {"url": LISTING, "extension": list(parts)} + + +def listed(value: bool, as_of: str = "2026-11", contract_year: str = "2027") -> Any: + return listing( + {"url": "listed", "valueBoolean": value}, + {"url": "asOf", "valueDate": as_of}, + {"url": "contractYear", "valueDate": contract_year}, + ) + + +def network(reference: str, display: str | None = None) -> Any: + value: Any = {"reference": reference} + if display is not None: + value["display"] = display + return {"url": NETWORK, "valueReference": value} + + +def spec_pharmacies() -> Any: + return example_answer(spec_operation("GET", "/v1/fhir/r4/HealthcareService")) + + +# --- the spec's own example answer ----------------------------------------------------------------- + + +def test_the_spec_example_gives_each_pharmacy_a_row_with_its_npi_store_and_part_d_listing() -> None: + answer_page = spec_pharmacies() + rows = pharmacy_views(answer_page) + matched = [e for e in answer_page["entry"] if e["search"]["mode"] == "match"] + assert len(rows) == len(matched) > 1 + held_resources = [e["resource"] for e in answer_page["entry"]] + for each in rows: + assert each.npi is not None and len(each.npi) == 10 and each.npi.isdigit() + assert each.organization is not None and each.organization.get("id") == f"Organization-pharmacy-{each.npi}" + assert len(each.locations) == 1 + assert each.address is not None and each.address.get("postalCode", "").startswith("33131") + assert each.name and each.phone and each.active is True + assert each.specialties and all(coding.get("system") == NUCC for coding in each.specialties) + assert each.part_d is not None + assert len(each.part_d.as_of) == 7 and len(each.part_d.contract_year) == 4 + # A search not narrowed by `network` names none. + assert (each.networks, each.preferred) == ((), None) + # Each is the resource the page holds, not a copy. + for resource in (each.service, each.organization, *each.locations): + assert any(resource is held_resource for held_resource in held_resources) + assert outcomes(answer_page) == [] + + +# --- the plain values ------------------------------------------------------------------------------- + + +def test_the_npi_is_the_organizations_identifier_in_the_npi_system_only_the_first_with_a_value() -> None: + identifiers = [ + {"system": "http://example.com/store-number", "value": "42"}, + {"system": NPI}, + {"system": NPI, "value": ""}, + {"system": NPI, "value": "1000000002"}, + ] + assert row(pharmacy("1000000001"), organization("1000000001", identifier=identifiers)).npi == "1000000002" + other = [{"system": "http://example.com/store-number", "value": "1000000001"}] + assert row(pharmacy("1000000001"), organization("1000000001", identifier=other)).npi is None + blank = [{"system": NPI, "value": " "}] + assert row(pharmacy("1000000001"), organization("1000000001", identifier=blank)).npi is None + + +def test_the_name_is_the_services_or_else_the_organizations() -> None: + assert row(pharmacy("1000000001")).name == "Corner Pharmacy 1000000001" + assert row(pharmacy("1000000001", name="")).name == "Corner Pharmacy LLC 1000000001" + assert row(pharmacy("1000000001", name=" ")).name == "Corner Pharmacy LLC 1000000001" + unnamed = pharmacy("1000000001") + del unnamed["name"] + assert row(unnamed).name == "Corner Pharmacy LLC 1000000001" + + +def test_the_address_is_the_first_location_with_one_or_else_the_organizations_first() -> None: + two_stores = pharmacy( + "1000000001", location=[{"reference": "Location/bare"}, {"reference": "Location/Location-1000000001"}] + ) + bare = {"resourceType": "Location", "id": "bare"} + [first] = pharmacy_views( + page( + (two_stores, "match"), + (organization("1000000001"), "include"), + (bare, "include"), + (store("1000000001"), "include"), + ) + ) + assert first.address is not None and first.address.get("line") == ["001 Main St"] + assert [location.get("id") for location in first.locations] == ["bare", "Location-1000000001"] + + org_address = {"line": ["9 Market Sq"], "city": "Springfield"} + no_store_address = store("1000000001") + del no_store_address["address"] + with_org_address = organization("1000000001", address=[org_address, {"city": "Elsewhere"}]) + assert row(pharmacy("1000000001"), with_org_address, no_store_address).address == org_address + empty = organization("1000000001", address=[{}, org_address]) + assert row(pharmacy("1000000001"), empty, store("1000000001", address={})).address == org_address + # Both have one: the store's. + both = row(pharmacy("1000000001"), organization("1000000001", address=[org_address]), store("1000000001")).address + assert both is not None and both.get("line") == ["001 Main St"] + assert row(pharmacy("1000000001"), organization("1000000001"), no_store_address).address is None + + +def test_the_phone_is_the_first_of_the_service_then_its_locations_then_its_organization() -> None: + fax = {"system": "fax", "value": "555-0100"} + service = pharmacy( + "1000000001", telecom=[fax, {"system": "phone", "value": ""}, {"system": "phone", "value": "555-0101"}] + ) + location = store("1000000001", telecom=[{"system": "phone", "value": "555-0102"}]) + org = organization("1000000001", telecom=[{"system": "phone", "value": "555-0103"}]) + assert row(service, org, location).phone == "555-0101" + assert row(pharmacy("1000000001", telecom=[fax]), org, location).phone == "555-0102" + assert row(pharmacy("1000000001"), org, store("1000000001")).phone == "555-0103" + assert row(pharmacy("1000000001"), organization("1000000001"), store("1000000001")).phone is None + + +def test_active_is_what_the_service_says_and_none_when_it_says_nothing() -> None: + assert row(pharmacy("1000000001", active=False)).active is False + silent = pharmacy("1000000001") + del silent["active"] + assert row(silent).active is None + assert row(pharmacy("1000000001", active="true")).active is None + + +def test_the_specialties_are_every_nucc_coding_in_order_and_no_other_systems() -> None: + retail = {"system": NUCC, "code": "3336C0003X", "display": "Community/Retail Pharmacy"} + general = {"system": NUCC, "code": "333600000X"} + specialty = [ + {"coding": [general, {"system": "http://snomed.info/sct", "code": "264372000"}]}, + {"text": "no coding"}, + {"coding": [retail]}, + ] + assert row(pharmacy("1000000001", specialty=specialty)).specialties == (general, retail) + assert row(pharmacy("1000000001")).specialties == () + + +# --- what Medicare Part D says --------------------------------------------------------------------- + + +def test_part_d_is_the_listings_three_parts_as_served_listed_or_not() -> None: + assert row(pharmacy("1000000001", extension=[listed(True)])).part_d == PartDListing( + listed=True, as_of="2026-11", contract_year="2027" + ) + assert row(pharmacy("1000000001", extension=[listed(False, "2027-01")])).part_d == PartDListing( + listed=False, as_of="2027-01", contract_year="2027" + ) + + +def test_part_d_is_none_not_known_when_the_service_carries_no_listing() -> None: + assert row(pharmacy("1000000001")).part_d is None + + +def test_part_d_is_none_for_a_listing_missing_a_part_or_of_another_type_and_the_first_whole_one_is_read() -> None: + missing = listing({"url": "listed", "valueBoolean": True}, {"url": "asOf", "valueDate": "2026-11"}) + wrong_type = listing( + {"url": "listed", "valueString": "true"}, + {"url": "asOf", "valueDate": "2026-11"}, + {"url": "contractYear", "valueDate": "2027"}, + ) + quoted = listing( + {"url": "listed", "valueBoolean": "true"}, + {"url": "asOf", "valueDate": "2026-11"}, + {"url": "contractYear", "valueDate": "2027"}, + ) + empty_date = listing( + {"url": "listed", "valueBoolean": True}, + {"url": "asOf", "valueDate": ""}, + {"url": "contractYear", "valueDate": "2027"}, + ) + for bad in (missing, wrong_type, quoted, empty_date): + assert row(pharmacy("1000000001", extension=[bad])).part_d is None + first_whole = row(pharmacy("1000000001", extension=[missing, listed(False)])).part_d + assert first_whole is not None and first_whole.listed is False + # Two whole listings: the first. + assert row(pharmacy("1000000001", extension=[listed(True), listed(False, "2026-12")])).part_d == PartDListing( + listed=True, as_of="2026-11", contract_year="2027" + ) + # A part repeated: the first of its url, so a first that is not usable leaves the listing unknown. + listed_twice = listing( + {"url": "listed", "valueString": "true"}, + {"url": "listed", "valueBoolean": True}, + {"url": "asOf", "valueDate": "2026-11"}, + {"url": "contractYear", "valueDate": "2027"}, + ) + assert row(pharmacy("1000000001", extension=[listed_twice])).part_d is None + + +def test_part_d_is_read_under_its_own_url_only() -> None: + elsewhere = {**listed(True), "url": "https://example.com/StructureDefinition/part-d-listing"} + assert row(pharmacy("1000000001", extension=[elsewhere])).part_d is None + + +# --- the networks that list it --------------------------------------------------------------------- + + +def test_each_part_d_network_is_named_with_its_plan_and_kind_read_from_its_id_and_its_display() -> None: + service = pharmacy( + "1000000001", + extension=[ + listed(True), + network("Organization/Organization-part-d-H2406-013-000-retail", "A plan: retail pharmacies, 2027"), + network("Organization/Organization-part-d-H2406-013-000-preferred-retail"), + ], + ) + assert row(service).networks == ( + PharmacyNetwork( + id="Organization-part-d-H2406-013-000-retail", + name="A plan: retail pharmacies, 2027", + plan="H2406-013-000", + kind="retail", + ), + PharmacyNetwork( + id="Organization-part-d-H2406-013-000-preferred-retail", + name=None, + plan="H2406-013-000", + kind="preferred-retail", + ), + ) + + +def test_an_absolute_or_versioned_reference_is_read_another_network_has_no_plan_or_kind_and_each_comes_once() -> None: + service = pharmacy( + "1000000001", + extension=[ + network(f"{BASE}/Organization/Organization-part-d-S5743-001-000-mail-order"), + network("Organization/Organization-part-d-S5743-001-000-mail-order/_history/2", "A plan: mail order, 2027"), + network("Organization/Organization-ea579d05-454e-4359-8751-900c940a599a", "A directory network"), + # Ids that only look like a Part D network's: a kind it does not have, a plan id of another shape. + network("Organization/Organization-part-d-S5743-001-000-specialty"), + network("Organization/Organization-part-d-S5743-1-0-retail"), + network("Organization/Organization-part-d-S5743-001-000-retailx"), + network("Organization/Organization-ea579d05-454e-4359-8751-900c940a599a", "Another name for it"), + network("https://ehr.example/api/FHIR/R4/Organization/Organization-part-d-S5743-001-000-retail"), + ], + ) + assert row(service).networks == ( + PharmacyNetwork( + id="Organization-part-d-S5743-001-000-mail-order", + name="A plan: mail order, 2027", + plan="S5743-001-000", + kind="mail-order", + ), + PharmacyNetwork( + id="Organization-ea579d05-454e-4359-8751-900c940a599a", name="A directory network", plan=None, kind=None + ), + PharmacyNetwork(id="Organization-part-d-S5743-001-000-specialty", name=None, plan=None, kind=None), + PharmacyNetwork(id="Organization-part-d-S5743-1-0-retail", name=None, plan=None, kind=None), + PharmacyNetwork(id="Organization-part-d-S5743-001-000-retailx", name=None, plan=None, kind=None), + PharmacyNetwork(id="Organization-part-d-S5743-001-000-retail", name=None, plan="S5743-001-000", kind="retail"), + ) + + +def test_networks_are_read_from_ndhs_network_reference_only() -> None: + elsewhere = { + **network("Organization/Organization-part-d-H2406-013-000-preferred-retail"), + "url": "http://example.com/StructureDefinition/network", + } + found = row(pharmacy("1000000001", extension=[elsewhere])) + assert (found.networks, found.preferred) == ((), None) + + +def test_a_reference_that_names_no_organization_by_id_is_left_out() -> None: + service = pharmacy( + "1000000001", + extension=[ + network("Location/Location-1000000001"), + network("#contained"), + network("Organization/Organization-part-d-H2406-013-000-retail\n"), + {"url": NETWORK, "valueReference": {"identifier": {"value": "network-7"}}}, + {"url": NETWORK, "valueString": "Organization/Organization-part-d-H2406-013-000-retail"}, + ], + ) + assert row(service).networks == () + + +def test_preferred_says_whether_a_part_d_network_is_preferred_retail_or_preferred_mail_order() -> None: + def preferred_of(*ids: str) -> bool | None: + return row(pharmacy("1000000001", extension=[network(f"Organization/{i}") for i in ids])).preferred + + assert ( + preferred_of("Organization-part-d-H2406-013-000-retail", "Organization-part-d-H2406-013-000-preferred-retail") + is True + ) + assert ( + preferred_of( + "Organization-part-d-H2406-013-000-mail-order", "Organization-part-d-H2406-013-000-preferred-mail-order" + ) + is True + ) + assert preferred_of("Organization-part-d-H2406-013-000-retail") is False + assert preferred_of("Organization-part-d-H2406-013-000-mail-order") is False + # Named by no network, or by networks that are not Part D's: not known. + assert preferred_of() is None + assert preferred_of("Organization-ea579d05-454e-4359-8751-900c940a599a") is None + assert ( + preferred_of("Organization-ea579d05-454e-4359-8751-900c940a599a", "Organization-part-d-H2406-013-000-retail") + is False + ) + + +# --- what the page holds ------------------------------------------------------------------------- + + +def test_a_pharmacy_naming_an_organization_the_page_does_not_hold_raises_naming_the_helper() -> None: + bundle = page((pharmacy("1000000001"), "match"), (store("1000000001"), "include")) + with pytest.raises( + Haau3Error, match=r"names an Organization the page does not hold.*search_healthcare_service_with_includes" + ): + pharmacy_views(bundle) + + +def test_a_pharmacy_naming_a_location_the_page_does_not_hold_raises_naming_the_helper() -> None: + bundle = page((pharmacy("1000000001"), "match"), (organization("1000000001"), "include")) + with pytest.raises( + Haau3Error, match=r"names a Location the page does not hold.*search_healthcare_service_with_includes" + ): + pharmacy_views(bundle) + + +def test_the_spec_example_searched_without_its_includes_raises() -> None: + answer_page = spec_pharmacies() + self_link = next(link["url"] for link in answer_page["link"] if link["relation"] == "self") + without = re.sub(r"&_include=[^&]*", "", self_link) + bare: Any = { + **answer_page, + "link": [{"relation": "self", "url": without}], + "entry": [e for e in answer_page["entry"] if e["search"]["mode"] == "match"], + } + with pytest.raises( + Haau3Error, match=r"names an Organization the page does not hold.*search_healthcare_service_with_includes" + ): + pharmacy_views(bare) + + +def test_whether_a_missing_record_was_asked_for_is_read_from_the_pages_self_link() -> None: + def missing_store(self_link: str | None = None) -> Any: + bundle = page((pharmacy("1000000001"), "match"), (organization("1000000001"), "include")) + if self_link is not None: + bundle["link"] = [{"relation": "self", "url": self_link}] + return bundle + + search = f"{BASE}/HealthcareService?service-category=pharm&location.address-postalcode=62701" + # A pharmacy search that did not ask for the store's include, or a page that does not say: searched + # without its includes. + for self_link in ( + f"{search}&_include=HealthcareService%3Aorganization", + f"{BASE}/HealthcareService?specialty=3336C0003X", + None, + "http://[not a url", + ): + with pytest.raises(Haau3Error, match="names a Location the page does not hold"): + pharmacy_views(missing_store(self_link)) + # Asked for and still missing: left out, since the fix the message names would change nothing. + [asked] = pharmacy_views( + missing_store(f"{search}&_include=HealthcareService%3Aorganization&_include=HealthcareService%3Alocation") + ) + assert (asked.locations, asked.npi) == ((), "1000000001") + # A page from the directory's own search, which cannot ask for includes, never raises, whatever it holds. + [directory] = pharmacy_views(missing_store(f"{BASE}/HealthcareService?location=Location/Location-6e138dc1")) + assert directory.locations == () + # Both includes asked for in one value, separated by a comma. + [comma_joined] = pharmacy_views( + missing_store(f"{search}&_include=HealthcareService%3Aorganization%2CHealthcareService%3Alocation") + ) + assert comma_joined.locations == () + # A self link a URL parser refuses, here for a port out of range, says nothing: today's rule. + with pytest.raises(Haau3Error, match="names a Location the page does not hold"): + pharmacy_views(missing_store("http://x:99999/HealthcareService?location=Location/x")) + + +def test_a_blank_reference_names_nothing_so_a_pharmacy_whose_reference_is_blank_does_not_raise() -> None: + for blank in ("", " "): + service = pharmacy("1000000001", providedBy={"reference": blank}) + [found] = pharmacy_views(page((service, "match"), (store("1000000001"), "include"))) + assert found.organization is None + + +def test_a_record_held_where_fhirs_rules_do_not_find_it_is_said_so_rather_than_blamed_on_the_includes() -> None: + # The store is held at another base than the service that names it relatively. + elsewhere = page((pharmacy("1000000001"), "match"), (organization("1000000001"), "include")) + elsewhere["entry"].append( + { + "fullUrl": "https://mirror.example/fhir/Location/Location-1000000001", + "resource": store("1000000001"), + "search": {"mode": "include"}, + } + ) + with pytest.raises(Haau3Error, match="names a Location the page holds, but not where FHIR's rules for a Bundle"): + pharmacy_views(elsewhere) + # The service at no address of its own: a relative reference resolves against nothing. + unaddressed = one(pharmacy("1000000001")) + del unaddressed["entry"][0]["fullUrl"] + with pytest.raises(Haau3Error, match="names an Organization the page holds, but not where"): + pharmacy_views(unaddressed) + # A version the page does not hold. + versioned = one( + pharmacy("1000000001", providedBy={"reference": "Organization/Organization-1000000001/_history/2"}), + organization("1000000001", meta={"versionId": "1"}), + ) + with pytest.raises(Haau3Error, match=r"the page holds, but not where .* and the version a reference names"): + pharmacy_views(versioned) + # An absolute reference on another server whose path holds a capitalised segment before the type. + deep_base = page( + ( + pharmacy( + "1000000001", + providedBy={"reference": "https://ehr.example/api/FHIR/R4/Organization/Organization-1000000001"}, + ), + "match", + ), + (organization("1000000001"), "include"), + (store("1000000001"), "include"), + ) + deep_base["link"] = [ + { + "relation": "self", + "url": f"{BASE}/HealthcareService?service-category=pharm" + "&_include=HealthcareService:organization&_include=HealthcareService:location", + } + ] + with pytest.raises(Haau3Error, match="names an Organization the page holds, but not where"): + pharmacy_views(deep_base) + + +def test_the_includes_are_blamed_not_the_addresses_when_the_page_holds_another_type_with_the_id() -> None: + # The page holds a Location whose id is the one the Organization reference names. + lookalike = page((pharmacy("1000000001"), "match"), (store("1000000001", id="Organization-1000000001"), "include")) + with pytest.raises(Haau3Error, match="names an Organization the page does not hold"): + pharmacy_views(lookalike) + + +def test_a_reference_to_another_type_the_page_does_not_hold_is_left_out_rather_than_raised_for() -> None: + wrong_type = pharmacy( + "1000000001", + providedBy={"reference": "Practitioner/Practitioner-1"}, + location=[{"reference": "Organization/Organization-elsewhere"}, {"reference": "Location/Location-1000000001"}], + ) + found = row(wrong_type) + assert found.organization is None + assert [location.get("id") for location in found.locations] == ["Location-1000000001"] + # An absolute reference to another type, on a server whose path holds a capitalised segment: left out. + absolute_wrong_type = pharmacy( + "1000000001", providedBy={"reference": "https://ehr.example/api/FHIR/R4/Location/L9"} + ) + [found_absolute] = pharmacy_views(page((absolute_wrong_type, "match"), (store("1000000001"), "include"))) + assert found_absolute.organization is None + # A type name with something before it is no type: taken as the one it should be. + glued = pharmacy("1000000001", providedBy={"reference": "https://example.org/fhir/xLocation/abc"}) + with pytest.raises(Haau3Error, match="names an Organization the page does not hold"): + pharmacy_views(page((glued, "match"), (store("1000000001"), "include"))) + # A target whose type its address does not say is taken as the one it should be. + by_uuid = pharmacy("1000000001", providedBy={"reference": "urn:uuid:3f2504e0-4f89-11d3-9a0c-0305e82c3301"}) + with pytest.raises(Haau3Error, match="names an Organization the page does not hold"): + pharmacy_views(page((by_uuid, "match"), (store("1000000001"), "include"))) + + +def test_a_service_that_is_not_a_pharmacy_leaves_out_what_the_page_does_not_hold() -> None: + directory = { + "resourceType": "HealthcareService", + "id": "HealthcareService-0009bcae", + "active": True, + "location": [{"reference": "Location/Location-6e138dc1"}], + "extension": [network("Organization/Organization-ea579d05-454e-4359-8751-900c940a599a")], + } + other_category = pharmacy("1000000003", category=[{"coding": [{"system": CATEGORY, "code": "prov"}]}]) + elsewhere = pharmacy( + "1000000004", category=[{"coding": [{"system": "http://example.com/categories", "code": "pharm"}]}] + ) + rows = pharmacy_views(page((directory, "match"), (other_category, "match"), (elsewhere, "match"))) + assert [(r.organization, r.locations, r.npi, r.address, r.part_d) for r in rows] == [ + (None, (), None, None, None) + ] * 3 + assert [n.id for n in rows[0].networks] == ["Organization-ea579d05-454e-4359-8751-900c940a599a"] + assert rows[0].preferred is None + + +def test_a_target_of_another_type_than_its_element_allows_is_left_out_and_the_page_kept() -> None: + crossed = pharmacy( + "1000000001", + providedBy={"reference": "Location/Location-1000000001"}, + location=[{"reference": "Organization/Organization-1000000001"}], + ) + first, second = pharmacy_views( + page( + *held(crossed, organization("1000000001"), store("1000000001")), + *held(pharmacy("1000000002"), organization("1000000002"), store("1000000002")), + ) + ) + assert (first.organization, first.locations, first.npi) == (None, (), None) + assert second.npi == "1000000002" + + +def test_a_reference_by_identifier_alone_names_no_entry_and_does_not_raise() -> None: + by_identifier = pharmacy("1000000001", providedBy={"identifier": {"system": NPI, "value": "1000000001"}}) + [found] = pharmacy_views(page((by_identifier, "match"), (store("1000000001"), "include"))) + assert found.organization is None + assert found.address is not None and found.address.get("city") == "Springfield" + + +def test_a_contained_organization_and_store_are_found_in_the_service_and_a_contained_one_it_lacks_left_out() -> None: + contained = pharmacy( + "1000000001", + contained=[organization("1000000001", id="org"), store("1000000001", id="store")], + providedBy={"reference": "#org"}, + location=[{"reference": "#store"}, {"reference": "#gone"}], + ) + [found] = pharmacy_views(page((contained, "match"))) + assert found.npi == "1000000001" + assert [location.get("id") for location in found.locations] == ["store"] + + +def test_each_location_comes_once_in_the_order_the_service_names_them() -> None: + service = pharmacy( + "1000000001", + location=[{"reference": "Location/b"}, {"reference": "Location/a"}, {"reference": f"{BASE}/Location/b"}], + ) + [found] = pharmacy_views( + page( + (service, "match"), + (organization("1000000001"), "include"), + (store("1", id="a"), "include"), + (store("2", id="b"), "include"), + ) + ) + assert [location.get("id") for location in found.locations] == ["b", "a"] + + +def test_two_entries_a_reference_could_name_raise_as_resolve_does() -> None: + twice = one(pharmacy("1000000001")) + twice["entry"].append( + { + "fullUrl": f"{BASE}/Organization/Organization-1000000001", + "resource": organization("1000000001"), + "search": {"mode": "include"}, + } + ) + with pytest.raises(Haau3Error, match="ambiguous"): + pharmacy_views(twice) + + +def test_a_value_of_another_shape_than_fhir_gives_reads_as_absent_and_never_fails_the_page() -> None: + odd = pharmacy( + "1000000001", + name=["Corner Pharmacy"], + telecom="305-555-0100", + specialty={"coding": []}, + category=None, + extension=[listing("not a part"), {"url": NETWORK, "valueReference": "Organization/x"}, "not an extension"], + location=["Location/Location-1000000001", None], + ) + bundle = page( + *held(odd, organization("1000000001", identifier="1000000001", address="1 Main St"), store("1000000001")) + ) + bundle["entry"].append(None) + bundle["entry"].append({"resource": "not a resource", "search": None}) + [found] = pharmacy_views(bundle) + assert (found.name, found.phone, found.specialties, found.part_d, found.networks, found.locations, found.npi) == ( + "Corner Pharmacy LLC 1000000001", + None, + (), + None, + (), + (), + None, + ) + assert found.address is None + no_entries: Any = {"resourceType": "Bundle", "entry": None} + assert pharmacy_views(no_entries) == [] + assert outcomes(no_entries) == [] + + +def test_a_row_cannot_be_hashed_compares_by_value_and_is_frozen() -> None: + bundle = one(pharmacy("1000000001", extension=[listed(True)])) + [first] = pharmacy_views(bundle) + [same] = pharmacy_views(bundle) + assert first == same + assert type(first).__hash__ is None + with pytest.raises(TypeError, match="unhashable type: 'PharmacyView'"): + hash(first) + with pytest.raises(dataclasses.FrozenInstanceError): + first.npi = "x" # type: ignore[misc] # pyright: ignore[reportAttributeAccessIssue] + + +def test_a_fastapi_route_returning_pharmacy_views_serializes_them() -> None: + """pydantic reads the rows' annotations at runtime, so FastAPI can serve them as a response model.""" + pytest.importorskip("fastapi") + from fastapi import FastAPI + + try: + from fastapi.testclient import TestClient + except RuntimeError: # An older Starlette's test client needs httpx, which the lowest dependencies lack. + pytest.skip("this FastAPI's test client needs httpx") + + rows = pharmacy_views(spec_pharmacies()) + app = FastAPI() + + @app.get("/pharmacies") + def pharmacies() -> list[PharmacyView]: + return rows + + served = TestClient(app).get("/pharmacies") + assert served.status_code == 200 + first = served.json()[0] + assert first["npi"] == rows[0].npi + assert rows[0].part_d is not None, "the spec's example carries each pharmacy's Part D listing" + assert first["part_d"]["as_of"] == rows[0].part_d.as_of + + +# --- which entries are rows ------------------------------------------------------------------------ + + +def test_rows_are_only_the_pages_healthcare_service_matches() -> None: + included = pharmacy("1000000009") + rows = pharmacy_views( + page( + *held(pharmacy("1000000001"), organization("1000000001"), store("1000000001")), + (included, "include"), + (organization("1000000005"), "match"), + ({"resourceType": "OperationOutcome", "issue": []}, "outcome"), + ) + ) + assert [r.service.get("id") for r in rows] == ["HealthcareService-1000000001"] + empty: Any = EMPTY_SEARCH + assert pharmacy_views(empty) == [] + + +@pytest.mark.anyio +async def test_the_clients_rows_are_what_the_plain_function_gives_and_ask_nothing(kind: str) -> None: + recorder = Recorder(AssertionError("a view sends nothing")) + client = Client(kind, recorder) + bundle = one(pharmacy("1000000001", extension=[listed(True)])) + assert client.inner.pharmacy_views(bundle) == pharmacy_views(bundle) + assert client.inner.outcomes(bundle) == outcomes(bundle) + assert recorder.requests == [] + + +# --- a search page's own OperationOutcomes --------------------------------------------------------- + +INFORMATION: Any = { + "resourceType": "OperationOutcome", + "issue": [ + {"severity": "information", "code": "informational", "details": {"text": "No preferred retail pharmacy."}} + ], +} +WARNING: Any = { + "resourceType": "OperationOutcome", + "issue": [{"severity": "warning", "code": "incomplete", "details": {"text": "Part D's files could not be read."}}], +} + + +def test_outcomes_are_each_entry_whose_search_mode_is_outcome_in_order() -> None: + bundle = page( + *held(pharmacy("1000000001"), organization("1000000001"), store("1000000001")), + (WARNING, "outcome"), + (INFORMATION, "outcome"), + ) + found = outcomes(bundle) + assert found == [WARNING, INFORMATION] + assert found[0] is WARNING + + +def test_outcomes_are_none_without_one_and_never_a_match_or_an_include() -> None: + assert outcomes(one(pharmacy("1000000001"))) == [] + assert outcomes(EMPTY_SEARCH) == [] + assert outcomes(page((WARNING, "match"), (INFORMATION, "include"))) == [] + # An entry marked outcome that holds another resource, or none, is not an OperationOutcome. + odd = page((organization("1000000001"), "outcome")) + odd["entry"].append({"search": {"mode": "outcome"}}) + assert outcomes(odd) == [] + + +def test_outcomes_are_what_matches_leaves_out() -> None: + client = sync_client(Recorder(AssertionError("nothing is sent"))) + bundle = page((INFORMATION, "outcome")) + assert client.matches(bundle) == [] + assert client.outcomes(bundle) == [INFORMATION] + + +# --- the search helper ----------------------------------------------------------------------------- + + +def _query(recorder: Recorder) -> dict[str, list[str]]: + found: dict[str, list[str]] = {} + for name, value in recorder.query(): + found.setdefault(name, []).append(value) + return found + + +@pytest.mark.anyio +async def test_the_helper_sends_the_callers_parameters_and_both_includes_and_nothing_else(kind: str) -> None: + recorder = Recorder(answer(200, EMPTY_SEARCH)) + got = await Client(kind, recorder)( + "search_healthcare_service_with_includes", + service_category="pharm", + network="Organization-part-d-H2406-013-000-retail", + location_address_postalcode="33131", + count=5, + ) + assert got == EMPTY_SEARCH + assert recorder.last.url.path == "/v1/fhir/r4/HealthcareService" + assert _query(recorder) == { + "service-category": ["pharm"], + "network": ["Organization-part-d-H2406-013-000-retail"], + "location.address-postalcode": ["33131"], + "_include": INCLUDES, + "_count": ["5"], + } + + +@pytest.mark.anyio +async def test_the_helpers_request_is_the_search_with_both_includes(kind: str) -> None: + helped, plain = Recorder(answer(200, EMPTY_SEARCH)), Recorder(answer(200, EMPTY_SEARCH)) + await Client(kind, helped)("search_healthcare_service_with_includes", service_category="pharm", active="true") + await Client(kind, plain)("search_healthcare_service", service_category="pharm", include=INCLUDES, active="true") + assert str(helped.last.url) == str(plain.last.url) + + +@pytest.mark.anyio +async def test_the_helper_passes_a_calls_options_on_and_answers_through_with_response(kind: str) -> None: + recorder = Recorder(answer(200, EMPTY_SEARCH), answer(200, EMPTY_SEARCH)) + client = Client(kind, recorder) + await client( + "search_healthcare_service_with_includes", service_category="pharm", extra_headers={"x-extra": "pharmacy"} + ) + assert recorder.last.headers["x-extra"] == "pharmacy" + response = await client.with_response("search_healthcare_service_with_includes", service_category="pharm") + assert (response.data, response.status, response.request_id) == (EMPTY_SEARCH, 200, REQUEST_ID) + assert _query(recorder)["_include"] == INCLUDES + + +@pytest.mark.anyio +async def test_python_refuses_summary_which_the_api_does_not_combine_with_an_include(kind: str) -> None: + recorder = Recorder(answer(200, EMPTY_SEARCH)) + client = Client(kind, recorder) + error = await client.raises("search_healthcare_service_with_includes", service_category="pharm", summary="count") + assert isinstance(error, TypeError) + assert "unexpected keyword argument 'summary'" in str(error) + assert recorder.requests == [] + + +def test_outcomes_is_named_as_the_package_exports_it() -> None: + assert haau3.outcomes.__name__ == "outcomes" + assert haau3.pharmacy_views.__name__ == "pharmacy_views" + + +@pytest.mark.anyio +@pytest.mark.parametrize("value", [["HealthcareService:organization"], "HealthcareService:location", [], None]) +async def test_python_refuses_an_include_passed_to_the_helper_and_nothing_is_sent(kind: str, value: object) -> None: + recorder = Recorder(answer(200, EMPTY_SEARCH)) + client = Client(kind, recorder) + error = await client.raises("search_healthcare_service_with_includes", service_category="pharm", include=value) + assert isinstance(error, TypeError) + assert "unexpected keyword argument 'include'" in str(error) + with pytest.raises(TypeError, match="unexpected keyword argument 'include'"): + await client.with_response("search_healthcare_service_with_includes", include=value) + assert recorder.requests == [] + + +def test_the_helper_sends_both_includes_the_search_serves_as_the_spec_lists_them() -> None: + op = spec_operation("GET", "/v1/fhir/r4/HealthcareService") + served = sorted( + { + value + for p in op["parameters"] + if p.get("name") in ("_include", "_include:iterate") + for value in (p["schema"].get("items", {}).get("enum") or p["schema"].get("enum") or []) + } + ) + include, iterate = generate.WITH_INCLUDES["searchHealthcareService"] + assert (sorted(include), iterate) == (served, ()) + assert len(served) == 2 + + +def test_the_helper_takes_the_searchs_keywords_but_include_and_summary_on_every_client() -> None: + # The API does not combine _summary with an include, so the helper, which always sends one, takes none. + expected = set(inspect.signature(haau3.Haau3.search_healthcare_service).parameters) - {"include", "summary"} + assert "summary" in inspect.signature(haau3.Haau3.search_healthcare_service).parameters + for cls in (haau3.Haau3, haau3.AsyncHaau3, haau3.SyncWithResponse, haau3.AsyncWithResponse): + assert set(inspect.signature(cls.search_healthcare_service_with_includes).parameters) == expected, cls + + +def test_the_helper_is_awaited_from_async_code_and_the_readers_are_not() -> None: + assert inspect.iscoroutinefunction(haau3.AsyncHaau3.search_healthcare_service_with_includes) + assert not inspect.iscoroutinefunction(haau3.Haau3.search_healthcare_service_with_includes) + for name in ("pharmacy_views", "outcomes"): + assert not inspect.iscoroutinefunction(getattr(haau3.AsyncHaau3, name)) diff --git a/tests/typecheck/consumer.py b/tests/typecheck/consumer.py index d051cd4..9b3708e 100644 --- a/tests/typecheck/consumer.py +++ b/tests/typecheck/consumer.py @@ -75,6 +75,38 @@ def sync_tour(client: Haau3, records: types.ReconcileMedicationsBody) -> None: assert_type(client.with_response.search_slot_with_includes(), Response[fhir.Bundle]) accepts: haau3.PatientType = "existptonly" + # The pharmacy view: each pharmacy as a row, typed, with no cast, and a page's own OperationOutcomes. + pharmacies = client.search_healthcare_service_with_includes( + service_category="pharm", location_address_postalcode="33131" + ) + assert_type(pharmacies, fhir.Bundle) + for pharmacy in client.pharmacy_views(pharmacies): + assert_type(pharmacy, haau3.PharmacyView) + assert_type(pharmacy.npi, "str | None") + assert_type(pharmacy.address, "fhir.Address | None") + assert_type(pharmacy.specialties, "tuple[fhir.Coding, ...]") + assert_type(pharmacy.part_d, "haau3.PartDListing | None") + assert_type(pharmacy.networks, "tuple[haau3.PharmacyNetwork, ...]") + assert_type(pharmacy.preferred, "bool | None") + assert_type(pharmacy.service, fhir.HealthcareService) + assert_type(pharmacy.organization, "fhir.Organization | None") + assert_type(pharmacy.locations, "tuple[fhir.Location, ...]") + if pharmacy.networks: + assert_type(pharmacy.networks[0].kind, "haau3.PartDNetworkKind | None") + assert_type(haau3.pharmacy_views(pharmacies), "list[haau3.PharmacyView]") + assert_type(client.outcomes(pharmacies), "list[fhir.OperationOutcome]") + assert_type(haau3.outcomes(pharmacies), "list[fhir.OperationOutcome]") + pharmacy_query: types.SearchHealthcareServiceWithIncludesQuery = { + "service_category": "pharm", + "location_address_state": "FL", + } + client.search_healthcare_service_with_includes(**pharmacy_query) + # ...and the same query suits the plain search. + client.search_healthcare_service(**pharmacy_query) + assert_type(client.with_response.search_healthcare_service_with_includes(), Response[fhir.Bundle]) + kind: haau3.PartDNetworkKind = "preferred-retail" + _ = kind + # resolve() and matches(), typed by a resource type's name. assert_type(client.matches(included, "Slot"), "list[fhir.Slot]") assert_type(haau3.matches(included, "Device"), "list[fhir.OtherResource]") @@ -223,6 +255,9 @@ def sync_tour(client: Haau3, records: types.ReconcileMedicationsBody) -> None: # A Slot search's query may hold an include, so the helper refuses one; its own query type is the one to build. client.search_slot_with_includes(**slot_search) # type: ignore[misc] # pyright: ignore[reportCallIssue] not_a_code: haau3.PatientType = "everyone" # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + client.search_healthcare_service_with_includes(include=["HealthcareService:organization"]) # type: ignore[call-arg] # pyright: ignore[reportCallIssue] + not_a_kind: haau3.PartDNetworkKind = "specialty" # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + _ = not_a_kind client.matches(found, "NotAResource") # type: ignore[call-overload] # pyright: ignore[reportCallIssue, reportArgumentType] _ = not_a_code # A view holds dicts, so it cannot be hashed. pyright alone checks hashability; mypy does not.