pdc-api 0.4.1__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {pdc_api-0.4.1 → pdc_api-0.5.0}/CHANGELOG.md +14 -0
  2. {pdc_api-0.4.1 → pdc_api-0.5.0}/PKG-INFO +28 -4
  3. {pdc_api-0.4.1 → pdc_api-0.5.0}/README.md +27 -3
  4. {pdc_api-0.4.1 → pdc_api-0.5.0}/integration_tests/conftest.py +13 -0
  5. {pdc_api-0.4.1 → pdc_api-0.5.0}/integration_tests/test_application_form_input_type_contract.py +4 -1
  6. {pdc_api-0.4.1 → pdc_api-0.5.0}/integration_tests/test_operations.py +32 -0
  7. {pdc_api-0.4.1 → pdc_api-0.5.0}/just/pdc.just +2 -1
  8. {pdc_api-0.4.1 → pdc_api-0.5.0}/justfile +25 -38
  9. {pdc_api-0.4.1 → pdc_api-0.5.0}/pyproject.toml +1 -1
  10. {pdc_api-0.4.1 → pdc_api-0.5.0}/pyproject.toml.orig +1 -1
  11. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/__init__.py +2 -0
  12. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/_generated.py +94 -2
  13. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/client.py +56 -0
  14. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/errors.py +4 -0
  15. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/models.py +8 -0
  16. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/openapi.json +414 -13
  17. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/permission_grants.py +12 -21
  18. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/seeding/keycloak_admin.py +3 -0
  19. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/testing.py +30 -2
  20. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/token.py +3 -0
  21. {pdc_api-0.4.1 → pdc_api-0.5.0}/tests/test_client.py +15 -0
  22. {pdc_api-0.4.1 → pdc_api-0.5.0}/tests/test_client_operations.py +96 -2
  23. pdc_api-0.5.0/tests/test_permission_grants.py +234 -0
  24. {pdc_api-0.4.1 → pdc_api-0.5.0}/tests/test_token.py +19 -0
  25. pdc_api-0.4.1/tests/test_permission_grants.py +0 -178
  26. {pdc_api-0.4.1 → pdc_api-0.5.0}/LICENSE +0 -0
  27. {pdc_api-0.4.1 → pdc_api-0.5.0}/codegen/postprocess.py +0 -0
  28. {pdc_api-0.4.1 → pdc_api-0.5.0}/codegen/preprocess.py +0 -0
  29. {pdc_api-0.4.1 → pdc_api-0.5.0}/integration_tests/test_default_permission_grants.py +0 -0
  30. {pdc_api-0.4.1 → pdc_api-0.5.0}/integration_tests/test_ensure_for_keycloak_org.py +0 -0
  31. {pdc_api-0.4.1 → pdc_api-0.5.0}/integration_tests/test_group_membership.py +0 -0
  32. {pdc_api-0.4.1 → pdc_api-0.5.0}/integration_tests/test_keycloak_admin.py +0 -0
  33. {pdc_api-0.4.1 → pdc_api-0.5.0}/integration_tests/test_permission_grants.py +0 -0
  34. {pdc_api-0.4.1 → pdc_api-0.5.0}/integration_tests/test_preprocess_rules.py +0 -0
  35. {pdc_api-0.4.1 → pdc_api-0.5.0}/integration_tests/test_seed.py +0 -0
  36. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/_base.py +0 -0
  37. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/py.typed +0 -0
  38. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/seeding/__init__.py +0 -0
  39. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/seeding/pdc_entities.py +0 -0
  40. {pdc_api-0.4.1 → pdc_api-0.5.0}/src/pdc_api/transport.py +0 -0
  41. {pdc_api-0.4.1 → pdc_api-0.5.0}/tests/conftest.py +0 -0
  42. {pdc_api-0.4.1 → pdc_api-0.5.0}/tests/test_client_files.py +0 -0
  43. {pdc_api-0.4.1 → pdc_api-0.5.0}/tests/test_keycloak_admin.py +0 -0
  44. {pdc_api-0.4.1 → pdc_api-0.5.0}/tests/test_models.py +0 -0
  45. {pdc_api-0.4.1 → pdc_api-0.5.0}/tests/test_transport.py +0 -0
@@ -4,6 +4,20 @@ This project follows [Semantic Versioning](https://semver.org). Until 1.0, a min
4
4
 
5
5
  PDC does not bump its spec version for every API change, so each entry names the spec version and the date the spec was downloaded.
6
6
 
7
+ ## 0.5.0 (2026-11-24)
8
+
9
+ Spec: PDC 0.43.0, downloaded 2026-11-24.
10
+
11
+ Breaking: `Organization.keycloak_organization_id` is now required, as PDC always returns it. Code that builds an `Organization` without it, such as test fixtures, must add it.
12
+
13
+ - `Organization` has `keycloak_organization_id`, `keycloak_organization_name`, `disabled_at`, `members`, and `former_members`. `members` and `former_members` are `None` when the caller may not see membership, or when PDC has not yet synced the organization from Keycloak.
14
+ - `get_organizations` walks `GET /organizations`.
15
+ - `pdc_api.testing` adds `user_payload`, and `organization_payload` takes the new fields.
16
+ - `sync_users_from_keycloak` and `sync_organizations_from_keycloak` start PDC's Keycloak sync and wait for it, raising `KeycloakSyncError` if it fails or times out. The token must carry the `kc-admin-api` scope.
17
+ - `KeycloakClientCredentialsProvider` takes an optional `scope`.
18
+ - Seeding's `KeycloakAdmin.set_user_enabled` enables or disables a Keycloak user.
19
+ - Permission grants accept the `allFunders` grantee type, which grants to every funder.
20
+
7
21
  ## 0.4.1 (2026-11-20)
8
22
 
9
23
  - `pdc-api` is published on [PyPI](https://pypi.org/project/pdc-api/). Install it with `pip install pdc-api`.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pdc-api
3
- Version: 0.4.1
3
+ Version: 0.5.0
4
4
  Summary: Python client for the Philanthropy Data Commons (PDC) API
5
5
  Keywords: philanthropy,philanthropy data commons,pdc,grantmaking,api client
6
6
  Author: Philanthropy Data Commons
@@ -100,7 +100,7 @@ class TokenProvider(Protocol):
100
100
  def refresh_if_necessary(self) -> None: ...
101
101
  ```
102
102
 
103
- The package ships one: `KeycloakClientCredentialsProvider` runs the OAuth2 client-credentials grant against PDC's Keycloak and caches the token until 30 seconds before it expires. Use it for a service account.
103
+ The package ships one: `KeycloakClientCredentialsProvider` runs the OAuth2 client-credentials grant against PDC's Keycloak and caches the token until 30 seconds before it expires. Use it for a service account. Pass `scope` to request an optional client scope, such as `kc-admin-api`.
104
104
 
105
105
  To call PDC as a signed-in user, write your own provider that returns the user's access token and refreshes it as your app requires. The protocol is structural, so your class doesn't need to import or subclass anything from this package.
106
106
 
@@ -157,9 +157,33 @@ A changemaker can also write its own profile values. `create_changemaker_source`
157
157
 
158
158
  Uploading a file takes two steps. `create_file` creates the file record and returns a presigned S3 POST, and `upload_file_to_s3_presigned_url` sends the bytes to it.
159
159
 
160
+ ## Syncing from Keycloak
161
+
162
+ PDC caches Keycloak's users, organizations, and memberships, and an `Organization`'s `members` and `former_members` come from that cache. `sync_users_from_keycloak` and `sync_organizations_from_keycloak` start PDC's sync, wait for it to finish, and return the completed task, or raise `KeycloakSyncError` if it fails or outlasts `timeout_seconds`. The token must carry the `kc-admin-api` scope:
163
+
164
+ ```python
165
+ from pdc_api.client import sync_organizations_from_keycloak, sync_users_from_keycloak
166
+
167
+ admin_session = APISession(
168
+ base_url="https://api.philanthropydatacommons.org/",
169
+ token_provider=KeycloakClientCredentialsProvider(
170
+ server_url="https://auth.philanthropydatacommons.org",
171
+ realm="pdc",
172
+ client_id="your-client-id",
173
+ client_secret="your-client-secret",
174
+ timeout=15,
175
+ scope="kc-admin-api",
176
+ ),
177
+ )
178
+ sync_users_from_keycloak(admin_session)
179
+ sync_organizations_from_keycloak(admin_session)
180
+ ```
181
+
182
+ `members` and `former_members` are `None` when the caller may not see membership, or when PDC has not yet synced the organization.
183
+
160
184
  ## Permission grants
161
185
 
162
- PDC controls access with permission grants. Each grant gives a grantee (a user, a Keycloak organization, or every authenticated user) a set of verbs (such as `view` or `edit`) over a set of scopes, in the context of one entity such as a changemaker or a proposal. `pdc_api.permission_grants` models each context as its own class, so a grant parses into, say, `ChangemakerPermissionGrant` with a typed `changemaker_id`:
186
+ PDC controls access with permission grants. Each grant gives a grantee (a user, a Keycloak organization, every authenticated user, or every funder) a set of verbs (such as `view` or `edit`) over a set of scopes, in the context of one entity such as a changemaker or a proposal. `pdc_api.permission_grants` models each context as its own class, so a grant parses into, say, `ChangemakerPermissionGrant` with a typed `changemaker_id`:
163
187
 
164
188
  ```python
165
189
  from pdc_api.models import PermissionGrantEntityType, PermissionGrantGranteeType, PermissionGrantVerb
@@ -265,7 +289,7 @@ def test_lists_changemakers():
265
289
  `pdc_api.seeding` (extra: `seeding`) creates realistic data on a PDC stack through the public PDC API and the Keycloak admin API. It is for local development and integration tests, not production:
266
290
 
267
291
  - **`pdc_api.seeding.pdc_entities`:** `seed_*` functions for funders, collaboratives, changemakers, fiscal sponsorships, data providers, opportunities, application forms, proposals, initiatives, and field values. `seed_proposal_bundle` creates a full proposal and everything it depends on in one call.
268
- - **`pdc_api.seeding.keycloak_admin`:** `KeycloakAdmin`, whose `ensure_*` methods create Keycloak organizations, users, memberships, and realm roles only if they don't already exist, so re-running a seed script is safe.
292
+ - **`pdc_api.seeding.keycloak_admin`:** `KeycloakAdmin`, whose `ensure_*` methods create Keycloak organizations, users, memberships, and realm roles only if they don't already exist, so re-running a seed script is safe. `set_user_enabled` enables or disables a user.
269
293
 
270
294
  ## Contributing
271
295
 
@@ -67,7 +67,7 @@ class TokenProvider(Protocol):
67
67
  def refresh_if_necessary(self) -> None: ...
68
68
  ```
69
69
 
70
- The package ships one: `KeycloakClientCredentialsProvider` runs the OAuth2 client-credentials grant against PDC's Keycloak and caches the token until 30 seconds before it expires. Use it for a service account.
70
+ The package ships one: `KeycloakClientCredentialsProvider` runs the OAuth2 client-credentials grant against PDC's Keycloak and caches the token until 30 seconds before it expires. Use it for a service account. Pass `scope` to request an optional client scope, such as `kc-admin-api`.
71
71
 
72
72
  To call PDC as a signed-in user, write your own provider that returns the user's access token and refreshes it as your app requires. The protocol is structural, so your class doesn't need to import or subclass anything from this package.
73
73
 
@@ -124,9 +124,33 @@ A changemaker can also write its own profile values. `create_changemaker_source`
124
124
 
125
125
  Uploading a file takes two steps. `create_file` creates the file record and returns a presigned S3 POST, and `upload_file_to_s3_presigned_url` sends the bytes to it.
126
126
 
127
+ ## Syncing from Keycloak
128
+
129
+ PDC caches Keycloak's users, organizations, and memberships, and an `Organization`'s `members` and `former_members` come from that cache. `sync_users_from_keycloak` and `sync_organizations_from_keycloak` start PDC's sync, wait for it to finish, and return the completed task, or raise `KeycloakSyncError` if it fails or outlasts `timeout_seconds`. The token must carry the `kc-admin-api` scope:
130
+
131
+ ```python
132
+ from pdc_api.client import sync_organizations_from_keycloak, sync_users_from_keycloak
133
+
134
+ admin_session = APISession(
135
+ base_url="https://api.philanthropydatacommons.org/",
136
+ token_provider=KeycloakClientCredentialsProvider(
137
+ server_url="https://auth.philanthropydatacommons.org",
138
+ realm="pdc",
139
+ client_id="your-client-id",
140
+ client_secret="your-client-secret",
141
+ timeout=15,
142
+ scope="kc-admin-api",
143
+ ),
144
+ )
145
+ sync_users_from_keycloak(admin_session)
146
+ sync_organizations_from_keycloak(admin_session)
147
+ ```
148
+
149
+ `members` and `former_members` are `None` when the caller may not see membership, or when PDC has not yet synced the organization.
150
+
127
151
  ## Permission grants
128
152
 
129
- PDC controls access with permission grants. Each grant gives a grantee (a user, a Keycloak organization, or every authenticated user) a set of verbs (such as `view` or `edit`) over a set of scopes, in the context of one entity such as a changemaker or a proposal. `pdc_api.permission_grants` models each context as its own class, so a grant parses into, say, `ChangemakerPermissionGrant` with a typed `changemaker_id`:
153
+ PDC controls access with permission grants. Each grant gives a grantee (a user, a Keycloak organization, every authenticated user, or every funder) a set of verbs (such as `view` or `edit`) over a set of scopes, in the context of one entity such as a changemaker or a proposal. `pdc_api.permission_grants` models each context as its own class, so a grant parses into, say, `ChangemakerPermissionGrant` with a typed `changemaker_id`:
130
154
 
131
155
  ```python
132
156
  from pdc_api.models import PermissionGrantEntityType, PermissionGrantGranteeType, PermissionGrantVerb
@@ -232,7 +256,7 @@ def test_lists_changemakers():
232
256
  `pdc_api.seeding` (extra: `seeding`) creates realistic data on a PDC stack through the public PDC API and the Keycloak admin API. It is for local development and integration tests, not production:
233
257
 
234
258
  - **`pdc_api.seeding.pdc_entities`:** `seed_*` functions for funders, collaboratives, changemakers, fiscal sponsorships, data providers, opportunities, application forms, proposals, initiatives, and field values. `seed_proposal_bundle` creates a full proposal and everything it depends on in one call.
235
- - **`pdc_api.seeding.keycloak_admin`:** `KeycloakAdmin`, whose `ensure_*` methods create Keycloak organizations, users, memberships, and realm roles only if they don't already exist, so re-running a seed script is safe.
259
+ - **`pdc_api.seeding.keycloak_admin`:** `KeycloakAdmin`, whose `ensure_*` methods create Keycloak organizations, users, memberships, and realm roles only if they don't already exist, so re-running a seed script is safe. `set_user_enabled` enables or disables a user.
236
260
 
237
261
  ## Contributing
238
262
 
@@ -144,3 +144,16 @@ def add_user_to_org(keycloak_admin, keycloak_client_id, test_user_password):
144
144
  keycloak_admin.ensure_user_in_organization(organization_id=org.id, user_id=user.id)
145
145
 
146
146
  return add
147
+
148
+
149
+ @pytest.fixture(scope="session")
150
+ def admin_api_session() -> APISession:
151
+ token_provider = KeycloakClientCredentialsProvider(
152
+ server_url=KEYCLOAK_SERVER_URL,
153
+ realm=KEYCLOAK_REALM,
154
+ client_id=KEYCLOAK_CLIENT_ID,
155
+ client_secret=KEYCLOAK_CLIENT_SECRET,
156
+ timeout=PDC_API_TIMEOUT,
157
+ scope="kc-admin-api",
158
+ )
159
+ return APISession(base_url=PDC_API_URL, token_provider=token_provider, timeout=PDC_API_TIMEOUT)
@@ -4,7 +4,7 @@ import pytest
4
4
 
5
5
  from pdc_api.client import get_application_form
6
6
  from pdc_api.errors import PDCBadRequestError
7
- from pdc_api.models import ChangemakerApplicationForm
7
+ from pdc_api.models import ChangemakerApplicationForm, InputType
8
8
  from pdc_api.seeding.pdc_entities import seed_application_form, seed_base_field, seed_opportunity
9
9
 
10
10
  SPEC_ENUM_VALUES = ["shortText", "longText", "radio", "dropdown", "multiselect", "hidden"]
@@ -38,6 +38,9 @@ def post_form_field(api_session):
38
38
 
39
39
 
40
40
  class TestApplicationFormInputTypeContract:
41
+ def test_spec_enum_values_match_the_generated_input_type(self):
42
+ assert set(SPEC_ENUM_VALUES) == set(InputType)
43
+
41
44
  @pytest.mark.parametrize("value", SPEC_ENUM_VALUES)
42
45
  def test_spec_enum_value_round_trips(self, post_form_field, value):
43
46
  assert post_form_field(value) == value
@@ -28,9 +28,12 @@ from pdc_api.client import (
28
28
  get_initiative_field_values,
29
29
  get_initiatives,
30
30
  get_organization_by_keycloak_id,
31
+ get_organizations,
31
32
  get_proposal,
32
33
  get_proposals,
33
34
  link_changemaker_to_proposal,
35
+ sync_organizations_from_keycloak,
36
+ sync_users_from_keycloak,
34
37
  )
35
38
  from pdc_api.errors import PDCNotFoundError, ProposalNotFoundError
36
39
  from pdc_api.models import (
@@ -531,6 +534,35 @@ class TestOrganizations:
531
534
  with pytest.raises(PDCNotFoundError):
532
535
  get_organization_by_keycloak_id(api_session, keycloak_id=str(uuid.uuid4()))
533
536
 
537
+ def test_sync_from_keycloak_reports_organization_members(
538
+ self,
539
+ api_session,
540
+ admin_api_session,
541
+ keycloak_admin,
542
+ fresh_keycloak_org,
543
+ add_user_to_org,
544
+ suffix,
545
+ test_user_password,
546
+ ):
547
+ username = f"sync-member-{suffix}@example.com"
548
+ add_user_to_org(username, fresh_keycloak_org)
549
+ member = keycloak_admin.ensure_user(username=username, email=username, password=test_user_password)
550
+
551
+ sync_users_from_keycloak(admin_api_session)
552
+ sync_organizations_from_keycloak(admin_api_session)
553
+
554
+ organization = get_organization_by_keycloak_id(api_session, keycloak_id=fresh_keycloak_org.id)
555
+ assert organization.members is not None
556
+ assert [(str(m.keycloak_user_id), m.disabled_at) for m in organization.members] == [(member.id, None)]
557
+ assert fresh_keycloak_org.id in {str(o.keycloak_organization_id) for o in get_organizations(api_session)}
558
+
559
+ keycloak_admin.set_user_enabled(user_id=member.id, enabled=False)
560
+ sync_users_from_keycloak(admin_api_session)
561
+
562
+ organization = get_organization_by_keycloak_id(api_session, keycloak_id=fresh_keycloak_org.id)
563
+ assert organization.members is not None
564
+ assert [m.disabled_at is not None for m in organization.members] == [True]
565
+
534
566
 
535
567
  class TestApplicationForm:
536
568
  def test_get_application_form_returns_seeded_form(self, api_session):
@@ -9,11 +9,12 @@ compose := 'docker compose -f ' + cache + '/compose-ci.yml'
9
9
  _default:
10
10
  @just --list pdc --unsorted
11
11
 
12
- # Fetch PDC's compose file and Keycloak realm
12
+ # Fetch PDC's compose file and Keycloak realm, adding the admin API access the realm lacks
13
13
  fetch:
14
14
  mkdir -p {{cache}}/keycloak
15
15
  curl -fsSL {{base}}/compose-ci.yml -o {{cache}}/compose-ci.yml
16
16
  curl -fsSL {{base}}/keycloak/realm.json -o {{cache}}/keycloak/realm.json
17
+ uv run --no-project python -I just/patch_realm.py {{cache}}/keycloak/realm.json
17
18
 
18
19
  # Start the stack and wait until it is healthy
19
20
  up: fetch
@@ -3,7 +3,14 @@ set minimum-version := '1.55.0'
3
3
 
4
4
  mod pdc 'just/pdc.just'
5
5
 
6
- python := shell("cat .python-version")
6
+ set positional-arguments
7
+
8
+ python := env("PYTHON", shell("cat .python-version"))
9
+ lowest_direct := env("LOWEST_DIRECT", "false")
10
+ upgrade := env("UPGRADE", "false")
11
+ isolated_run := "uv run --python=" + python + (if lowest_direct == "true" { " --resolution=lowest-direct" } else { "" }) + " --isolated --no-dev"
12
+ pytest := isolated_run + (if upgrade == "true" { " --upgrade" } else { "" }) + " --no-editable --group tests --reinstall -- python -I -m pytest"
13
+ typecheck_run := isolated_run + " --group tests --group typecheck --"
7
14
 
8
15
  _default:
9
16
  @just --list --unsorted
@@ -23,69 +30,49 @@ format:
23
30
  # Audit GitHub Actions workflows with zizmor (passes through args)
24
31
  [group('dev')]
25
32
  zizmor *args:
26
- uvx --exclude-newer "7 days" zizmor .github/ {{args}}
33
+ uvx --exclude-newer "7 days" zizmor .github/ "$@"
27
34
 
28
35
  # Run all three type checkers, failing at the end if any failed
29
36
  [group('dev')]
30
- [arg("python", long)]
31
- [arg("lowest_direct", long="lowest-direct", value="true")]
32
- typecheck python=python lowest_direct="false":
37
+ typecheck:
33
38
  #!/usr/bin/env bash
34
39
  status=0
35
40
  for checker in mypy pyrefly ty; do
36
- {{just_executable()}} typecheck-$checker --python={{python}} \
37
- {{ if lowest_direct == "true" { "--lowest-direct" } else { "" } }} || status=1
41
+ {{just_executable()}} typecheck-$checker || status=1
38
42
  done
39
43
  exit $status
40
44
 
41
45
  # Type check the package and tests with mypy, then the package in strict mode
42
46
  [group('dev')]
43
- [arg("python", long)]
44
- [arg("lowest_direct", long="lowest-direct", value="true")]
45
- typecheck-mypy python=python lowest_direct="false":
47
+ typecheck-mypy:
46
48
  #!/usr/bin/env bash
47
49
  status=0
48
- {{just_executable()}} _typecheck {{python}} {{lowest_direct}} mypy || status=1
49
- {{just_executable()}} _typecheck {{python}} {{lowest_direct}} mypy --strict src || status=1
50
+ {{typecheck_run}} mypy --python-version={{python}} || status=1
51
+ {{typecheck_run}} mypy --python-version={{python}} --strict src || status=1
50
52
  exit $status
51
53
 
52
54
  # Type check the package and tests with pyrefly
53
55
  [group('dev')]
54
- [arg("python", long)]
55
- [arg("lowest_direct", long="lowest-direct", value="true")]
56
- typecheck-pyrefly python=python lowest_direct="false" *args: (_typecheck python lowest_direct "pyrefly check" args)
56
+ typecheck-pyrefly *args:
57
+ {{typecheck_run}} pyrefly check --python-version={{python}} "$@"
57
58
 
58
59
  # Type check the package and tests with ty
59
60
  [group('dev')]
60
- [arg("python", long)]
61
- [arg("lowest_direct", long="lowest-direct", value="true")]
62
- typecheck-ty python=python lowest_direct="false" *args: (_typecheck python lowest_direct "ty check" args)
61
+ typecheck-ty *args:
62
+ {{typecheck_run}} ty check --python-version={{python}} "$@"
63
63
 
64
64
  # Run the unit tests against the installed package
65
65
  [group('test')]
66
- [arg("python", long)]
67
- [arg("lowest_direct", long="lowest-direct", value="true")]
68
- [arg("upgrade", long, value="true")]
69
- test python=python lowest_direct="false" upgrade="false" *args: (_pytest python lowest_direct upgrade args)
66
+ test *args: _preview-upgrade
67
+ {{pytest}} "$@"
70
68
 
71
69
  # Run the integration tests against the installed package and a live PDC stack (run `just pdc up` first)
72
70
  [group('test')]
73
- [arg("python", long)]
74
- [arg("lowest_direct", long="lowest-direct", value="true")]
75
- [arg("upgrade", long, value="true")]
76
- integration python=python lowest_direct="false" upgrade="false" *args: (_pytest python lowest_direct upgrade "integration_tests/ " + args)
77
-
78
- _typecheck python lowest_direct tool *args:
79
- uv run --python={{python}} {{ if lowest_direct == "true" { "--resolution=lowest-direct" } else { "" } }} --isolated --no-dev --group tests --group typecheck -- \
80
- {{tool}} --python-version={{python}} {{args}}
81
-
82
- _pytest python lowest_direct upgrade *args:
83
- @if [ "{{upgrade}}" = "true" ]; then uv lock --upgrade --dry-run; fi
84
- uv run --python={{python}} \
85
- {{ if lowest_direct == "true" { "--resolution=lowest-direct" } else { "" } }} \
86
- {{ if upgrade == "true" { "--upgrade" } else { "" } }} \
87
- --isolated --no-editable --no-dev --group tests --reinstall -- \
88
- python -I -m pytest {{args}}
71
+ integration *args: _preview-upgrade
72
+ {{pytest}} integration_tests/ "$@"
73
+
74
+ _preview-upgrade:
75
+ @if [ "{{upgrade}}" = true ]; then uv lock --upgrade --dry-run; fi
89
76
 
90
77
  # Run lint, type checks, unit tests, and integration tests (run `just pdc up` first)
91
78
  [group('test')]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pdc-api"
3
- version = "0.4.1"
3
+ version = "0.5.0"
4
4
  description = "Python client for the Philanthropy Data Commons (PDC) API"
5
5
  readme = "README.md"
6
6
  license = "AGPL-3.0-only"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pdc-api"
3
- version = "0.4.1"
3
+ version = "0.5.0"
4
4
  description = "Python client for the Philanthropy Data Commons (PDC) API"
5
5
  readme = "README.md"
6
6
  license = "AGPL-3.0-only"
@@ -3,6 +3,7 @@ from pdc_api.errors import (
3
3
  ChangemakerFieldValueBatchNotFoundError,
4
4
  ChangemakerNotFoundError,
5
5
  FunderNotFoundError,
6
+ KeycloakSyncError,
6
7
  PDCBadRequestError,
7
8
  PDCConflictError,
8
9
  PDCException,
@@ -23,6 +24,7 @@ __all__ = [
23
24
  "ChangemakerFieldValueBatchNotFoundError",
24
25
  "ChangemakerNotFoundError",
25
26
  "FunderNotFoundError",
27
+ "KeycloakSyncError",
26
28
  "PDCBadRequestError",
27
29
  "PDCConflictError",
28
30
  "PDCException",
@@ -132,6 +132,45 @@ class InitiativePatch(BaseSchema):
132
132
  title: Annotated[str | None, Field(examples=["Clean Water for the Upper Valley"], min_length=1)] = None
133
133
 
134
134
 
135
+ class Memberships(BaseSchema):
136
+ added: Annotated[int, Field(description="The number of memberships created in the local cache by the sync run.")]
137
+ disabled: Annotated[
138
+ int,
139
+ Field(
140
+ description="The number of local membership rows marked disabled by the sync run because Keycloak no longer reports them."
141
+ ),
142
+ ]
143
+ seen: Annotated[int, Field(description="The number of memberships found in Keycloak during the sync run.")]
144
+ updated: Annotated[
145
+ int, Field(description="The number of existing memberships confirmed against Keycloak by the sync run.")
146
+ ]
147
+
148
+
149
+ class Organizations(BaseSchema):
150
+ added: Annotated[int, Field(description="The number of organizations created in the local cache by the sync run.")]
151
+ disabled: Annotated[
152
+ int,
153
+ Field(
154
+ description="The number of local organization rows marked disabled by the sync run because Keycloak reports them as absent or not enabled."
155
+ ),
156
+ ]
157
+ seen: Annotated[int, Field(description="The number of organizations found in Keycloak during the sync run.")]
158
+ updated: Annotated[
159
+ int, Field(description="The number of existing organizations confirmed against Keycloak by the sync run.")
160
+ ]
161
+
162
+
163
+ class Details(BaseSchema):
164
+ error: Annotated[
165
+ str | None,
166
+ Field(
167
+ description="The message of the error that caused the sync run to fail; present only when the task status is `failed`."
168
+ ),
169
+ ] = None
170
+ memberships: Memberships | None = None
171
+ organizations: Organizations | None = None
172
+
173
+
135
174
  class PdcError(BaseSchema):
136
175
  details: list[Any] | None = []
137
176
  message: str | None = None
@@ -167,6 +206,7 @@ class PermissionGrantGranteeType(StrEnum):
167
206
  USER = "user"
168
207
  USER_GROUP = "userGroup"
169
208
  AUTHENTICATED_USERS = "authenticatedUsers"
209
+ ALL_FUNDERS = "allFunders"
170
210
 
171
211
 
172
212
  class PermissionGrantVerb(StrEnum):
@@ -265,7 +305,7 @@ class Users(BaseSchema):
265
305
  ]
266
306
 
267
307
 
268
- class Details(BaseSchema):
308
+ class Details1(BaseSchema):
269
309
  users: Users
270
310
 
271
311
 
@@ -488,6 +528,22 @@ class InitiativeFieldValuePatch(BaseSchema):
488
528
  value: Annotated[str | None, Field(examples=["A program that brings clean water to the upper valley."])] = None
489
529
 
490
530
 
531
+ class OrganizationSyncTask(BaseSchema):
532
+ created_at: Annotated[AwareDatetime, Field(alias="createdAt")]
533
+ created_by: Annotated[
534
+ UUID, Field(alias="createdBy", description="The keycloak user id of the PDC user that requested this sync.")
535
+ ]
536
+ details: Annotated[
537
+ Details | None,
538
+ Field(
539
+ description="The summary of a completed sync run (counts for organizations and memberships), or an `error` message describing why the run failed; null until the task finishes."
540
+ ),
541
+ ]
542
+ id: Annotated[int, Field(examples=[3407])]
543
+ status: Status
544
+ status_updated_at: Annotated[AwareDatetime, Field(alias="statusUpdatedAt")]
545
+
546
+
491
547
  class PartialChangemaker(BaseSchema):
492
548
  keycloak_organization_id: Annotated[
493
549
  UUID | None,
@@ -612,7 +668,7 @@ class UserSyncTask(BaseSchema):
612
668
  UUID, Field(alias="createdBy", description="The keycloak user id of the PDC user that requested this sync.")
613
669
  ]
614
670
  details: Annotated[
615
- Details | None, Field(description="The summary of the completed sync run; null until the task completes.")
671
+ Details1 | None, Field(description="The summary of the completed sync run; null until the task completes.")
616
672
  ]
617
673
  id: Annotated[int, Field(examples=[3407])]
618
674
  status: Status
@@ -727,7 +783,43 @@ class OpportunityBundle(Bundle):
727
783
  class Organization(BaseSchema):
728
784
  changemaker: ShallowChangemaker | None = None
729
785
  data_provider: Annotated[DataProvider | None, Field(alias="dataProvider")] = None
786
+ disabled_at: Annotated[
787
+ AwareDatetime | None,
788
+ Field(
789
+ alias="disabledAt",
790
+ description="The time this organization was observed as absent from or not enabled in Keycloak by a sync; null if the organization is still live in Keycloak.",
791
+ ),
792
+ ] = None
793
+ former_members: Annotated[
794
+ list[User] | None,
795
+ Field(
796
+ alias="formerMembers",
797
+ description="The organization's former members, the cached users whose cached membership Keycloak no longer reports; null when the caller may not see membership data.",
798
+ validate_default=True,
799
+ ),
800
+ ] = []
730
801
  funder: Funder | None = None
802
+ keycloak_organization_id: Annotated[
803
+ UUID, Field(alias="keycloakOrganizationId", description="The Keycloak-assigned UUID of the organization.")
804
+ ]
805
+ keycloak_organization_name: Annotated[
806
+ str | None,
807
+ Field(
808
+ alias="keycloakOrganizationName",
809
+ description="The organization name as reported by Keycloak; null until the first successful organization sync.",
810
+ ),
811
+ ] = None
812
+ members: Annotated[
813
+ list[User] | None,
814
+ Field(
815
+ description="The organization's current cached members as cached users; null when the caller may not see membership data.",
816
+ validate_default=True,
817
+ ),
818
+ ] = []
819
+
820
+
821
+ class OrganizationBundle(Bundle):
822
+ entries: Annotated[list[Organization], Field(description="The collection of requested resources.")]
731
823
 
732
824
 
733
825
  class ProposalFieldValue(FieldValueBase):
@@ -1,4 +1,5 @@
1
1
  import json
2
+ import time
2
3
  from collections.abc import Generator
3
4
  from datetime import datetime
4
5
  from typing import Any, ClassVar, Protocol, Self
@@ -20,10 +21,13 @@ from pdc_api.models import (
20
21
  InitiativeFieldValue,
21
22
  NewProposalVersion,
22
23
  Organization,
24
+ OrganizationSyncTask,
23
25
  PresignedPost,
24
26
  Proposal,
25
27
  ProposalVersion,
26
28
  Source,
29
+ SyncTaskStatus,
30
+ UserSyncTask,
27
31
  )
28
32
  from pdc_api.transport import APISession
29
33
 
@@ -76,6 +80,12 @@ def get_funders(session: APISession) -> Generator[Funder, None, None]:
76
80
  yield Funder.model_validate(entry)
77
81
 
78
82
 
83
+ def get_organizations(session: APISession) -> Generator[Organization, None, None]:
84
+ for payload in _iterate_pages(session, endpoint="organizations"):
85
+ for entry in payload["entries"]:
86
+ yield Organization.model_validate(entry)
87
+
88
+
79
89
  def get_data_providers(session: APISession) -> Generator[DataProvider, None, None]:
80
90
  for payload in _iterate_pages(session, endpoint="dataProviders"):
81
91
  for entry in payload["entries"]:
@@ -330,3 +340,49 @@ def upload_file_to_s3_presigned_url(
330
340
  response.raise_for_status()
331
341
  except requests.RequestException as exc:
332
342
  raise errors.PDCServiceError(detail=f"Could not upload file to S3: {exc}") from exc
343
+
344
+
345
+ def sync_users_from_keycloak(
346
+ session: APISession, *, poll_interval_seconds: float = 0.5, timeout_seconds: float = 120.0
347
+ ) -> UserSyncTask:
348
+ return _run_sync_task(
349
+ session,
350
+ endpoint="users/sync",
351
+ task_type=UserSyncTask,
352
+ poll_interval_seconds=poll_interval_seconds,
353
+ timeout_seconds=timeout_seconds,
354
+ )
355
+
356
+
357
+ def sync_organizations_from_keycloak(
358
+ session: APISession, *, poll_interval_seconds: float = 0.5, timeout_seconds: float = 120.0
359
+ ) -> OrganizationSyncTask:
360
+ return _run_sync_task(
361
+ session,
362
+ endpoint="organizations/sync",
363
+ task_type=OrganizationSyncTask,
364
+ poll_interval_seconds=poll_interval_seconds,
365
+ timeout_seconds=timeout_seconds,
366
+ )
367
+
368
+
369
+ def _run_sync_task[SyncTask: (UserSyncTask, OrganizationSyncTask)](
370
+ session: APISession,
371
+ *,
372
+ endpoint: str,
373
+ task_type: type[SyncTask],
374
+ poll_interval_seconds: float,
375
+ timeout_seconds: float,
376
+ ) -> SyncTask:
377
+ task = task_type.model_validate(session.post(endpoint).json())
378
+ deadline = time.monotonic() + timeout_seconds
379
+ while task.status in (SyncTaskStatus.PENDING, SyncTaskStatus.IN_PROGRESS):
380
+ if time.monotonic() >= deadline:
381
+ raise errors.KeycloakSyncError(
382
+ detail=f"{endpoint} task {task.id} still {task.status} after {timeout_seconds}s"
383
+ )
384
+ time.sleep(poll_interval_seconds)
385
+ task = task_type.model_validate(session.get(f"{endpoint}/{task.id}").json())
386
+ if task.status != SyncTaskStatus.COMPLETED:
387
+ raise errors.KeycloakSyncError(detail=f"{endpoint} task {task.id} {task.status}: {task.details}")
388
+ return task
@@ -37,6 +37,10 @@ class PDCUnprocessableEntityError(PDCException):
37
37
  pass
38
38
 
39
39
 
40
+ class KeycloakSyncError(PDCException):
41
+ pass
42
+
43
+
40
44
  class TokenRequestError(PDCException):
41
45
  pass
42
46
 
@@ -25,6 +25,7 @@ from pdc_api._generated import (
25
25
  InitiativeFieldValue,
26
26
  Opportunity,
27
27
  Organization,
28
+ OrganizationSyncTask,
28
29
  PermissionGrantEntityType,
29
30
  PermissionGrantGranteeType,
30
31
  PermissionGrantVerb,
@@ -36,6 +37,7 @@ from pdc_api._generated import (
36
37
  SensitivityClassification,
37
38
  ShallowChangemaker,
38
39
  Source,
40
+ UserSyncTask,
39
41
  )
40
42
  from pdc_api._generated import (
41
43
  ApplicationFormFieldInputType as InputType,
@@ -43,6 +45,9 @@ from pdc_api._generated import (
43
45
  from pdc_api._generated import (
44
46
  DataType as BaseFieldDataType,
45
47
  )
48
+ from pdc_api._generated import (
49
+ Status as SyncTaskStatus,
50
+ )
46
51
 
47
52
  __all__ = [
48
53
  "ApplicationFormField",
@@ -73,6 +78,7 @@ __all__ = [
73
78
  "Opportunity",
74
79
  "OpportunityBundle",
75
80
  "Organization",
81
+ "OrganizationSyncTask",
76
82
  "PermissionGrantEntityType",
77
83
  "PermissionGrantGranteeType",
78
84
  "PermissionGrantVerb",
@@ -85,6 +91,8 @@ __all__ = [
85
91
  "SensitivityClassification",
86
92
  "ShallowChangemaker",
87
93
  "Source",
94
+ "SyncTaskStatus",
95
+ "UserSyncTask",
88
96
  ]
89
97
 
90
98