diff --git a/.github/workflows/build-publish.yml b/.github/workflows/build-publish.yml index 4367474..f6269e0 100644 --- a/.github/workflows/build-publish.yml +++ b/.github/workflows/build-publish.yml @@ -28,13 +28,13 @@ jobs: images: | [ { - "name": "openg2p-pbms-core", - "repo": "openg2p/openg2p-pbms-core", + "name": "openg2p-pbms-odoo-base", + "repo": "openg2p/openg2p-pbms-odoo-base", "dockerfile": "docker/openg2p-pbms-odoo/utils/Dockerfile" }, { - "name": "openg2p-pbms-staff-portal-api", - "repo": "openg2p/openg2p-pbms-staff-portal-api", + "name": "openg2p-pbms-staff-api-base", + "repo": "openg2p/openg2p-pbms-staff-api-base", "dockerfile": "docker/openg2p-pbms-apis/staff-portal-api/Dockerfile", "pins": [ { @@ -45,8 +45,8 @@ jobs: ] }, { - "name": "openg2p-pbms-bene-portal-api", - "repo": "openg2p/openg2p-pbms-bene-portal-api", + "name": "openg2p-pbms-beneficiary-api", + "repo": "openg2p/openg2p-pbms-beneficiary-api", "dockerfile": "docker/openg2p-pbms-apis/bene-portal-api/Dockerfile", "pins": [ { @@ -57,9 +57,9 @@ jobs: ] }, { - "name": "openg2p-pbms-bg-task-celery-workers", - "repo": "openg2p/openg2p-pbms-bg-task-celery-workers", - "dockerfile": "docker/openg2p-pbms-bg-tasks/bg-task-celery-worker/Dockerfile", + "name": "openg2p-pbms-celery-base", + "repo": "openg2p/openg2p-pbms-celery-base", + "dockerfile": "docker/openg2p-pbms-bg-tasks/celery/Dockerfile", "pins": [ { "arg": "FASTAPI_COMMON_REF", @@ -72,25 +72,13 @@ jobs: "ref": "develop" } ] - }, - { - "name": "openg2p-pbms-bg-task-celery-beat-producers", - "repo": "openg2p/openg2p-pbms-bg-task-celery-beat-producers", - "dockerfile": "docker/openg2p-pbms-bg-tasks/bg-task-celery-beat/Dockerfile", - "pins": [ - { - "arg": "FASTAPI_COMMON_REF", - "repo": "https://github.com/openg2p/openg2p-fastapi-common", - "ref": "develop" - } - ] } ] - chart-path: deployment/charts/openg2p-pbms + chart-path: deployment/charts/openg2p-pbms-platform chart-image-paths: | - [".odoo.image.tag",".staffPortalApi.image.tag",".benePortalApi.image.tag",".celeryWorkers.image.tag",".beatProducers.image.tag"] + [".odoo.image.tag",".celeryWorkers.image.tag",".beatProducers.image.tag",".staffPortalApi.image.tag",".benePortalApi.image.tag"] packaging-ref: v1 diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 442e1e9..8c637f7 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -18,7 +18,6 @@ jobs: matrix: project: - core - - extensions - apis - docker - deployment diff --git a/README.md b/README.md index 0b318c0..2f6b5c9 100644 --- a/README.md +++ b/README.md @@ -8,34 +8,30 @@ entitlement engine, the portal APIs, Docker packaging, and a single Helm chart. | Path | Description | License | |------|-------------|---------| -| `odoo/` | Odoo modules — core (`g2p_pbms`, `g2p_pbms_program_access`), `extensions/`, and `community-addons/` | LGPL-3.0 | +| `odoo/` | Odoo modules — core (`g2p_pbms`, `g2p_pbms_program_access`) and `community-addons/` | LGPL-3.0 | | `core/` | Background-task engine — PBMS + bg-task models, Celery workers and beat producers | MPL-2.0 | -| `extensions/` | Registry adapter extensions for the background-task engine | MPL-2.0 | | `apis/` | Staff Portal and Beneficiary Portal FastAPI services | MPL-2.0 | -| `docker/` | Dockerfiles for the Odoo (`core`), API, and Celery images | MPL-2.0 | -| `deployment/` | Single consolidated Helm chart (`charts/openg2p-pbms`) | MPL-2.0 | +| `docker/` | Dockerfiles for the Odoo, API, and Celery base images | MPL-2.0 | +| `deployment/` | Platform Helm chart (`charts/openg2p-pbms-platform`) | MPL-2.0 | ## Images Built from local source by the workflows under `.github/workflows/`, tagged with -the branch name (a push to `develop` publishes `:develop`): +the branch name (a push to `develop` publishes `:develop`). Names ending in +`-base` are extended by `pbms-connectors`. The beneficiary API is installed as-is. -- `openg2p/openg2p-pbms-core` (Odoo) -- `openg2p/openg2p-pbms-staff-portal-api` -- `openg2p/openg2p-pbms-bene-portal-api` -- `openg2p/openg2p-pbms-bg-task-celery-workers` -- `openg2p/openg2p-pbms-bg-task-celery-beat-producers` +- `openg2p/openg2p-pbms-odoo-base` +- `openg2p/openg2p-pbms-celery-base` (worker and beat, selected by `CELERY_APP`) +- `openg2p/openg2p-pbms-staff-api-base` +- `openg2p/openg2p-pbms-beneficiary-api` ## Helm -The chart under `deployment/charts/openg2p-pbms` installs and runs all of PBMS. -Chart versions are published to -[openg2p-helm](https://openg2p.github.io/openg2p-helm) by the `helm-publish` -workflow, versioned from the branch (`develop` → `0.0.0-develop.`). - -```sh -helm install pbms deployment/charts/openg2p-pbms -``` +`deployment/charts/openg2p-pbms-platform` holds the Kubernetes templates and the +base image tags. Install `openg2p-pbms` from `pbms-connectors`, which depends on +this chart. Chart versions are published to +[openg2p-helm](https://openg2p.github.io/openg2p-helm) by the build workflow, +versioned from the branch (`develop` → `0.0.0-develop.`). External OpenG2P libraries (e.g. `openg2p-fastapi-common`) are tracked at their `develop` branch. diff --git a/apis/openg2p-pbms-bene-portal-api/.env.example b/apis/openg2p-pbms-bene-portal-api/.env.example index 7f21170..1c2d161 100644 --- a/apis/openg2p-pbms-bene-portal-api/.env.example +++ b/apis/openg2p-pbms-bene-portal-api/.env.example @@ -1,4 +1,4 @@ -# Social Registry Database +# PBMS database PBMS_BENE_PORTAL_API_DB_USERNAME_PBMS='postgres' PBMS_BENE_PORTAL_API_DB_PASSWORD_PBMS='password' PBMS_BENE_PORTAL_API_DB_HOSTNAME_PBMS='localhost' diff --git a/apis/openg2p-pbms-staff-portal-api/.env.example b/apis/openg2p-pbms-staff-portal-api/.env.example index 2ec0413..3449ce3 100644 --- a/apis/openg2p-pbms-staff-portal-api/.env.example +++ b/apis/openg2p-pbms-staff-portal-api/.env.example @@ -1,13 +1,23 @@ -# Social Registry Database -STAFF_PORTAL_API_DB_USERNAME_SR='postgres' -STAFF_PORTAL_API_DB_PASSWORD_SR='password' -STAFF_PORTAL_API_DB_HOSTNAME_SR='localhost' -STAFF_PORTAL_API_DB_PORT_SR='5432' -STAFF_PORTAL_API_DB_DBNAME_SR='socialregistrydb' +# Background task database. Prefix is staff_portal_api_. +STAFF_PORTAL_API_DB_DRIVER=postgresql+asyncpg +STAFF_PORTAL_API_DB_USERNAME=postgres +STAFF_PORTAL_API_DB_PASSWORD=postgres +STAFF_PORTAL_API_DB_HOSTNAME=localhost +STAFF_PORTAL_API_DB_PORT=5432 +STAFF_PORTAL_API_DB_DBNAME=bgtaskdb -# Background Task Database -STAFF_PORTAL_API_DB_USERNAME_BG_TASK='postgres' -STAFF_PORTAL_API_DB_PASSWORD_BG_TASK='password' -STAFF_PORTAL_API_DB_HOSTNAME_BG_TASK='localhost' -STAFF_PORTAL_API_DB_PORT_BG_TASK='5432' -STAFF_PORTAL_API_DB_DBNAME_BG_TASK='bgtaskdb' +# Registry adapter. Same variables on the Celery worker. db or dci. +REGISTRY_ADAPTERS_CONNECTOR=db +REGISTRY_ADAPTERS_DB_DRIVER=postgresql +REGISTRY_ADAPTERS_DB_USERNAME=postgres +REGISTRY_ADAPTERS_DB_PASSWORD=postgres +REGISTRY_ADAPTERS_DB_HOSTNAME=localhost +REGISTRY_ADAPTERS_DB_PORT=5432 +REGISTRY_ADAPTERS_DB_DBNAME=socialregistrydb +REGISTRY_ADAPTERS_PARTNER_API_URL=http://localhost:8000 +REGISTRY_ADAPTERS_PARTNER_API_TIMEOUT=30 +REGISTRY_ADAPTERS_PARTNER_API_SSL_VERIFY=true +REGISTRY_ADAPTERS_FARMER_REG_TYPE=Farmer +REGISTRY_ADAPTERS_HOUSEHOLD_REG_TYPE=Household +REGISTRY_ADAPTERS_FARMER_REG_RECORD_TYPE=Farmer +REGISTRY_ADAPTERS_HOUSEHOLD_REG_RECORD_TYPE=Household diff --git a/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/config.py b/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/config.py index a099aa6..c37508d 100644 --- a/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/config.py +++ b/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/config.py @@ -17,10 +17,3 @@ class Settings(BaseSettings): *********************************** """ openapi_version: str = __version__ - - # Social Registry - db_username_sr: str = "postgres" - db_password_sr: str = "password" - db_hostname_sr: str = "localhost" - db_port_sr: int = 5432 - db_dbname_sr: str = "socialregistrydb" diff --git a/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/engine.py b/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/engine.py index a42afeb..1e663e8 100644 --- a/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/engine.py +++ b/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/engine.py @@ -1,47 +1,12 @@ -import logging - from sqlalchemy.ext.asyncio import create_async_engine from .config import Settings _config = Settings.get_config() -_logger = logging.getLogger(_config.logging_default_logger_name) - - -def construct_db_datasource( - db_driver, db_username, db_password, db_hostname, db_port, db_dbname -) -> str: - datasource = "" - if db_driver: - datasource += f"{db_driver}://" - if db_username: - datasource += f"{db_username}:{db_password}@" - if db_hostname: - datasource += db_hostname - if db_port: - datasource += f":{db_port}" - if db_dbname: - datasource += f"/{db_dbname}" - - _logger.info(f"Constructed Datasource: {datasource}") - - return datasource def get_engine(): if _config.db_datasource: - db_datasource_sr = construct_db_datasource( - _config.db_driver, - _config.db_username_sr, - _config.db_password_sr, - _config.db_hostname_sr, - _config.db_port_sr, - _config.db_dbname_sr, - ) - - db_engine_bg_task = create_async_engine(_config.db_datasource) - db_engine_sr = create_async_engine(db_datasource_sr) return { - "db_engine_bg_task": db_engine_bg_task, - "db_engine_sr": db_engine_sr, + "db_engine_bg_task": create_async_engine(_config.db_datasource), } diff --git a/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/services/beneficiary_search.py b/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/services/beneficiary_search.py index 21d4b09..57737a4 100644 --- a/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/services/beneficiary_search.py +++ b/apis/openg2p-pbms-staff-portal-api/src/openg2p_pbms_staff_portal_api/services/beneficiary_search.py @@ -38,11 +38,8 @@ async def search_beneficiaries( session_maker = async_sessionmaker( bind=_engine.get("db_engine_bg_task"), expire_on_commit=False ) - sr_session_maker = async_sessionmaker( - bind=_engine.get("db_engine_sr"), expire_on_commit=False - ) - async with session_maker() as session, sr_session_maker() as sr_session: + async with session_maker() as session: try: registry_interface: RegistryInterface = ( RegistryFactory.get_registry_class( @@ -54,7 +51,6 @@ async def search_beneficiaries( total_count, ) = await registry_interface.search_beneficiaries( session, - sr_session, beneficiary_search_request_payload.beneficiary_list_id, beneficiary_search_request_payload.target_registry, pagination_request.search_text, diff --git a/core/openg2p-bg-task-celery-beat-producers/.env.example b/core/openg2p-bg-task-celery-beat-producers/.env.example index 4f1ca2a..65f3aa2 100644 --- a/core/openg2p-bg-task-celery-beat-producers/.env.example +++ b/core/openg2p-bg-task-celery-beat-producers/.env.example @@ -1,26 +1,18 @@ BG_TASK_CELERY_BEAT_CELERY_BROKER_URL=redis://localhost:6379/0 BG_TASK_CELERY_BEAT_CELERY_BACKEND_URL=redis://localhost:6379/0 -BG_TASK_CELERY_BEAT_PRODUCER_FREQUENCY=10 +BG_TASK_CELERY_BEAT_PRODUCER_FREQUENCY=30 BG_TASK_CELERY_BEAT_BATCH_SIZE=2000 +BG_TASK_CELERY_BEAT_NO_OF_TASKS_TO_PROCESS=5 +BG_TASK_CELERY_BEAT_BG_TASK_WORKER_QUEUE=bg_task_worker_queue -# Background Task Database -BG_TASK_CELERY_BEAT__DB_USERNAME='postgres' -BG_TASK_CELERY_BEAT__DB_PASSWORD='password' -BG_TASK_CELERY_BEAT__DB_HOSTNAME='localhost' -BG_TASK_CELERY_BEAT__DB_PORT=5432 -BG_TASK_CELERY_BEAT__DB_DBNAME='bgtaskdb' +# PBMS database +BG_TASK_CELERY_BEAT_DB_USERNAME_PBMS=postgres +BG_TASK_CELERY_BEAT_DB_PASSWORD_PBMS=postgres +BG_TASK_CELERY_BEAT_DB_HOSTNAME_PBMS=localhost +BG_TASK_CELERY_BEAT_DB_PORT_PBMS=5432 +BG_TASK_CELERY_BEAT_DB_DBNAME_PBMS=pbmsdb -# Social Registry Database -BG_TASK_CELERY_BEAT__DB_USERNAME_SR='postgres' -BG_TASK_CELERY_BEAT__DB_PASSWORD_SR='password' -BG_TASK_CELERY_BEAT__DB_HOSTNAME_SR='localhost' -BG_TASK_CELERY_BEAT__DB_PORT_SR=5432 -BG_TASK_CELERY_BEAT__DB_DBNAME_SR='socialregistrydb' - -# PBMS Database -BG_TASK_CELERY_BEAT__DB_USERNAME_PBMS='postgres' -BG_TASK_CELERY_BEAT__DB_PASSWORD_PBMS='password' -BG_TASK_CELERY_BEAT__DB_HOSTNAME_PBMS='localhost' -BG_TASK_CELERY_BEAT__DB_PORT_PBMS=5432 -BG_TASK_CELERY_BEAT__DB_DBNAME_PBMS='pbmsdb' +# One image runs worker or beat. The chart sets these on the beat deployment. +CELERY_APP=openg2p_bg_task_celery_beat_producers.main.celery_app +CELERY_OPTS=worker --beat -Q celery --loglevel=info --schedule=/tmp/celery-beat-schedule.db diff --git a/core/openg2p-bg-task-celery-beat-producers/src/openg2p_bg_task_celery_beat_producers/app.py b/core/openg2p-bg-task-celery-beat-producers/src/openg2p_bg_task_celery_beat_producers/app.py index c5f3854..5942db2 100644 --- a/core/openg2p-bg-task-celery-beat-producers/src/openg2p_bg_task_celery_beat_producers/app.py +++ b/core/openg2p-bg-task-celery-beat-producers/src/openg2p_bg_task_celery_beat_producers/app.py @@ -43,14 +43,6 @@ def construct_db_datasource( def get_engine(): if _config.db_datasource: - db_datasource_sr = construct_db_datasource( - _config.db_driver, - _config.db_username_sr, - _config.db_password_sr, - _config.db_hostname_sr, - _config.db_port_sr, - _config.db_dbname_sr, - ) db_datasource_pbms = construct_db_datasource( _config.db_driver, _config.db_username_pbms, @@ -60,11 +52,9 @@ def get_engine(): _config.db_dbname_pbms, ) db_engine_bg_task = create_engine(_config.db_datasource, poolclass=NullPool) - db_engine_sr = create_engine(db_datasource_sr, poolclass=NullPool) db_engine_pbms = create_engine(db_datasource_pbms, poolclass=NullPool) return { "db_engine_bg_task": db_engine_bg_task, - "db_engine_sr": db_engine_sr, "db_engine_pbms": db_engine_pbms, } diff --git a/core/openg2p-bg-task-celery-beat-producers/src/openg2p_bg_task_celery_beat_producers/config.py b/core/openg2p-bg-task-celery-beat-producers/src/openg2p_bg_task_celery_beat_producers/config.py index 902d4b1..dc92bb9 100644 --- a/core/openg2p-bg-task-celery-beat-producers/src/openg2p_bg_task_celery_beat_producers/config.py +++ b/core/openg2p-bg-task-celery-beat-producers/src/openg2p_bg_task_celery_beat_producers/config.py @@ -20,13 +20,6 @@ class Settings(BaseSettings): # DB Driver Overwrite db_driver: str = "postgresql" - # Social Registry Database - db_username_sr: str = "postgres" - db_password_sr: str = "postgres" - db_hostname_sr: str = "localhost" - db_port_sr: int = 5432 - db_dbname_sr: str = "socialregistrydb" - # PBMS Database db_username_pbms: str = "postgres" db_password_pbms: str = "postgres" diff --git a/core/openg2p-bg-task-celery-workers/.env.example b/core/openg2p-bg-task-celery-workers/.env.example index e1c3a34..344ff9d 100644 --- a/core/openg2p-bg-task-celery-workers/.env.example +++ b/core/openg2p-bg-task-celery-workers/.env.example @@ -1,4 +1,4 @@ -BG_TASK_CELERY_WORKERS_G2P_BRIDGE_BASE_URL= "https://g2p_brige_base_url" +BG_TASK_CELERY_WORKERS_G2P_BRIDGE_BASE_URL=http://g2pbridge-api BG_TASK_CELERY_WORKERS_CELERY_BROKER_URL=redis://localhost:6379/0 BG_TASK_CELERY_WORKERS_CELERY_BACKEND_URL=redis://localhost:6379/0 @@ -6,15 +6,53 @@ BG_TASK_CELERY_WORKERS_CELERY_BACKEND_URL=redis://localhost:6379/0 BG_TASK_CELERY_WORKERS_BATCH_SIZE=2000 BG_TASK_CELERY_WORKERS_WORKER_MAX_ATTEMPTS=5 -# TODO: refactor and remove -BG_TASK_CELERY_WORKERS_SIGN_KEY_KEYMANAGER_APP_ID="PBMS" -BG_TASK_CELERY_WORKERS_SIGN_KEY_KEYMANAGER_REF_ID="" +# Background task database +BG_TASK_CELERY_WORKERS_DB_USERNAME=postgres +BG_TASK_CELERY_WORKERS_DB_PASSWORD=postgres +BG_TASK_CELERY_WORKERS_DB_HOSTNAME=localhost +BG_TASK_CELERY_WORKERS_DB_PORT=5432 +BG_TASK_CELERY_WORKERS_DB_DBNAME=bgtaskdb -BG_TASK_CELERY_WORKERS_KEYMANAGER_SIGN_APP_ID="OPENG2P_PBMS" -BG_TASK_CELERY_WORKERS_KEYMANAGER_SIGN_REF_ID="" +# PBMS database +BG_TASK_CELERY_WORKERS_DB_USERNAME_PBMS=postgres +BG_TASK_CELERY_WORKERS_DB_PASSWORD_PBMS=postgres +BG_TASK_CELERY_WORKERS_DB_HOSTNAME_PBMS=localhost +BG_TASK_CELERY_WORKERS_DB_PORT_PBMS=5432 +BG_TASK_CELERY_WORKERS_DB_DBNAME_PBMS=pbmsdb + +# Background task database (async) +BG_TASK_CELERY_WORKERS_DB_DRIVER_ASYNC=postgresql+asyncpg +BG_TASK_CELERY_WORKERS_DB_USERNAME_ASYNC=postgres +BG_TASK_CELERY_WORKERS_DB_PASSWORD_ASYNC=postgres +BG_TASK_CELERY_WORKERS_DB_HOSTNAME_ASYNC=localhost +BG_TASK_CELERY_WORKERS_DB_PORT_ASYNC=5432 +BG_TASK_CELERY_WORKERS_DB_DBNAME_ASYNC=bgtaskdb + +# Registry adapter. Same variables on the staff API. db or dci. +REGISTRY_ADAPTERS_CONNECTOR=db +REGISTRY_ADAPTERS_DB_DRIVER=postgresql +REGISTRY_ADAPTERS_DB_USERNAME=postgres +REGISTRY_ADAPTERS_DB_PASSWORD=postgres +REGISTRY_ADAPTERS_DB_HOSTNAME=localhost +REGISTRY_ADAPTERS_DB_PORT=5432 +REGISTRY_ADAPTERS_DB_DBNAME=socialregistrydb +REGISTRY_ADAPTERS_PARTNER_API_URL=http://localhost:8000 +REGISTRY_ADAPTERS_PARTNER_API_TIMEOUT=30 +REGISTRY_ADAPTERS_PARTNER_API_SSL_VERIFY=true +REGISTRY_ADAPTERS_FARMER_REG_TYPE=Farmer +REGISTRY_ADAPTERS_HOUSEHOLD_REG_TYPE=Household +REGISTRY_ADAPTERS_FARMER_REG_RECORD_TYPE=Farmer +REGISTRY_ADAPTERS_HOUSEHOLD_REG_RECORD_TYPE=Household + +# One image runs worker or beat. The chart sets these per deployment. +CELERY_APP=openg2p_bg_task_celery_workers.main.celery_app +CELERY_OPTS=worker -Q bg_task_worker_queue --loglevel=info + +BG_TASK_CELERY_WORKERS_KEYMANAGER_SIGN_APP_ID=OPENG2P_PBMS +BG_TASK_CELERY_WORKERS_KEYMANAGER_SIGN_REF_ID= BG_TASK_CELERY_WORKERS_KEYMANAGER_API_TIMEOUT=10 -BG_TASK_CELERY_WORKERS_KEYMANAGER_API_BASE_URL="" -BG_TASK_CELERY_WORKERS_KEYMANAGER_AUTH_ENABLED=True -BG_TASK_CELERY_WORKERS_KEYMANAGER_AUTH_URL="" -BG_TASK_CELERY_WORKERS_KEYMANAGER_AUTH_CLIENT_ID="openg2p-pbms-dev" -BG_TASK_CELERY_WORKERS_KEYMANAGER_AUTH_CLIENT_SECRET="" +BG_TASK_CELERY_WORKERS_KEYMANAGER_API_BASE_URL= +BG_TASK_CELERY_WORKERS_KEYMANAGER_AUTH_ENABLED=true +BG_TASK_CELERY_WORKERS_KEYMANAGER_AUTH_URL= +BG_TASK_CELERY_WORKERS_KEYMANAGER_AUTH_CLIENT_ID=openg2p-pbms +BG_TASK_CELERY_WORKERS_KEYMANAGER_AUTH_CLIENT_SECRET= diff --git a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/app.py b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/app.py index 488ab3d..211fd8d 100644 --- a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/app.py +++ b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/app.py @@ -44,14 +44,6 @@ def construct_db_datasource( def get_engine(): if _config.db_datasource: - db_datasource_sr = construct_db_datasource( - _config.db_driver, - _config.db_username_sr, - _config.db_password_sr, - _config.db_hostname_sr, - _config.db_port_sr, - _config.db_dbname_sr, - ) db_datasource_pbms = construct_db_datasource( _config.db_driver, _config.db_username_pbms, @@ -69,14 +61,12 @@ def get_engine(): _config.db_dbname_async, ) db_engine_bg_task = create_engine(_config.db_datasource, poolclass=NullPool) - db_engine_sr = create_engine(db_datasource_sr, poolclass=NullPool) db_engine_pbms = create_engine(db_datasource_pbms, poolclass=NullPool) db_engine_bg_task_async = create_async_engine( db_datasource_bg_task_async, poolclass=NullPool ) return { "db_engine_bg_task": db_engine_bg_task, - "db_engine_sr": db_engine_sr, "db_engine_pbms": db_engine_pbms, "db_engine_bg_task_async": db_engine_bg_task_async, } diff --git a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/config.py b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/config.py index 1d5a377..673b468 100644 --- a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/config.py +++ b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/config.py @@ -27,13 +27,6 @@ class Settings(BaseSettings): db_port: int = 5432 db_dbname: str = "bgtaskdb" - # Social Registry Database - db_username_sr: str = "postgres" - db_password_sr: str = "postgres" - db_hostname_sr: str = "localhost" - db_port_sr: int = 5432 - db_dbname_sr: str = "socialregistrydb" - # PBMS Database db_username_pbms: str = "postgres" db_password_pbms: str = "postgres" diff --git a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/helpers/__init__.py b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/helpers/__init__.py index 6fe08ba..484efce 100644 --- a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/helpers/__init__.py +++ b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/helpers/__init__.py @@ -1,3 +1,2 @@ from .g2p_bridge_helper import G2PBridgeDisbursementHelper from .keymanager_helper import KeymanagerHelper -from .query_helper import construct_eligibility_query, construct_priority_query diff --git a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/helpers/query_helper.py b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/helpers/query_helper.py deleted file mode 100644 index 84b258a..0000000 --- a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/helpers/query_helper.py +++ /dev/null @@ -1,73 +0,0 @@ -import logging - -from sqlalchemy import TextClause, text - -from ..config import Settings - -_config = Settings.get_config() -_logger = logging.getLogger(_config.logging_default_logger_name) - - -def construct_eligibility_query( - sql_queries_and_set_operators: list[tuple], -) -> TextClause: - """ - Convert list of (SQL query, set operation) tuples - into a single SQL query using the set operations - """ - try: - if not sql_queries_and_set_operators or not isinstance( - sql_queries_and_set_operators, list - ): - return None - - query_parts = [] - for idx, (sql, set_op) in enumerate(sql_queries_and_set_operators): - if not sql: - continue - if idx == 0: - query_parts.append(sql) - else: - op = set_op if (set_op and set_op != "NONE") else "UNION" - query_parts.append(f"{op} {sql}") - - final_query = " ".join(query_parts) - - _logger.debug("Constructed eligibility query: %s", final_query) - return text(final_query) - except Exception as _: - return None - - -def construct_priority_query(sql_queries: list, registrant_ids: list) -> TextClause: - """ - Convert list of SQL queries into a single SQL query using INTERSECT - and filter the result to only include registrant_ids in the provided list. - """ - try: - if not sql_queries or not isinstance(sql_queries, list): - return None - - intersect_query = " INTERSECT ".join(sql_queries) - # Add the IN clause for registrant_ids - if registrant_ids: - # Prepare a comma-separated string of quoted IDs - # If IDs are integers, don't quote; if strings, quote - if all(isinstance(rid, int) for rid in registrant_ids): - ids_str = ",".join(str(rid) for rid in registrant_ids) - else: - ids_str = ",".join(f"'{str(rid)}'" for rid in registrant_ids) - # Wrap the intersect query as a subquery - filtered_query = f""" - SELECT * FROM ( - {intersect_query} - ) AS subquery - WHERE internal_record_id IN ({ids_str}) - """ - _logger.debug("Constructed query for priority: %s", filtered_query) - return text(filtered_query) - else: - _logger.debug("Constructed query for priority: %s", intersect_query) - return text(intersect_query) - except Exception as _: - return None diff --git a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/beneficiary_list_worker.py b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/beneficiary_list_worker.py index 04f6404..d57ef8f 100644 --- a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/beneficiary_list_worker.py +++ b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/beneficiary_list_worker.py @@ -21,10 +21,6 @@ from ..app import celery_app, get_engine from ..config import Settings -from ..helpers import ( - construct_eligibility_query, - construct_priority_query, -) _config = Settings.get_config() _logger = logging.getLogger(_config.logging_default_logger_name) @@ -37,17 +33,13 @@ def beneficiary_list_worker(id: int): bg_task_session_maker = sessionmaker( bind=_engine.get("db_engine_bg_task"), expire_on_commit=False ) - sr_session_maker = sessionmaker( - bind=_engine.get("db_engine_sr"), expire_on_commit=False - ) pbms_session_maker = sessionmaker( bind=_engine.get("db_engine_pbms"), expire_on_commit=False ) - with bg_task_session_maker() as bg_task_session, sr_session_maker() as sr_session, pbms_session_maker() as pbms_session: + with bg_task_session_maker() as bg_task_session, pbms_session_maker() as pbms_session: beneficiary_list = None try: - # Fetch the queue entry from pbms db using id beneficiary_list = ( pbms_session.query(G2PBeneficiaryList) .filter(G2PBeneficiaryList.id == id) @@ -58,76 +50,55 @@ def beneficiary_list_worker(id: int): .filter(G2PProgramDefinition.id == beneficiary_list.program_id) .first() ) - - constructed_query = None + registry: RegistryInterface = RegistryFactory.get_registry_class( + g2p_program_definition.target_registry + ) + enrollment_rules = _enrollment_rules(pbms_session, beneficiary_list.program_id) if beneficiary_list.list_stage == ListStageEnum.ENROLLMENT.value: - _logger.info( - "Constructing enrollment sql query for beneficiary list id: %s", id - ) - constructed_query = construct_enrollment_sql_query( - pbms_session, beneficiary_list + id_batches = registry.iter_eligible_ids( + enrollment_rules, _config.batch_size ) elif beneficiary_list.list_stage == ListStageEnum.DISBURSEMENT.value: - _logger.info( - "Constructing disbursement sql query for beneficiary list id: %s", - id, - ) - constructed_query = construct_disbursement_sql_query( - pbms_session, bg_task_session, beneficiary_list + id_batches = registry.iter_priority_ids( + _priority_domains(pbms_session, beneficiary_list), + _enrolled_ids(pbms_session, bg_task_session, beneficiary_list), + enrollment_rules, + _config.batch_size, ) else: - _logger.error( + raise ValueError( f"Invalid list stage {beneficiary_list.list_stage} for beneficiary list id {id}" ) - _logger.debug( - f"Constructed sql query for beneficiary list id {id} is: {constructed_query}" - ) - # Execute the constructed SQL query to fetch registrant details and build BeneficiaryListDetails objects total_number_of_registrants = 0 beneficiary_list_details: List[BeneficiaryListDetails] = [] - registry_cursor = sr_session.execute(constructed_query) - while True: - number_of_registrants_for_batch = 0 - registry_batch = registry_cursor.fetchmany(_config.batch_size) - registrant_details: List[RegistrantDetails] = [] - if not registry_batch: - break - for registry_row in registry_batch: - number_of_registrants_for_batch += 1 - registrant_details.append( - RegistrantDetails( - registrant_id=registry_row[0], - entitlement={}, - compute_elements={}, - ).model_dump(mode="json") - ) - - total_number_of_registrants += number_of_registrants_for_batch + for registrant_ids in id_batches: + if not registrant_ids: + continue + registrant_details = [ + RegistrantDetails( + registrant_id=registrant_id, + entitlement={}, + compute_elements={}, + ).model_dump(mode="json") + for registrant_id in registrant_ids + ] + total_number_of_registrants += len(registrant_ids) beneficiary_list_details.append( BeneficiaryListDetails( beneficiary_list_id=beneficiary_list.beneficiary_list_id, registrant_details=registrant_details, entitlement_process_status=StatusEnum.pending.value - if beneficiary_list.list_stage - == ListStageEnum.DISBURSEMENT.value + if beneficiary_list.list_stage == ListStageEnum.DISBURSEMENT.value else StatusEnum.not_applicable.value, - number_of_registrants=number_of_registrants_for_batch, + number_of_registrants=len(registrant_ids), ) ) - _logger.debug( - f"Count of registrant IDs for beneficiary list id {id} are: {total_number_of_registrants}" - ) - beneficiary_list.number_of_registrants = total_number_of_registrants - _logger.info(f"Adding eligibility details for beneficiary list id: {id}") + beneficiary_list.number_of_registrants = total_number_of_registrants bg_task_session.add_all(beneficiary_list_details) - _logger.info( - f"Computing and adding summary statistics for beneficiary list id: {id}" - ) - # Create base summary object base_summary = BeneficiaryListSummary( program_id=beneficiary_list.program_id, program_mnemonic=g2p_program_definition.program_mnemonic, @@ -136,43 +107,13 @@ def beneficiary_list_worker(id: int): number_of_registrants=total_number_of_registrants, date_created=datetime.now(timezone.utc), ) - _logger.debug( - f"Base summary for beneficiary list id {id} is: {base_summary}" + registry.compute_eligibility_statistics( + beneficiary_list_details, base_summary, bg_task_session ) - try: - # Get the appropriate summary computation class - summary_computation_interface: RegistryInterface = ( - RegistryFactory.get_registry_class( - g2p_program_definition.target_registry - ) - ) - - # Compute summary and add to session - summary_computation_interface.compute_eligibility_statistics( - beneficiary_list_details, base_summary, sr_session, bg_task_session - ) - - _logger.info( - f"Summary statistics added successfully for beneficiary list id: {id}" - ) - - except ValueError as e: - raise Exception( - f"Invalid registrant type for program_id {beneficiary_list.program_id}: {e}" - ) from e - - except Exception as e: - raise Exception( - f"Error computing summary statistics for beneficiary list id {id}: {e}" - ) from e - - # Update beneficiary list entry status beneficiary_list.eligibility_process_status = StatusEnum.complete.value - if beneficiary_list.list_stage == ListStageEnum.DISBURSEMENT.value: beneficiary_list.entitlement_process_status = StatusEnum.pending.value - beneficiary_list.processed_date = datetime.now(timezone.utc) bg_task_session.commit() @@ -180,11 +121,10 @@ def beneficiary_list_worker(id: int): except Exception as e: _logger.error( - "Error during processing eligibility request for beneficiary list id {}: {}".format( - id, str(e) - ) + "Error during processing eligibility request for beneficiary list id %s: %s", + id, + e, ) - # Rollback all sessions pbms_session.rollback() bg_task_session.rollback() @@ -201,26 +141,37 @@ def beneficiary_list_worker(id: int): raise e _logger.info( - "Completed processing eligibility request for beneficiary list id: %s" % id + "Completed processing eligibility request for beneficiary list id: %s", id ) -def construct_enrollment_sql_query(pbms_session, beneficiary_list): - sql_queries_and_set_operators = pbms_session.execute( +def _enrollment_rules(pbms_session, program_id) -> list[tuple[str, str]]: + rows = pbms_session.execute( select( - G2PEligibilityRuleDefinition.sql_query, + G2PEligibilityRuleDefinition.pbms_domain, G2PEligibilityRuleDefinition.set_operator, ) - .where(G2PEligibilityRuleDefinition.program_id == beneficiary_list.program_id) + .where(G2PEligibilityRuleDefinition.program_id == program_id) .order_by(G2PEligibilityRuleDefinition.rule_number.asc()) ).all() + return [(domain, operator) for domain, operator in rows] + - return construct_eligibility_query(sql_queries_and_set_operators) +def _priority_domains(pbms_session, beneficiary_list) -> list[str]: + return list( + pbms_session.execute( + select(G2PPriorityRuleDefinition.pbms_domain).where( + G2PPriorityRuleDefinition.disbursement_cycle_id + == beneficiary_list.disbursement_cycle_id + ) + ) + .scalars() + .all() + ) -def construct_disbursement_sql_query(pbms_session, bg_task_session, beneficiary_list): - # Get the beneficiary_list_id of the latest APPROVED FINAL ENROLMENT in the same program - latest_approved_final_enrollment_beneficiary_list_id = ( +def _enrolled_ids(pbms_session, bg_task_session, beneficiary_list) -> list[str]: + latest = ( pbms_session.query(G2PBeneficiaryList.beneficiary_list_id) .filter( G2PBeneficiaryList.program_id == beneficiary_list.program_id, @@ -231,48 +182,21 @@ def construct_disbursement_sql_query(pbms_session, bg_task_session, beneficiary_ .order_by(G2PBeneficiaryList.creation_date.desc()) .first() ) - if latest_approved_final_enrollment_beneficiary_list_id: - latest_approved_final_enrollment_beneficiary_list_id = ( - latest_approved_final_enrollment_beneficiary_list_id[0] - ) - - # Get the registrant_details field from beneficiary_list_details for the latest approved final enrollment - registrant_details_list = None - if latest_approved_final_enrollment_beneficiary_list_id: - registrant_details_list = ( - bg_task_session.execute( - select(BeneficiaryListDetails.registrant_details).where( - BeneficiaryListDetails.beneficiary_list_id - == latest_approved_final_enrollment_beneficiary_list_id - ) - ) - .scalars() - .all() - ) - - # Get approved registrant details for the latest approved final enrollment - registrant_ids = [] - for registrant_details in registrant_details_list: - if registrant_details: - if isinstance(registrant_details, str): - registrant_details = json.loads(registrant_details) - registrant_ids = [ - registrant["registrant_id"] for registrant in registrant_details - ] - - # Fetch priority rule SQL queries for the current disbursement cycle and construct the priority query using the list of registrant IDs - sql_queries = ( - pbms_session.execute( - select(G2PPriorityRuleDefinition.sql_query).where( - G2PPriorityRuleDefinition.disbursement_cycle_id - == beneficiary_list.disbursement_cycle_id + if not latest: + return [] + blocks = ( + bg_task_session.execute( + select(BeneficiaryListDetails.registrant_details).where( + BeneficiaryListDetails.beneficiary_list_id == latest[0] ) ) .scalars() .all() ) - return ( - construct_priority_query(sql_queries, registrant_ids) - if sql_queries - else construct_enrollment_sql_query(pbms_session, beneficiary_list) - ) + registrant_ids = [] + for block in blocks: + if isinstance(block, str): + block = json.loads(block) + for registrant in block or []: + registrant_ids.append(registrant["registrant_id"]) + return registrant_ids diff --git a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/entitlement_summary_worker.py b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/entitlement_summary_worker.py index 303ed51..3cf6fdc 100644 --- a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/entitlement_summary_worker.py +++ b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/entitlement_summary_worker.py @@ -27,14 +27,11 @@ def entitlement_summary_worker(id: int): bg_task_session_maker = sessionmaker( bind=_engine.get("db_engine_bg_task"), expire_on_commit=False ) - sr_session_maker = sessionmaker( - bind=_engine.get("db_engine_sr"), expire_on_commit=False - ) pbms_session_maker = sessionmaker( bind=_engine.get("db_engine_pbms"), expire_on_commit=False ) - with bg_task_session_maker() as bg_task_session, sr_session_maker() as sr_session, pbms_session_maker() as pbms_session: + with bg_task_session_maker() as bg_task_session, pbms_session_maker() as pbms_session: beneficiary_list = None try: beneficiary_list: G2PBeneficiaryList = ( @@ -57,7 +54,6 @@ def entitlement_summary_worker(id: int): registry_interface.compute_entitlement_statistics( beneficiary_list.beneficiary_list_id, bg_task_session, - sr_session, ) _logger.info( diff --git a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/entitlement_worker.py b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/entitlement_worker.py index 97d5ef6..79f84a2 100644 --- a/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/entitlement_worker.py +++ b/core/openg2p-bg-task-celery-workers/src/openg2p_bg_task_celery_workers/tasks/entitlement_worker.py @@ -29,14 +29,11 @@ def entitlement_worker(id: str): bg_task_session_maker = sessionmaker( bind=_engine.get("db_engine_bg_task"), expire_on_commit=False ) - sr_session_maker = sessionmaker( - bind=_engine.get("db_engine_sr"), expire_on_commit=False - ) pbms_session_maker = sessionmaker( bind=_engine.get("db_engine_pbms"), expire_on_commit=False ) - with bg_task_session_maker() as bg_task_session, sr_session_maker() as sr_session, pbms_session_maker() as pbms_session: + with bg_task_session_maker() as bg_task_session, pbms_session_maker() as pbms_session: beneficiary_list_details = None try: beneficiary_list_details = ( @@ -69,90 +66,61 @@ def entitlement_worker(id: str): .all() ) - registrant_details: List[RegistrantDetails] = [] - - for registrant_detail in beneficiary_list_details.registrant_details: - registrant_detail = RegistrantDetails(**registrant_detail) - _logger.debug( - "Calculating entitlement(s) for registrant id: %s", - registrant_detail.registrant_id, - ) + registrant_details: List[RegistrantDetails] = [ + RegistrantDetails(**item) + for item in beneficiary_list_details.registrant_details + ] + registrant_ids = [item.registrant_id for item in registrant_details] + registry_interface: RegistryInterface = RegistryFactory.get_registry_class( + target_registry + ) - for entitlement_rule_definition in entitlement_rule_definitions: - benefit_code_id = entitlement_rule_definition.benefit_code_id - program_benefit_code_max_quantity = ( - pbms_session.query(G2PProgramBenefitCodes.max_quantity) - .filter( - G2PProgramBenefitCodes.program_id - == beneficiary_list.program_id, - G2PProgramBenefitCodes.benefit_code_id == benefit_code_id, - ) - .first() - ) - max_quantity: float = ( - program_benefit_code_max_quantity[0] - if program_benefit_code_max_quantity - else 0 + for entitlement_rule_definition in entitlement_rule_definitions: + benefit_code_id = entitlement_rule_definition.benefit_code_id + program_benefit_code_max_quantity = ( + pbms_session.query(G2PProgramBenefitCodes.max_quantity) + .filter( + G2PProgramBenefitCodes.program_id == beneficiary_list.program_id, + G2PProgramBenefitCodes.benefit_code_id == benefit_code_id, ) + .first() + ) + max_quantity: float = ( + program_benefit_code_max_quantity[0] + if program_benefit_code_max_quantity + else 0 + ) + multipliers = registry_interface.entitlement_multipliers( + registrant_ids, + entitlement_rule_definition.pbms_domain, + entitlement_rule_definition.multiplier, + ) + for registrant_detail in registrant_details: if ( registrant_detail.entitlement is not None and benefit_code_id in registrant_detail.entitlement - and registrant_detail.entitlement[benefit_code_id] - == max_quantity + and registrant_detail.entitlement[benefit_code_id] == max_quantity ): continue - + multiplier_value = multipliers.get(str(registrant_detail.registrant_id)) + is_registrant_entitled = multiplier_value is not None + if not is_registrant_entitled: + multiplier_value = 0 + calculated_entitlement = 0 else: - try: - registry_interface: RegistryInterface = ( - RegistryFactory.get_registry_class( - entitlement_rule_definition.target_registry - ) - ) - is_registrant_entitled: bool = ( - registry_interface.get_is_registant_entitled( - registrant_detail.registrant_id, - entitlement_rule_definition.sql_query, - sr_session, - ) - ) - calculated_entitlement = 0 - multiplier_value = 0 - if is_registrant_entitled: - ( - calculated_entitlement, - multiplier_value, - ) = calculate_entitlement( - sr_session, - registrant_detail, - entitlement_rule_definition, - registry_interface, - ) - _logger.debug( - "Calculated entitlement for registrant id %s: %s", - registrant_detail.registrant_id, - calculated_entitlement, - ) - update_registrant_detail_json( - registrant_detail, - benefit_code_id, - max_quantity, - calculated_entitlement, - entitlement_rule_definition.multiplier, - multiplier_value, - is_registrant_entitled, - ) - - except Exception as e: - raise Exception( - f"Error processing entitlement rule id {entitlement_rule_definition.id} for registrant id {registrant_detail.registrant_id} in request beneficiary list id {id}: {e}" - ) from e - - registrant_details.append(registrant_detail) - - _logger.debug( - f"Entitlement processed for registrant_id {registrant_detail.registrant_id}: {registrant_detail}" - ) + calculated_entitlement = round( + multiplier_value * entitlement_rule_definition.quantity, + entitlement_rule_definition.decimal_places, + ) + update_registrant_detail_json( + registrant_detail, + benefit_code_id, + max_quantity, + calculated_entitlement, + entitlement_rule_definition.multiplier, + multiplier_value, + is_registrant_entitled, + ) _logger.info( "Updating beneficiary list details with calculated entitlements" @@ -199,17 +167,15 @@ def entitlement_worker(id: str): def compute_entitlement_statistics( - id, bg_task_session, sr_session, beneficiary_list_details, target_registry + id, bg_task_session, beneficiary_list_details, target_registry ): try: - # Get the appropriate summary computation class registry_interface: RegistryInterface = RegistryFactory.get_registry_class( target_registry ) registry_interface.compute_entitlement_statistics( beneficiary_list_details.beneficiary_list_id, bg_task_session, - sr_session, ) _logger.info( @@ -260,19 +226,3 @@ def update_registrant_detail_json( ] = multiplier_value -def calculate_entitlement( - sr_session, registrant_detail, entitlement_rule_definition, registry_interface -): - multiplier: float = 1.0 - if entitlement_rule_definition.multiplier: - multiplier = registry_interface.get_entitlement_multiplier( - entitlement_rule_definition.multiplier, - registrant_detail.registrant_id, - sr_session, - ) - calculated_entitlement = round( - multiplier * entitlement_rule_definition.quantity, - entitlement_rule_definition.decimal_places, - ) - - return calculated_entitlement, multiplier diff --git a/core/openg2p-pbms-models/src/openg2p_pbms_models/models/eligibility_rule_definition.py b/core/openg2p-pbms-models/src/openg2p_pbms_models/models/eligibility_rule_definition.py index 943f489..919a77d 100644 --- a/core/openg2p-pbms-models/src/openg2p_pbms_models/models/eligibility_rule_definition.py +++ b/core/openg2p-pbms-models/src/openg2p_pbms_models/models/eligibility_rule_definition.py @@ -19,6 +19,5 @@ class G2PEligibilityRuleDefinition(BaseORMModel): description = mapped_column(String, nullable=True) target_registry = mapped_column(String, nullable=False) pbms_domain = mapped_column(String, nullable=False) - sql_query = mapped_column(String, nullable=True) create_date = mapped_column(TIMESTAMP(timezone=False), nullable=True) write_date = mapped_column(TIMESTAMP(timezone=False), nullable=True) diff --git a/core/openg2p-pbms-models/src/openg2p_pbms_models/models/entitlement_rule_definition.py b/core/openg2p-pbms-models/src/openg2p_pbms_models/models/entitlement_rule_definition.py index 8f003b3..b9c7099 100644 --- a/core/openg2p-pbms-models/src/openg2p_pbms_models/models/entitlement_rule_definition.py +++ b/core/openg2p-pbms-models/src/openg2p_pbms_models/models/entitlement_rule_definition.py @@ -20,7 +20,6 @@ class G2PEntitlementRuleDefinition(BaseORMModel): decimal_places = mapped_column(Integer, nullable=True) multiplier = mapped_column(String, nullable=True) pbms_domain = mapped_column(String, nullable=False) - sql_query = mapped_column(String, nullable=False) create_date = mapped_column( String, nullable=True ) # Should be DateTime, but using String for "timestamp without time zone" diff --git a/core/openg2p-pbms-models/src/openg2p_pbms_models/models/priority_rule_definition.py b/core/openg2p-pbms-models/src/openg2p_pbms_models/models/priority_rule_definition.py index 81ba339..eaca396 100644 --- a/core/openg2p-pbms-models/src/openg2p_pbms_models/models/priority_rule_definition.py +++ b/core/openg2p-pbms-models/src/openg2p_pbms_models/models/priority_rule_definition.py @@ -16,4 +16,3 @@ class G2PPriorityRuleDefinition(BaseORMModel): program_id = mapped_column(Integer, nullable=True) target_registry = mapped_column(String, nullable=False) pbms_domain = mapped_column(String, nullable=False) - sql_query = mapped_column(String, nullable=False) diff --git a/deployment/charts/openg2p-pbms/.gitignore b/deployment/charts/openg2p-pbms-platform/.gitignore similarity index 100% rename from deployment/charts/openg2p-pbms/.gitignore rename to deployment/charts/openg2p-pbms-platform/.gitignore diff --git a/deployment/charts/openg2p-pbms/.helmignore b/deployment/charts/openg2p-pbms-platform/.helmignore similarity index 100% rename from deployment/charts/openg2p-pbms/.helmignore rename to deployment/charts/openg2p-pbms-platform/.helmignore diff --git a/deployment/charts/openg2p-pbms/Chart.yaml b/deployment/charts/openg2p-pbms-platform/Chart.yaml similarity index 83% rename from deployment/charts/openg2p-pbms/Chart.yaml rename to deployment/charts/openg2p-pbms-platform/Chart.yaml index 81c29d9..99c5527 100644 --- a/deployment/charts/openg2p-pbms/Chart.yaml +++ b/deployment/charts/openg2p-pbms-platform/Chart.yaml @@ -1,6 +1,6 @@ apiVersion: v2 -name: openg2p-pbms -description: Helm chart for OpenG2P PBMS +name: openg2p-pbms-platform +description: Helm chart for the OpenG2P PBMS platform. Templates and base images. Install openg2p-pbms, which depends on this chart. type: application # Version handling: # This `version` is a STATIC placeholder — NOT the published version. The @@ -27,5 +27,4 @@ dependencies: condition: redis.enabled icon: https://openg2p.github.io/openg2p-helm/openg2p-logo.png annotations: - catalog.cattle.io/display-name: "OpenG2P PBMS" - openg2p.org/add-to-rancher: "" + catalog.cattle.io/display-name: "OpenG2P PBMS Platform" diff --git a/deployment/charts/openg2p-pbms-platform/README.md b/deployment/charts/openg2p-pbms-platform/README.md new file mode 100644 index 0000000..908b28e --- /dev/null +++ b/deployment/charts/openg2p-pbms-platform/README.md @@ -0,0 +1,10 @@ +# OpenG2P PBMS Platform Helm Chart + +Templates and base images. Install the `openg2p-pbms` chart from `pbms-connectors`, which depends on this one. + +This contains the following components: + +- PBMS Odoo Package (Odoo + PostgreSQL) +- PBMS Background Tasks (API, Celery) +- MinIO +- Keymanager diff --git a/deployment/charts/openg2p-pbms/app-readme.md b/deployment/charts/openg2p-pbms-platform/app-readme.md similarity index 100% rename from deployment/charts/openg2p-pbms/app-readme.md rename to deployment/charts/openg2p-pbms-platform/app-readme.md diff --git a/deployment/charts/openg2p-pbms/questions.yaml b/deployment/charts/openg2p-pbms-platform/questions.yaml similarity index 59% rename from deployment/charts/openg2p-pbms/questions.yaml rename to deployment/charts/openg2p-pbms-platform/questions.yaml index d0576d8..5911805 100644 --- a/deployment/charts/openg2p-pbms/questions.yaml +++ b/deployment/charts/openg2p-pbms-platform/questions.yaml @@ -26,7 +26,7 @@ questions: # Odoo Settings - variable: odoo.image.tag - description: Image tag (version) for the Odoo (core) image + description: Image tag (version) for the Odoo base image type: string label: Odoo Image Tag group: Odoo Settings @@ -112,29 +112,99 @@ questions: show_if: "benePortalApi.enabled=true" # Registry settings +- variable: global.registryConnector + description: How PBMS reads the registry. db queries the registry database. dci calls the registry partner API POST /dci/sync/search. + type: enum + options: + - db + - dci + default: db + label: Registry Connector + group: Registry + - variable: global.registryDB - description: Name of the Registry DB in PostgreSQL + description: Name of the Registry DB in PostgreSQL. Used when the connector is db. type: string label: Registry DB group: Registry + show_if: "global.registryConnector=db" - variable: global.registryDBUser - description: Name of the Registry DB User in PostgreSQL + description: Name of the Registry DB User in PostgreSQL. Used when the connector is db. type: string label: Registry DB User group: Registry + show_if: "global.registryConnector=db" - variable: global.registryDBSecret - description: Name of the Registry DB Secret that contains user password + description: Name of the Registry DB Secret that contains the user password. Used when the connector is db. type: string label: Registry DB Secret with User Password group: Registry + show_if: "global.registryConnector=db" - variable: global.registryDBUserPasswordKey - description: Name of the Registry DB Secret key that contains user password + description: Key inside the Registry DB Secret that contains the user password. Used when the connector is db. type: string label: Registry DB Secret Key with User Password group: Registry + show_if: "global.registryConnector=db" + +- variable: global.registryPartnerApiUrl + description: Origin of the registry partner API, with no path. PBMS calls {url}/dci/sync/search. Used when the connector is dci. + type: string + default: http://registry-partner-api + label: Registry Partner API URL + group: Registry + show_if: "global.registryConnector=dci" + +- variable: global.registryPartnerApiTimeout + description: Seconds to wait for one registry partner API call. Used when the connector is dci. + type: int + default: 30 + label: Registry Partner API Timeout + group: Registry + show_if: "global.registryConnector=dci" + +- variable: global.registryPartnerApiSslVerify + description: Verify the registry partner API TLS certificate. Used when the connector is dci. + type: boolean + default: true + label: Registry Partner API TLS Verify + group: Registry + show_if: "global.registryConnector=dci" + +- variable: global.farmerRegType + description: DCI search reg_type for farmers. Must match the register mnemonic on the registry. + type: string + default: Farmer + label: Farmer Register Type + group: Registry + show_if: "global.registryConnector=dci" + +- variable: global.householdRegType + description: DCI search reg_type for households. Must match the register mnemonic on the registry. + type: string + default: Household + label: Household Register Type + group: Registry + show_if: "global.registryConnector=dci" + +- variable: global.farmerRegRecordType + description: DCI reg_record_type sent with a farmer search. + type: string + default: Farmer + label: Farmer Record Type + group: Registry + show_if: "global.registryConnector=dci" + +- variable: global.householdRegRecordType + description: DCI reg_record_type sent with a household search. + type: string + default: Household + label: Household Record Type + group: Registry + show_if: "global.registryConnector=dci" diff --git a/deployment/charts/openg2p-pbms/templates/_helper.tpl b/deployment/charts/openg2p-pbms-platform/templates/_helper.tpl similarity index 100% rename from deployment/charts/openg2p-pbms/templates/_helper.tpl rename to deployment/charts/openg2p-pbms-platform/templates/_helper.tpl diff --git a/deployment/charts/openg2p-pbms/templates/beat-producers/deployment.yaml b/deployment/charts/openg2p-pbms-platform/templates/beat-producers/deployment.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/beat-producers/deployment.yaml rename to deployment/charts/openg2p-pbms-platform/templates/beat-producers/deployment.yaml diff --git a/deployment/charts/openg2p-pbms/templates/beat-producers/serviceaccount.yaml b/deployment/charts/openg2p-pbms-platform/templates/beat-producers/serviceaccount.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/beat-producers/serviceaccount.yaml rename to deployment/charts/openg2p-pbms-platform/templates/beat-producers/serviceaccount.yaml diff --git a/deployment/charts/openg2p-pbms/templates/bene-portal-api/deployment.yaml b/deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/deployment.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/bene-portal-api/deployment.yaml rename to deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/deployment.yaml diff --git a/deployment/charts/openg2p-pbms/templates/bene-portal-api/gateway.yaml b/deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/gateway.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/bene-portal-api/gateway.yaml rename to deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/gateway.yaml diff --git a/deployment/charts/openg2p-pbms/templates/bene-portal-api/hpa.yaml b/deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/hpa.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/bene-portal-api/hpa.yaml rename to deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/hpa.yaml diff --git a/deployment/charts/openg2p-pbms/templates/bene-portal-api/service.yaml b/deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/service.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/bene-portal-api/service.yaml rename to deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/service.yaml diff --git a/deployment/charts/openg2p-pbms/templates/bene-portal-api/serviceaccount.yaml b/deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/serviceaccount.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/bene-portal-api/serviceaccount.yaml rename to deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/serviceaccount.yaml diff --git a/deployment/charts/openg2p-pbms/templates/bene-portal-api/virtualservice.yaml b/deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/virtualservice.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/bene-portal-api/virtualservice.yaml rename to deployment/charts/openg2p-pbms-platform/templates/bene-portal-api/virtualservice.yaml diff --git a/deployment/charts/openg2p-pbms/templates/celery-workers/deployment.yaml b/deployment/charts/openg2p-pbms-platform/templates/celery-workers/deployment.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/celery-workers/deployment.yaml rename to deployment/charts/openg2p-pbms-platform/templates/celery-workers/deployment.yaml diff --git a/deployment/charts/openg2p-pbms/templates/celery-workers/serviceaccount.yaml b/deployment/charts/openg2p-pbms-platform/templates/celery-workers/serviceaccount.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/celery-workers/serviceaccount.yaml rename to deployment/charts/openg2p-pbms-platform/templates/celery-workers/serviceaccount.yaml diff --git a/deployment/charts/openg2p-pbms/templates/gateway.yaml b/deployment/charts/openg2p-pbms-platform/templates/gateway.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/gateway.yaml rename to deployment/charts/openg2p-pbms-platform/templates/gateway.yaml diff --git a/deployment/charts/openg2p-pbms/templates/selfservice-gateway.yaml b/deployment/charts/openg2p-pbms-platform/templates/selfservice-gateway.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/selfservice-gateway.yaml rename to deployment/charts/openg2p-pbms-platform/templates/selfservice-gateway.yaml diff --git a/deployment/charts/openg2p-pbms/templates/selfservice-virtualservice.yaml b/deployment/charts/openg2p-pbms-platform/templates/selfservice-virtualservice.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/selfservice-virtualservice.yaml rename to deployment/charts/openg2p-pbms-platform/templates/selfservice-virtualservice.yaml diff --git a/deployment/charts/openg2p-pbms/templates/serviceprovider-gateway.yaml b/deployment/charts/openg2p-pbms-platform/templates/serviceprovider-gateway.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/serviceprovider-gateway.yaml rename to deployment/charts/openg2p-pbms-platform/templates/serviceprovider-gateway.yaml diff --git a/deployment/charts/openg2p-pbms/templates/serviceprovider-virtualservice.yaml b/deployment/charts/openg2p-pbms-platform/templates/serviceprovider-virtualservice.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/serviceprovider-virtualservice.yaml rename to deployment/charts/openg2p-pbms-platform/templates/serviceprovider-virtualservice.yaml diff --git a/deployment/charts/openg2p-pbms/templates/staff-portal-api/deployment.yaml b/deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/deployment.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/staff-portal-api/deployment.yaml rename to deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/deployment.yaml diff --git a/deployment/charts/openg2p-pbms/templates/staff-portal-api/gateway.yaml b/deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/gateway.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/staff-portal-api/gateway.yaml rename to deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/gateway.yaml diff --git a/deployment/charts/openg2p-pbms/templates/staff-portal-api/hpa.yaml b/deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/hpa.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/staff-portal-api/hpa.yaml rename to deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/hpa.yaml diff --git a/deployment/charts/openg2p-pbms/templates/staff-portal-api/service.yaml b/deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/service.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/staff-portal-api/service.yaml rename to deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/service.yaml diff --git a/deployment/charts/openg2p-pbms/templates/staff-portal-api/serviceaccount.yaml b/deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/serviceaccount.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/staff-portal-api/serviceaccount.yaml rename to deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/serviceaccount.yaml diff --git a/deployment/charts/openg2p-pbms/templates/staff-portal-api/virtualservice.yaml b/deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/virtualservice.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/staff-portal-api/virtualservice.yaml rename to deployment/charts/openg2p-pbms-platform/templates/staff-portal-api/virtualservice.yaml diff --git a/deployment/charts/openg2p-pbms/templates/virtualservice.yaml b/deployment/charts/openg2p-pbms-platform/templates/virtualservice.yaml similarity index 100% rename from deployment/charts/openg2p-pbms/templates/virtualservice.yaml rename to deployment/charts/openg2p-pbms-platform/templates/virtualservice.yaml diff --git a/deployment/charts/openg2p-pbms/values.yaml b/deployment/charts/openg2p-pbms-platform/values.yaml similarity index 87% rename from deployment/charts/openg2p-pbms/values.yaml rename to deployment/charts/openg2p-pbms-platform/values.yaml index a1719e2..1e1223c 100644 --- a/deployment/charts/openg2p-pbms/values.yaml +++ b/deployment/charts/openg2p-pbms-platform/values.yaml @@ -32,6 +32,15 @@ global: registryDBUser: 'registry_user' registryDBSecret: 'registry' registryDBUserPasswordKey: 'registry-db-user' + # db uses the registry database. dci calls the registry partner API. + registryConnector: db + registryPartnerApiUrl: http://registry-partner-api + registryPartnerApiTimeout: 30 + registryPartnerApiSslVerify: true + farmerRegType: Farmer + householdRegType: Household + farmerRegRecordType: Farmer + householdRegRecordType: Household mailInstallationName: commons-mail @@ -85,7 +94,7 @@ odoo: extraAddonsUrlsToPull: '' image: - repository: openg2p/openg2p-pbms-core + repository: openg2p/openg2p-pbms-odoo-base tag: "develop" pullPolicy: Always @@ -170,7 +179,7 @@ beatProducers: name: "" image: - repository: openg2p/openg2p-pbms-bg-task-celery-beat-producers + repository: openg2p/openg2p-pbms-celery-base tag: "develop" pullPolicy: Always @@ -213,12 +222,6 @@ beatProducers: BG_TASK_CELERY_BEAT_DB_DBNAME: '{{ tpl .Values.global.pbmsBgTaskDB $ }}' BG_TASK_CELERY_BEAT_DB_USERNAME: '{{ tpl .Values.global.pbmsBgTaskDBUser $ }}' - # Social Registry Database - BG_TASK_CELERY_BEAT_DB_HOSTNAME_SR: '{{ tpl .Values.global.postgresqlHost $ }}' - BG_TASK_CELERY_BEAT_DB_PORT_SR: 5432 - BG_TASK_CELERY_BEAT_DB_DBNAME_SR: '{{ tpl .Values.global.registryDB $ }}' - BG_TASK_CELERY_BEAT_DB_USERNAME_SR: '{{ tpl .Values.global.registryDBUser $ }}' - # PBMS Database BG_TASK_CELERY_BEAT_DB_USERNAME_PBMS: '{{ tpl .Values.global.pbmsDBUser $ }}' BG_TASK_CELERY_BEAT_DB_HOSTNAME_PBMS: '{{ tpl .Values.global.postgresqlHost $ }}' @@ -227,16 +230,14 @@ beatProducers: BG_TASK_CELERY_BEAT_CELERY_BROKER_URL: redis://{{ tpl .Values.global.redisInstallationName $ }}:6379/0 BG_TASK_CELERY_BEAT_CELERY_BACKEND_URL: redis://{{ tpl .Values.global.redisInstallationName $ }}:6379/0 + CELERY_APP: openg2p_bg_task_celery_beat_producers.main.celery_app + CELERY_OPTS: worker --beat -Q celery --loglevel=info --schedule=/tmp/celery-beat-schedule.db envVarsFrom: BG_TASK_CELERY_BEAT_DB_PASSWORD: secretKeyRef: name: '{{ tpl .Values.global.pbmsBgTaskDBSecret $ }}' key: '{{ tpl .Values.global.pbmsBgTaskDBUserPasswordKey $ }}' - BG_TASK_CELERY_BEAT_DB_PASSWORD_SR: - secretKeyRef: - name: '{{ tpl .Values.global.registryDBSecret $ }}' - key: '{{ tpl .Values.global.registryDBUserPasswordKey $ }}' BG_TASK_CELERY_BEAT_DB_PASSWORD_PBMS : secretKeyRef: name: '{{ tpl .Values.global.pbmsDBSecret $ }}' @@ -334,7 +335,7 @@ celeryWorkers: name: "" image: - repository: openg2p/openg2p-pbms-bg-task-celery-workers + repository: openg2p/openg2p-pbms-celery-base tag: "develop" pullPolicy: Always @@ -371,6 +372,8 @@ celeryWorkers: BG_TASK_CELERY_WORKERS_G2P_BRIDGE_BASE_URL: "http://g2p-bridge-api" BG_TASK_CELERY_WORKERS_CELERY_BROKER_URL: "redis://{{ tpl .Values.global.redisInstallationName $ }}:6379/0" BG_TASK_CELERY_WORKERS_CELERY_BACKEND_URL: "redis://{{ tpl .Values.global.redisInstallationName $ }}:6379/0" + CELERY_APP: openg2p_bg_task_celery_workers.main.celery_app + CELERY_OPTS: worker -Q bg_task_worker_queue --loglevel=info BG_TASK_CELERY_WORKERS_BATCH_SIZE: 500 @@ -380,11 +383,20 @@ celeryWorkers: BG_TASK_CELERY_WORKERS_DB_DBNAME: '{{ tpl .Values.global.pbmsBgTaskDB $ }}' BG_TASK_CELERY_WORKERS_DB_USERNAME: '{{ tpl .Values.global.pbmsBgTaskDBUser $ }}' - # Social Registry Database - BG_TASK_CELERY_WORKERS_DB_HOSTNAME_SR: '{{ tpl .Values.global.postgresqlHost $ }}' - BG_TASK_CELERY_WORKERS_DB_PORT_SR: 5432 - BG_TASK_CELERY_WORKERS_DB_DBNAME_SR: '{{ tpl .Values.global.registryDB $ }}' - BG_TASK_CELERY_WORKERS_DB_USERNAME_SR: '{{ tpl .Values.global.registryDBUser $ }}' + # Registry adapter (db session or DCI partner API). Same values on the staff API. + REGISTRY_ADAPTERS_CONNECTOR: '{{ tpl .Values.global.registryConnector $ }}' + REGISTRY_ADAPTERS_DB_DRIVER: postgresql + REGISTRY_ADAPTERS_DB_HOSTNAME: '{{ tpl .Values.global.postgresqlHost $ }}' + REGISTRY_ADAPTERS_DB_PORT: 5432 + REGISTRY_ADAPTERS_DB_DBNAME: '{{ tpl .Values.global.registryDB $ }}' + REGISTRY_ADAPTERS_DB_USERNAME: '{{ tpl .Values.global.registryDBUser $ }}' + REGISTRY_ADAPTERS_PARTNER_API_URL: '{{ tpl .Values.global.registryPartnerApiUrl $ }}' + REGISTRY_ADAPTERS_PARTNER_API_TIMEOUT: '{{ .Values.global.registryPartnerApiTimeout }}' + REGISTRY_ADAPTERS_PARTNER_API_SSL_VERIFY: '{{ .Values.global.registryPartnerApiSslVerify }}' + REGISTRY_ADAPTERS_FARMER_REG_TYPE: '{{ tpl .Values.global.farmerRegType $ }}' + REGISTRY_ADAPTERS_HOUSEHOLD_REG_TYPE: '{{ tpl .Values.global.householdRegType $ }}' + REGISTRY_ADAPTERS_FARMER_REG_RECORD_TYPE: '{{ tpl .Values.global.farmerRegRecordType $ }}' + REGISTRY_ADAPTERS_HOUSEHOLD_REG_RECORD_TYPE: '{{ tpl .Values.global.householdRegRecordType $ }}' # PBMS Database BG_TASK_CELERY_WORKERS_DB_HOSTNAME_PBMS: '{{ tpl .Values.global.postgresqlHost $ }}' @@ -417,7 +429,7 @@ celeryWorkers: secretKeyRef: name: '{{ tpl .Values.global.pbmsBgTaskDBSecret $ }}' key: '{{ tpl .Values.global.pbmsBgTaskDBUserPasswordKey $ }}' - BG_TASK_CELERY_WORKERS_DB_PASSWORD_SR: + REGISTRY_ADAPTERS_DB_PASSWORD: secretKeyRef: name: '{{ tpl .Values.global.registryDBSecret $ }}' key: '{{ tpl .Values.global.registryDBUserPasswordKey $ }}' @@ -503,7 +515,7 @@ staffPortalApi: name: "" image: - repository: openg2p/openg2p-pbms-staff-portal-api + repository: openg2p/openg2p-pbms-staff-api-base tag: "develop" pullPolicy: Always @@ -534,10 +546,19 @@ staffPortalApi: runAsNonRoot: true envVars: - STAFF_PORTAL_API_DB_USERNAME_SR: '{{ tpl .Values.global.registryDBUser $ }}' - STAFF_PORTAL_API_DB_HOSTNAME_SR: '{{ tpl .Values.global.postgresqlHost $ }}' - STAFF_PORTAL_API_DB_PORT_SR: 5432 - STAFF_PORTAL_API_DB_DBNAME_SR: '{{ tpl .Values.global.registryDB $ }}' + REGISTRY_ADAPTERS_CONNECTOR: '{{ tpl .Values.global.registryConnector $ }}' + REGISTRY_ADAPTERS_DB_DRIVER: postgresql + REGISTRY_ADAPTERS_DB_HOSTNAME: '{{ tpl .Values.global.postgresqlHost $ }}' + REGISTRY_ADAPTERS_DB_PORT: 5432 + REGISTRY_ADAPTERS_DB_DBNAME: '{{ tpl .Values.global.registryDB $ }}' + REGISTRY_ADAPTERS_DB_USERNAME: '{{ tpl .Values.global.registryDBUser $ }}' + REGISTRY_ADAPTERS_PARTNER_API_URL: '{{ tpl .Values.global.registryPartnerApiUrl $ }}' + REGISTRY_ADAPTERS_PARTNER_API_TIMEOUT: '{{ .Values.global.registryPartnerApiTimeout }}' + REGISTRY_ADAPTERS_PARTNER_API_SSL_VERIFY: '{{ .Values.global.registryPartnerApiSslVerify }}' + REGISTRY_ADAPTERS_FARMER_REG_TYPE: '{{ tpl .Values.global.farmerRegType $ }}' + REGISTRY_ADAPTERS_HOUSEHOLD_REG_TYPE: '{{ tpl .Values.global.householdRegType $ }}' + REGISTRY_ADAPTERS_FARMER_REG_RECORD_TYPE: '{{ tpl .Values.global.farmerRegRecordType $ }}' + REGISTRY_ADAPTERS_HOUSEHOLD_REG_RECORD_TYPE: '{{ tpl .Values.global.householdRegRecordType $ }}' STAFF_PORTAL_API_OPENAPI_ROOT_PATH: "/" @@ -551,7 +572,7 @@ staffPortalApi: secretKeyRef: name: '{{ tpl .Values.global.pbmsBgTaskDBSecret $ }}' key: '{{ tpl .Values.global.pbmsBgTaskDBUserPasswordKey $ }}' - STAFF_PORTAL_API_DB_PASSWORD_SR: + REGISTRY_ADAPTERS_DB_PASSWORD: secretKeyRef: name: '{{ tpl .Values.global.registryDBSecret $ }}' key: '{{ tpl .Values.global.registryDBUserPasswordKey $ }}' @@ -667,7 +688,7 @@ benePortalApi: name: "" image: - repository: openg2p/openg2p-pbms-bene-portal-api + repository: openg2p/openg2p-pbms-beneficiary-api tag: "develop" pullPolicy: Always diff --git a/deployment/charts/openg2p-pbms/README.md b/deployment/charts/openg2p-pbms/README.md deleted file mode 100644 index 1fa075b..0000000 --- a/deployment/charts/openg2p-pbms/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# OpenG2P PBMS Helm Chart - -This contains the following components: - -- PBMS Odoo Package (Odoo + PostgreSQL) -- PBMS Background Tasks (API, Celery) -- MinIO -- Keymanager diff --git a/docker/openg2p-pbms-apis/bene-portal-api/Dockerfile b/docker/openg2p-pbms-apis/bene-portal-api/Dockerfile index 997c833..0ba707b 100644 --- a/docker/openg2p-pbms-apis/bene-portal-api/Dockerfile +++ b/docker/openg2p-pbms-apis/bene-portal-api/Dockerfile @@ -1,8 +1,7 @@ FROM python:3.12.11-alpine3.22 # External OpenG2P library refs (not part of this repo). Override via build-arg / -# workflow input. The PBMS API code + registry adapter extensions are installed -# from LOCAL source (build context = repo root). +# workflow input. The beneficiary portal API is installed from local source. ARG FASTAPI_COMMON_REF=develop RUN apk add --no-cache --virtual .build-deps gcc libc-dev linux-headers make \ @@ -17,17 +16,14 @@ RUN pip install --no-cache-dir \ "git+https://github.com/openg2p/openg2p-fastapi-common@${FASTAPI_COMMON_REF}#subdirectory=openg2p-fastapi-auth-models" \ && pip install --no-cache-dir jinja2 -# Local source: PBMS + bg-task models, the beneficiary portal API, and the -# registry adapter extensions. +# Local source: PBMS + bg-task models and the beneficiary portal API. COPY core/openg2p-pbms-models /src/openg2p-pbms-models COPY core/openg2p-bg-task-models /src/openg2p-bg-task-models COPY apis/openg2p-pbms-bene-portal-api /src/openg2p-pbms-bene-portal-api -COPY extensions/openg2p-bg-task-registry-adapters /src/openg2p-bg-task-registry-adapters RUN pip install --no-cache-dir \ /src/openg2p-pbms-models \ /src/openg2p-bg-task-models \ - /src/openg2p-pbms-bene-portal-api \ - /src/openg2p-bg-task-registry-adapters + /src/openg2p-pbms-bene-portal-api RUN apk del --no-network .build-deps diff --git a/docker/openg2p-pbms-apis/staff-portal-api/Dockerfile b/docker/openg2p-pbms-apis/staff-portal-api/Dockerfile index 3dcce0b..3737597 100644 --- a/docker/openg2p-pbms-apis/staff-portal-api/Dockerfile +++ b/docker/openg2p-pbms-apis/staff-portal-api/Dockerfile @@ -1,8 +1,8 @@ FROM python:3.12.11-alpine3.22 # External OpenG2P library refs (not part of this repo). Override via build-arg / -# workflow input. The PBMS API code + registry adapter extensions are installed -# from LOCAL source (build context = repo root). +# workflow input. The staff portal API is installed from local source. +# pbms-connectors installs registry-adapters on top of this image. ARG FASTAPI_COMMON_REF=develop RUN apk add --no-cache --virtual .build-deps gcc libc-dev linux-headers make \ @@ -17,17 +17,15 @@ RUN pip install --no-cache-dir \ "git+https://github.com/openg2p/openg2p-fastapi-common@${FASTAPI_COMMON_REF}#subdirectory=openg2p-fastapi-auth-models" \ && pip install --no-cache-dir jinja2 -# Local source: PBMS + bg-task models, the staff portal API, and the registry -# adapter extensions. +# Local source: PBMS + bg-task models and the staff portal API. +# Registry adapters are installed by the pbms-connectors image. COPY core/openg2p-pbms-models /src/openg2p-pbms-models COPY core/openg2p-bg-task-models /src/openg2p-bg-task-models COPY apis/openg2p-pbms-staff-portal-api /src/openg2p-pbms-staff-portal-api -COPY extensions/openg2p-bg-task-registry-adapters /src/openg2p-bg-task-registry-adapters RUN pip install --no-cache-dir \ /src/openg2p-pbms-models \ /src/openg2p-bg-task-models \ - /src/openg2p-pbms-staff-portal-api \ - /src/openg2p-bg-task-registry-adapters + /src/openg2p-pbms-staff-portal-api RUN apk del --no-network .build-deps diff --git a/docker/openg2p-pbms-bg-tasks/bg-task-celery-beat/Dockerfile b/docker/openg2p-pbms-bg-tasks/bg-task-celery-beat/Dockerfile deleted file mode 100644 index 2adce01..0000000 --- a/docker/openg2p-pbms-bg-tasks/bg-task-celery-beat/Dockerfile +++ /dev/null @@ -1,34 +0,0 @@ -FROM python:3.12.11-alpine3.22 - -# External OpenG2P library refs (not part of this repo). Override via build-arg / -# workflow input. The PBMS bg-task code is installed from LOCAL source -# (build context = repo root). -ARG FASTAPI_COMMON_REF=develop - -RUN apk add --no-cache --virtual .build-deps gcc libc-dev linux-headers make \ - && apk add --no-cache bash git gettext libpq-dev libffi-dev openssl-dev - -WORKDIR /app - -# External libs (openg2p-fastapi-common family) -RUN pip install --upgrade pip setuptools && \ - pip install --no-cache-dir \ - "git+https://github.com/openg2p/openg2p-fastapi-common@${FASTAPI_COMMON_REF}#subdirectory=openg2p-fastapi-common" \ - "git+https://github.com/openg2p/openg2p-fastapi-common@${FASTAPI_COMMON_REF}#subdirectory=openg2p-fastapi-auth" \ - "git+https://github.com/openg2p/openg2p-fastapi-common@${FASTAPI_COMMON_REF}#subdirectory=openg2p-fastapi-auth-models" - -# Local source: PBMS + bg-task models and the celery beat producers. -COPY core/openg2p-pbms-models /src/openg2p-pbms-models -COPY core/openg2p-bg-task-models /src/openg2p-bg-task-models -COPY core/openg2p-bg-task-celery-beat-producers /src/openg2p-bg-task-celery-beat-producers -RUN pip install --no-cache-dir \ - /src/openg2p-pbms-models \ - /src/openg2p-bg-task-models \ - /src/openg2p-bg-task-celery-beat-producers - -RUN apk del --no-network .build-deps - -ENV PYTHONUNBUFFERED=1 - -# Use module path for Celery beat app -CMD ["celery", "-A", "openg2p_bg_task_celery_beat_producers.main.celery_app", "worker", "--beat", "--loglevel=info", "--schedule=/tmp/celery-beat-schedule.db"] diff --git a/docker/openg2p-pbms-bg-tasks/bg-task-celery-worker/Dockerfile b/docker/openg2p-pbms-bg-tasks/celery/Dockerfile similarity index 60% rename from docker/openg2p-pbms-bg-tasks/bg-task-celery-worker/Dockerfile rename to docker/openg2p-pbms-bg-tasks/celery/Dockerfile index debe045..ac6e461 100644 --- a/docker/openg2p-pbms-bg-tasks/bg-task-celery-worker/Dockerfile +++ b/docker/openg2p-pbms-bg-tasks/celery/Dockerfile @@ -1,8 +1,8 @@ +# One Celery image for the worker and the beat producer. +# CELERY_APP selects the Python app. CELERY_OPTS selects worker or worker --beat. +# pbms-connectors installs registry-adapters on top of this image. FROM python:3.12.11-alpine3.22 -# External OpenG2P library refs (not part of this repo). Override via build-arg / -# workflow input. The PBMS bg-task code (models, workers) and the registry -# adapter extensions are installed from LOCAL source (build context = repo root). ARG FASTAPI_COMMON_REF=develop ARG G2P_BRIDGE_REF=develop @@ -11,7 +11,6 @@ RUN apk add --no-cache --virtual .build-deps gcc libc-dev linux-headers make \ WORKDIR /app -# External libs (openg2p-fastapi-common family + g2p-bridge models) RUN pip install --upgrade pip setuptools && \ pip install --no-cache-dir jinja2 && \ pip install --no-cache-dir \ @@ -20,21 +19,21 @@ RUN pip install --upgrade pip setuptools && \ "git+https://github.com/openg2p/openg2p-fastapi-common@${FASTAPI_COMMON_REF}#subdirectory=openg2p-fastapi-auth-models" \ "git+https://github.com/openg2p/g2p-bridge@${G2P_BRIDGE_REF}#subdirectory=core/models" -# Local source: PBMS + bg-task models, the celery workers, and the registry -# adapter extensions. Remaining deps resolve from PyPI via each pyproject. COPY core/openg2p-pbms-models /src/openg2p-pbms-models COPY core/openg2p-bg-task-models /src/openg2p-bg-task-models COPY core/openg2p-bg-task-celery-workers /src/openg2p-bg-task-celery-workers -COPY extensions/openg2p-bg-task-registry-adapters /src/openg2p-bg-task-registry-adapters +COPY core/openg2p-bg-task-celery-beat-producers /src/openg2p-bg-task-celery-beat-producers RUN pip install --no-cache-dir \ /src/openg2p-pbms-models \ /src/openg2p-bg-task-models \ /src/openg2p-bg-task-celery-workers \ - /src/openg2p-bg-task-registry-adapters + /src/openg2p-bg-task-celery-beat-producers \ + && apk del --no-network .build-deps -RUN apk del --no-network .build-deps +COPY docker/openg2p-pbms-bg-tasks/celery/run_celery.py /app/run_celery.py ENV PYTHONUNBUFFERED=1 +ENV CELERY_APP=openg2p_bg_task_celery_workers.main.celery_app +ENV CELERY_OPTS="worker -Q bg_task_worker_queue --loglevel=info" -# Use module path for Celery app (no local main.py) -CMD ["celery", "-A", "openg2p_bg_task_celery_workers.main.celery_app", "worker", "-Q", "bg_task_worker_queue", "--loglevel=debug"] +CMD ["python3", "/app/run_celery.py"] diff --git a/docker/openg2p-pbms-bg-tasks/celery/run_celery.py b/docker/openg2p-pbms-bg-tasks/celery/run_celery.py new file mode 100644 index 0000000..135724d --- /dev/null +++ b/docker/openg2p-pbms-bg-tasks/celery/run_celery.py @@ -0,0 +1,32 @@ +import importlib +import os +import sys + + +def get_app(): + app_path = os.environ.get("CELERY_APP") + if not app_path: + print("Error: CELERY_APP environment variable is not set.") + sys.exit(1) + + try: + if ":" in app_path: + module_name, app_attr = app_path.split(":", 1) + else: + module_name, app_attr = app_path.rsplit(".", 1) + module = importlib.import_module(module_name) + return getattr(module, app_attr) + except Exception as exc: + print(f"Error loading Celery app '{app_path}': {exc}") + sys.exit(1) + + +def main(): + celery_app = get_app() + opts = os.environ.get("CELERY_OPTS", "worker --loglevel=info").split() + print(f"Starting Celery with options: {opts}") + celery_app.start(argv=opts) + + +if __name__ == "__main__": + main() diff --git a/docker/openg2p-pbms-odoo/utils/Dockerfile b/docker/openg2p-pbms-odoo/utils/Dockerfile index e111d00..acbb639 100644 --- a/docker/openg2p-pbms-odoo/utils/Dockerfile +++ b/docker/openg2p-pbms-odoo/utils/Dockerfile @@ -20,7 +20,6 @@ RUN ln -s $(which python3) /usr/bin/python COPY odoo/g2p_pbms ${EXTRA_ADDONS_DIR}/pbms-core/g2p_pbms COPY odoo/g2p_pbms_program_access ${EXTRA_ADDONS_DIR}/pbms-core/g2p_pbms_program_access COPY odoo/requirements.txt ${EXTRA_ADDONS_DIR}/pbms-core/requirements.txt -COPY odoo/extensions ${EXTRA_ADDONS_DIR}/pbms-extensions COPY odoo/community-addons ${EXTRA_ADDONS_DIR}/community-addons # External OpenG2P Odoo commons, baked in at build time. diff --git a/extensions/.gitignore b/extensions/.gitignore deleted file mode 100644 index 09be0ef..0000000 --- a/extensions/.gitignore +++ /dev/null @@ -1,207 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[codz] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py.cover -.hypothesis/ -.pytest_cache/ -cover/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# UV -# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -#uv.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -#poetry.lock -#poetry.toml - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. -# https://pdm-project.org/en/latest/usage/project/#working-with-version-control -#pdm.lock -#pdm.toml -.pdm-python -.pdm-build/ - -# pixi -# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. -#pixi.lock -# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one -# in the .venv directory. It is recommended not to include this directory in version control. -.pixi - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - -# Environments -.env -.envrc -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ - -# Abstra -# Abstra is an AI-powered process automation framework. -# Ignore directories containing user credentials, local state, and settings. -# Learn more at https://abstra.io/docs -.abstra/ - -# Visual Studio Code -# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore -# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore -# and can be added to the global gitignore or merged into this file. However, if you prefer, -# you could uncomment the following to ignore the entire vscode folder -# .vscode/ - -# Ruff stuff: -.ruff_cache/ - -# PyPI configuration file -.pypirc - -# Cursor -# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to -# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data -# refer to https://docs.cursor.com/context/ignore-files -.cursorignore -.cursorindexingignore - -# Marimo -marimo/_static/ -marimo/_lsp/ -__marimo__/ diff --git a/extensions/.pre-commit-config.yaml b/extensions/.pre-commit-config.yaml deleted file mode 100644 index 336b7e1..0000000 --- a/extensions/.pre-commit-config.yaml +++ /dev/null @@ -1,49 +0,0 @@ -exclude: | - (?x) - # We don't want to mess with tool-generated files - .svg$|/tests/([^/]+/)?cassettes/|^.copier-answers.yml$|^.github/| - # Maybe reactivate this when all README files include prettier ignore tags? - ^README\.md$| - # Repos using Sphinx to generate docs don't need prettying - ^docs/_templates/.*\.html$| - # You don't usually want a bot to modify your legal texts - (LICENSE.*|COPYING.*) -default_language_version: - python: python3 -repos: - - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 - hooks: - - id: trailing-whitespace - - id: end-of-file-fixer - - id: debug-statements - - id: fix-encoding-pragma - args: ["--remove"] - - id: check-case-conflict - - id: check-docstring-first - - id: check-executables-have-shebangs - - id: check-merge-conflict - - id: check-symlinks - - id: check-toml - - id: check-yaml - args: - - --unsafe - - id: mixed-line-ending - args: ["--fix=lf"] - - repo: https://github.com/asottile/pyupgrade - rev: v3.11.0 - hooks: - - id: pyupgrade - args: - - --py3-plus - - --keep-runtime-typing - - repo: https://github.com/psf/black - rev: 23.9.1 - hooks: - - id: black - - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.0.289 - hooks: - - id: ruff - args: - - --fix diff --git a/extensions/.ruff.toml b/extensions/.ruff.toml deleted file mode 100644 index aa1fc5b..0000000 --- a/extensions/.ruff.toml +++ /dev/null @@ -1,16 +0,0 @@ -select = [ - "E", # pycodestyle errors - "W", # pycodestyle warnings - "F", # pyflakes - "I", # isort - "C", # flake8-comprehensions - "B", # flake8-bugbear -] -ignore = [ - "E501", # line too long, handled by black - "B008", # do not perform function calls in argument defaults - "C901", # too complex -] - -[per-file-ignores] -"__init__.py" = ["F401"] diff --git a/extensions/LICENSE b/extensions/LICENSE deleted file mode 100644 index a612ad9..0000000 --- a/extensions/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/extensions/README.md b/extensions/README.md deleted file mode 100644 index cf5dcd5..0000000 --- a/extensions/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# openg2p-pbms-bg-tasks-extensions - -Registry adapter extensions for the OpenG2P PBMS background-task engine. diff --git a/extensions/openg2p-bg-task-registry-adapters/CODE-OF-CONDUCT.md b/extensions/openg2p-bg-task-registry-adapters/CODE-OF-CONDUCT.md deleted file mode 100644 index e1949e1..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/CODE-OF-CONDUCT.md +++ /dev/null @@ -1,114 +0,0 @@ -# Code of Conduct - -## Contributor Covenant Code of Conduct - -### Preamble - -OpenG2P was created to foster an open, innovative and inclusive community around open source & open standard. -To clarify expected behaviour in our communities we have adopted the Contributor Covenant. This code of -conduct has been adopted by many other open source communities and we feel it expresses our values well. - -### Our Pledge - -We as members, contributors, and leaders pledge to make participation in our community a harassment-free -experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex -characteristics, gender identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy -community. - -### Our Standards - -Examples of behavior that contributes to a positive environment for our community include: - -- Demonstrating empathy and kindness toward other people -- Being respectful of differing opinions, viewpoints, and experiences -- Giving and gracefully accepting constructive feedback -- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience -- Focusing on what is best not just for us as individuals, but for the overall community - -Examples of unacceptable behavior include: - -- The use of sexualized language or imagery, and sexual attention or advances of any kind -- Trolling, insulting or derogatory comments, and personal or political attacks -- Public or private harassment -- Publishing others' private information, such as a physical or email address, without their explicit - permission -- Other conduct which could reasonably be considered inappropriate in a professional setting - -### Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will -take appropriate and fair corrective action in response to any behavior that they deem inappropriate, -threatening, offensive, or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki -edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate -reasons for moderation decisions when appropriate. - -### Scope - -This Code of Conduct applies within all community spaces, and also applies when an individual is officially -representing the community in public spaces. Examples of representing our community include using an official -e-mail address, posting via an official social media account, or acting as an appointed representative at an -online or offline event. - -### Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders -responsible for enforcement at \[INSERT CONTACT METHOD]. All complaints will be reviewed and investigated -promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the reporter of any incident. - -### Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining the consequences for any action -they deem in violation of this Code of Conduct: - -#### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in -the community. - -**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the -violation and an explanation of why the behavior was inappropriate. A public apology may be requested. - -#### 2. Warning - -**Community Impact**: A violation through a single incident or series of actions. - -**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, -including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. -This includes avoiding interactions in community spaces as well as external channels like social media. -Violating these terms may lead to a temporary or permanent ban. - -#### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a -specified period of time. No public or private interaction with the people involved, including unsolicited -interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may -lead to a permanent ban. - -#### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained -inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of -individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the community. - -### Attribution - -This Code of Conduct is adapted from the -[Contributor Covenant version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). - -Community Impact Guidelines were inspired by -[Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). - -For answers to common questions about this code of conduct, see the -[FAQ](https://www.contributor-covenant.org/faq). Translations are available -[here](https://www.contributor-covenant.org/translations). diff --git a/extensions/openg2p-bg-task-registry-adapters/CONTRIBUTING.md b/extensions/openg2p-bg-task-registry-adapters/CONTRIBUTING.md deleted file mode 100644 index c187f93..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/CONTRIBUTING.md +++ /dev/null @@ -1,2 +0,0 @@ -Refer to contribution guidelines -[here](https://github.com/OpenG2P/openg2p-documentation/blob/1.0.0/community/contributing-to-openg2p.md). diff --git a/extensions/openg2p-bg-task-registry-adapters/README.md b/extensions/openg2p-bg-task-registry-adapters/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/extensions/openg2p-bg-task-registry-adapters/pyproject.toml b/extensions/openg2p-bg-task-registry-adapters/pyproject.toml deleted file mode 100644 index 36635ed..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/pyproject.toml +++ /dev/null @@ -1,33 +0,0 @@ -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" - -[project] -name = "openg2p-bg-task-registry-adapters" -authors = [ - { name="OpenG2P", email="info@openg2p.org" }, -] -description = "OpenG2P PBMS Background Task Registry Adapters" -readme = "README.md" -requires-python = ">=3.7" -classifiers = [ - "Programming Language :: Python :: 3", - "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", - "Operating System :: OS Independent", -] -dependencies = [ - "openg2p-fastapi-common", - "openg2p-fastapi-auth", - "fastapi-cache2", - "numpy" -] -dynamic = ["version"] - -[project.urls] -Homepage = "https://openg2p.org" -Documentation = "https://docs.openg2p.org/" -Repository = "https://github.com/OpenG2P/pbms" -Source = "https://github.com/OpenG2P/pbms" - -[tool.hatch.version] -path = "src/openg2p_bg_task_registry_adapters/__init__.py" diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/__init__.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/__init__.py deleted file mode 100644 index d539d50..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "3.1.1" diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/cache.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/cache.py deleted file mode 100644 index b0fab13..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/cache.py +++ /dev/null @@ -1,18 +0,0 @@ -from fastapi_cache import FastAPICache -from fastapi_cache.backends.inmemory import InMemoryBackend - - -def init_cache(): - FastAPICache.init(InMemoryBackend(), prefix="fastapi-cache") - - -# Custom key builder function -def beneficiary_count_key_builder(func, namespace: str, *args, **kwargs): - """ - Build a custom cache key with `beneficiary_list_id` and `search_query`. - """ - args: list = kwargs.get("args") - beneficiary_list_id: str = args[2] - search_query: str = args[4] - - return f"{namespace}{beneficiary_list_id}{search_query}" diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/computations/__init__.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/computations/__init__.py deleted file mode 100644 index d33549d..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/computations/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .register_household import RegisterHousehold -from .registry_farmer import RegistryFarmer diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/computations/register_household.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/computations/register_household.py deleted file mode 100644 index bbf5819..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/computations/register_household.py +++ /dev/null @@ -1,438 +0,0 @@ -import logging -from typing import Any, Dict, List, Optional, Tuple - -import numpy as np -from fastapi_cache.decorator import cache -from openg2p_bg_task_models.models import BeneficiaryListDetails -from openg2p_bg_task_models.schemas import ( - BeneficiarySearchResponsePayload, - RegistrantDetails, -) -from sqlalchemy import update -from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy.future import select -from sqlalchemy.orm import Session - -from ..cache import beneficiary_count_key_builder -from ..interface import RegistryInterface -from ..models import ( - BeneficiaryListSummaryHousehold as BeneficiaryListSummaryHouseholdModel, -) -from ..models import G2PRegisterHousehold -from ..schema import ( - BeneficiaryListSummary, - BeneficiaryListSummaryHousehold, - BeneficiaryListSummaryHouseholdPayload, - G2PRegisterHouseholdPayload, -) - -_logger = logging.getLogger("app") - - -class RegisterHousehold(RegistryInterface): - """Fetches household data and computes summary statistics""" - - # =================== - # Summary API Methods - # =================== - async def get_summary( - self, - beneficiary_list_id: str, - bg_task_session: AsyncSession, - formated: bool = False, - ) -> BeneficiaryListSummaryHouseholdPayload: - result = await bg_task_session.execute( - select(BeneficiaryListSummaryHouseholdModel).where( - BeneficiaryListSummaryHouseholdModel.beneficiary_list_id - == beneficiary_list_id - ) - ) - summary_row = result.scalars().first() - return self._build_summary_payload(summary_row) - - def get_summary_sync( - self, beneficiary_list_id: str, bg_task_session: Session - ) -> BeneficiaryListSummaryHouseholdPayload: - summary_row = ( - bg_task_session.query(BeneficiaryListSummaryHouseholdModel) - .filter_by(beneficiary_list_id=beneficiary_list_id) - .first() - ) - return self._build_summary_payload(summary_row) - - def _build_summary_payload(self, row) -> BeneficiaryListSummaryHouseholdPayload: - def fmt(value, units): - return f"{value} {units}" if value is not None else None - - return BeneficiaryListSummaryHouseholdPayload( - beneficiary_list_summary=BeneficiaryListSummary( - id=row.id, - program_id=row.program_id, - program_mnemonic=row.program_mnemonic, - target_registry=row.target_registry, - beneficiary_list_id=row.beneficiary_list_id, - number_of_registrants=row.number_of_registrants, - date_created=row.date_created, - total_disbursement_quantity=row.total_disbursement_quantity, - average_entitlement_per_registrant=row.average_entitlement_per_person, - ), - registry_summary=BeneficiaryListSummaryHousehold( - size_children_u5_mean=fmt( - row.size_children_u5_mean, row.size_children_u5_units - ), - size_children_u5_q1=fmt( - row.size_children_u5_q1, row.size_children_u5_units - ), - size_children_u5_q2=fmt( - row.size_children_u5_q2, row.size_children_u5_units - ), - size_children_u5_q3=fmt( - row.size_children_u5_q3, row.size_children_u5_units - ), - size_elderly_mean=fmt(row.size_elderly_mean, row.size_elderly_units), - size_elderly_q1=fmt(row.size_elderly_q1, row.size_elderly_units), - size_elderly_q2=fmt(row.size_elderly_q2, row.size_elderly_units), - size_elderly_q3=fmt(row.size_elderly_q3, row.size_elderly_units), - rooms_count_mean=fmt(row.rooms_count_mean, row.rooms_count_units), - rooms_count_q1=fmt(row.rooms_count_q1, row.rooms_count_units), - rooms_count_q2=fmt(row.rooms_count_q2, row.rooms_count_units), - rooms_count_q3=fmt(row.rooms_count_q3, row.rooms_count_units), - overcrowding_indicator_mean=fmt( - row.overcrowding_indicator_mean, row.overcrowding_indicator_units - ), - overcrowding_indicator_q1=fmt( - row.overcrowding_indicator_q1, row.overcrowding_indicator_units - ), - overcrowding_indicator_q2=fmt( - row.overcrowding_indicator_q2, row.overcrowding_indicator_units - ), - overcrowding_indicator_q3=fmt( - row.overcrowding_indicator_q3, row.overcrowding_indicator_units - ), - entitlement_amount_q1=row.entitlement_amount_q1, - entitlement_amount_q2=row.entitlement_amount_q2, - entitlement_amount_q3=row.entitlement_amount_q3, - ), - ) - - # ============================== - # Beneficiary Search API Methods - # ============================== - async def search_beneficiaries( - self, - bg_task_session: AsyncSession, - sr_session: AsyncSession, - beneficiary_list_id: str, - target_registry: str, - search_query, - page: int = 1, - page_size: int = 10, - order_by: str = "internal_record_id asc", - ) -> Tuple[BeneficiarySearchResponsePayload, int]: - registrant_details_result = await bg_task_session.execute( - select(BeneficiaryListDetails.registrant_details).where( - BeneficiaryListDetails.beneficiary_list_id == beneficiary_list_id - ) - ) - registrant_details = registrant_details_result.scalars().all() - _logger.info( - "search_beneficiaries: beneficiary_list_id=%r registrant_details row_count=%d", - beneficiary_list_id, - len(registrant_details), - ) - registrant_ids = [] - for registrant_detail in registrant_details: - for registrant in registrant_detail: - registrant_ids.append(registrant["registrant_id"]) - - _logger.info( - "search_beneficiaries: registrant_ids count=%d ids=%r", - len(registrant_ids), - registrant_ids, - ) - _logger.info( - "search_beneficiaries: search_query=%r order_by=%r page=%r page_size=%r", - search_query, - order_by, - page, - page_size, - ) - - ( - household_search_query, - household_search_params, - ) = self.construct_beneficiary_search_sql_query( - registrant_ids, - target_registry, - search_query, - order_by, - page_size, - page, - ) - _logger.info( - "search_beneficiaries: sql=%r params=%r", - str(household_search_query), - household_search_params, - ) - - household_search_results = ( - (await sr_session.execute(household_search_query, household_search_params)) - .mappings() - .all() - ) - _logger.info( - "search_beneficiaries: result_count=%d", len(household_search_results) - ) - - total_beneficiary_count: int = await self._get_total_beneficiary_count( - sr_session, beneficiary_list_id, registrant_ids, search_query - ) - _logger.info( - "search_beneficiaries: total_beneficiary_count=%d", total_beneficiary_count - ) - - beneficiaries = [] - if household_search_results: - beneficiaries = [ - G2PRegisterHouseholdPayload( - internal_record_id=row["internal_record_id"], - functional_record_id=row["functional_record_id"], - household_head_name=row["household_head_name"], - headship_type=row["headship_type"], - size_total=row["size_total"], - size_children_u5=row["size_children_u5"], - size_elderly=row["size_elderly"], - number_of_female_members=row["number_of_female_members"], - number_of_male_members=row["number_of_male_members"], - dwelling_type=row["dwelling_type"], - tenure_status=row["tenure_status"], - rooms_count=row["rooms_count"], - overcrowding_indicator=float(row["overcrowding_indicator"]) - if row["overcrowding_indicator"] is not None - else None, - water_source_type=row["water_source_type"], - sanitation_type=row["sanitation_type"], - lighting_source=row["lighting_source"], - cooking_fuel_type=row["cooking_fuel_type"], - address_line_1=row["address_line_1"], - address_line_2=row["address_line_2"], - postal_code=row["postal_code"], - country_code=row["country_code"], - ) - for row in household_search_results - ] - - response_payload = BeneficiarySearchResponsePayload( - beneficiary_count=len(beneficiaries), - beneficiaries=beneficiaries, - ) - - return response_payload, total_beneficiary_count - - @cache(expire=120, key_builder=beneficiary_count_key_builder) - async def _get_total_beneficiary_count( - self, - sr_session: AsyncSession, - beneficiary_list_id: str, - registrant_ids: List[str], - search_query: Optional[str] = None, - ) -> int: - _logger.info( - "_get_total_beneficiary_count: registrant_ids count=%d search_query=%r", - len(registrant_ids), - search_query, - ) - ( - beneficiary_count_query, - beneficiary_count_params, - ) = self.construct_beneficiary_search_count_sql_query( - registrant_ids, "households", search_query - ) - _logger.info( - "_get_total_beneficiary_count: count_sql=%r params=%r", - str(beneficiary_count_query), - beneficiary_count_params, - ) - total_beneficiary_count = ( - await sr_session.execute(beneficiary_count_query, beneficiary_count_params) - ).scalar_one() - _logger.info("_get_total_beneficiary_count: result=%d", total_beneficiary_count) - return total_beneficiary_count - - # ================================= - # Eligibility Celery Worker Methods - # ================================= - def compute_eligibility_statistics( - self, - beneficiary_list_details: List[BeneficiaryListDetails], - base_summary, - sr_session: Session, - bg_task_session: Session, - ): - household_summary = BeneficiaryListSummaryHouseholdModel( - program_id=base_summary.program_id, - program_mnemonic=base_summary.program_mnemonic, - target_registry=base_summary.target_registry, - beneficiary_list_id=base_summary.beneficiary_list_id, - number_of_registrants=base_summary.number_of_registrants, - date_created=base_summary.date_created, - ) - - size_children_u5: List[int] = [] - size_elderly: List[int] = [] - rooms_count: List[int] = [] - overcrowding_indicator: List[float] = [] - - for beneficiary_list_detail in beneficiary_list_details: - registrant_ids = [] - for registrant_detail in beneficiary_list_detail.registrant_details: - registrant_detail = RegistrantDetails(**registrant_detail) - registrant_ids.append(registrant_detail.registrant_id) - - registrants = self.get_registrants_by_ids(registrant_ids, sr_session) - for household in registrants: - if household.size_children_u5 is not None: - size_children_u5.append(household.size_children_u5) - if household.size_elderly is not None: - size_elderly.append(household.size_elderly) - if household.rooms_count is not None: - rooms_count.append(household.rooms_count) - if household.overcrowding_indicator is not None: - overcrowding_indicator.append( - float(household.overcrowding_indicator) - ) - - self._apply_quartiles(household_summary, "size_children_u5", size_children_u5) - self._apply_quartiles(household_summary, "size_elderly", size_elderly) - self._apply_quartiles(household_summary, "rooms_count", rooms_count) - self._apply_quartiles( - household_summary, "overcrowding_indicator", overcrowding_indicator - ) - - bg_task_session.add(household_summary) - - @staticmethod - def _apply_quartiles(summary_obj, prefix: str, values: List[float]) -> None: - if not values: - return - arr = np.array(values) - setattr(summary_obj, f"{prefix}_mean", round(float(np.mean(arr)), 2)) - setattr( - summary_obj, - f"{prefix}_q1", - round(float(np.percentile(arr, 25, method="midpoint")), 2), - ) - setattr( - summary_obj, - f"{prefix}_q2", - round(float(np.percentile(arr, 50, method="midpoint")), 2), - ) - setattr( - summary_obj, - f"{prefix}_q3", - round(float(np.percentile(arr, 75, method="midpoint")), 2), - ) - - def get_registrants_by_ids( - self, registrant_ids, sr_session - ) -> List[G2PRegisterHousehold]: - households = sr_session.query(G2PRegisterHousehold).filter( - G2PRegisterHousehold.internal_record_id.in_(registrant_ids) - ) - return list(households.yield_per(500)) - - # ================================= - # Entitlement Celery Worker Methods - # ================================= - def get_is_registant_entitled( - self, registrant_id: str, sql_query: str, sr_session: Session - ) -> bool: - sql_query_with_registrant_id = ( - self.construct_get_is_registrant_entitled_sql_query( - registrant_id, "households", sql_query - ) - ) - result = sr_session.execute(sql_query_with_registrant_id).fetchone() - return result is not None - - def get_entitlement_multiplier( - self, multiplier: str, registrant_id: str, sr_session: Session - ) -> int: - if not multiplier or multiplier == "none": - return 1 - - sql_query = self.construct_multiplier_sql_query( - multiplier, target_registry="households" - ) - params = {"registrant_id": registrant_id} - result = sr_session.execute(sql_query, params).fetchone() - multiplier_value: int = ( - int(result[0]) if result and result[0] is not None else 1 - ) - return multiplier_value - - def compute_entitlement_statistics( - self, beneficiary_list_id: str, bg_task_session: Session, sr_session: Session - ): - beneficiary_list_details = ( - bg_task_session.query(BeneficiaryListDetails) - .filter_by(beneficiary_list_id=beneficiary_list_id) - .all() - ) - - entitlements: Dict[Any, List[float]] = {} - - for beneficiary_list_detail in beneficiary_list_details: - for registrant_detail in beneficiary_list_detail.registrant_details: - registrant_detail = RegistrantDetails(**registrant_detail) - for benefit_code_id, value in registrant_detail.entitlement.items(): - entitlements.setdefault(benefit_code_id, []).append(value) - - entitlement_stats = self.compute_stats_dict(entitlements) - - bg_task_session.execute( - update(BeneficiaryListSummaryHouseholdModel) - .where( - BeneficiaryListSummaryHouseholdModel.beneficiary_list_id - == beneficiary_list_id - ) - .values( - total_disbursement_quantity=dict(entitlement_stats["total"]), - average_entitlement_per_person=dict(entitlement_stats["average"]), - entitlement_amount_q1=dict(entitlement_stats["q1"]), - entitlement_amount_q2=dict(entitlement_stats["q2"]), - entitlement_amount_q3=dict(entitlement_stats["q3"]), - ) - ) - - def compute_stats_dict( - self, entitlements_dict: Dict[Any, List[float]] - ) -> Dict[str, Dict[Any, float]]: - stats: Dict[str, Dict[Any, float]] = { - "average": {}, - "q1": {}, - "q2": {}, - "q3": {}, - "total": {}, - } - for benefit_code_id, values in entitlements_dict.items(): - if not values: - stats["average"][benefit_code_id] = 0.0 - stats["q1"][benefit_code_id] = 0.0 - stats["q2"][benefit_code_id] = 0.0 - stats["q3"][benefit_code_id] = 0.0 - stats["total"][benefit_code_id] = 0.0 - else: - arr = np.array(values) - stats["average"][benefit_code_id] = round(float(np.mean(arr)), 2) - stats["q1"][benefit_code_id] = round( - float(np.percentile(arr, 25, method="midpoint")), 2 - ) - stats["q2"][benefit_code_id] = round( - float(np.percentile(arr, 50, method="midpoint")), 2 - ) - stats["q3"][benefit_code_id] = round( - float(np.percentile(arr, 75, method="midpoint")), 2 - ) - stats["total"][benefit_code_id] = float(np.sum(arr)) - return stats diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/computations/registry_farmer.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/computations/registry_farmer.py deleted file mode 100644 index 69721af..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/computations/registry_farmer.py +++ /dev/null @@ -1,434 +0,0 @@ -from typing import List - -import numpy as np -from fastapi_cache.decorator import cache -from openg2p_bg_task_models.models import BeneficiaryListDetails -from openg2p_bg_task_models.schemas import ( - BeneficiarySearchResponsePayload, - RegistrantDetails, -) -from openg2p_pbms_models.models import Gender -from sqlalchemy import update -from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy.future import select -from sqlalchemy.orm import Session - -from ..cache import beneficiary_count_key_builder -from ..interface import RegistryInterface -from ..models import ( - BeneficiaryListSummaryFarmer as BeneficiaryListSummaryFarmerModel, -) -from ..models import ( - G2PFarmerRegistry, -) -from ..schema import ( - BeneficiaryListSummary, - BeneficiaryListSummaryFarmer, - BeneficiaryListSummaryFarmerPayload, - G2PFarmerRegistryPayload, -) - - -class RegistryFarmer(RegistryInterface): - """Fetches farmer data and computes summary statistics""" - - # =================== - # Summary API Methods - # =================== - async def get_summary( - self, - beneficiary_list_id: str, - bg_task_session: AsyncSession, - formated: bool = False, - ) -> BeneficiaryListSummaryFarmerPayload: - beneficiary_list_summary_farmer = await bg_task_session.execute( - select(BeneficiaryListSummaryFarmerModel).where( - BeneficiaryListSummaryFarmerModel.beneficiary_list_id - == beneficiary_list_id - ) - ) - beneficiary_list_summary_farmer = ( - beneficiary_list_summary_farmer.scalars().first() - ) - - summary_farmer_payload = BeneficiaryListSummaryFarmerPayload( - beneficiary_list_summary=BeneficiaryListSummary( - id=beneficiary_list_summary_farmer.id, - program_id=beneficiary_list_summary_farmer.program_id, - program_mnemonic=beneficiary_list_summary_farmer.program_mnemonic, - target_registry=beneficiary_list_summary_farmer.target_registry, - beneficiary_list_id=beneficiary_list_summary_farmer.beneficiary_list_id, - number_of_registrants=beneficiary_list_summary_farmer.number_of_registrants, - date_created=beneficiary_list_summary_farmer.date_created, - total_disbursement_quantity=beneficiary_list_summary_farmer.total_disbursement_quantity, - average_entitlement_per_registrant=beneficiary_list_summary_farmer.average_entitlement_per_person, - ), - registry_summary=BeneficiaryListSummaryFarmer( - estimated_age_mean=f"{beneficiary_list_summary_farmer.estimated_age_mean} {beneficiary_list_summary_farmer.estimated_age_units}" - if beneficiary_list_summary_farmer.estimated_age_mean is not None - else None, - estimated_age_q1=f"{beneficiary_list_summary_farmer.estimated_age_q1} {beneficiary_list_summary_farmer.estimated_age_units}" - if beneficiary_list_summary_farmer.estimated_age_q1 is not None - else None, - estimated_age_q2=f"{beneficiary_list_summary_farmer.estimated_age_q2} {beneficiary_list_summary_farmer.estimated_age_units}" - if beneficiary_list_summary_farmer.estimated_age_q2 is not None - else None, - estimated_age_q3=f"{beneficiary_list_summary_farmer.estimated_age_q3} {beneficiary_list_summary_farmer.estimated_age_units}" - if beneficiary_list_summary_farmer.estimated_age_q3 is not None - else None, - average_entitlement_female=beneficiary_list_summary_farmer.average_entitlement_female, - average_entitlement_male=beneficiary_list_summary_farmer.average_entitlement_male, - entitlement_amount_q3=beneficiary_list_summary_farmer.entitlement_amount_q3, - entitlement_amount_q2=beneficiary_list_summary_farmer.entitlement_amount_q2, - entitlement_amount_q1=beneficiary_list_summary_farmer.entitlement_amount_q1, - entitlement_amount_male_q3=beneficiary_list_summary_farmer.entitlement_amount_male_q3, - entitlement_amount_male_q2=beneficiary_list_summary_farmer.entitlement_amount_male_q2, - entitlement_amount_male_q1=beneficiary_list_summary_farmer.entitlement_amount_male_q1, - entitlement_amount_female_q3=beneficiary_list_summary_farmer.entitlement_amount_female_q3, - entitlement_amount_female_q2=beneficiary_list_summary_farmer.entitlement_amount_female_q2, - entitlement_amount_female_q1=beneficiary_list_summary_farmer.entitlement_amount_female_q1, - ), - ) - - return summary_farmer_payload - - def get_summary_sync( - self, beneficiary_list_id: str, bg_task_session: Session - ) -> BeneficiaryListSummaryFarmerPayload: - beneficiary_list_summary_farmer = ( - bg_task_session.query(BeneficiaryListSummaryFarmerModel) - .filter_by(beneficiary_list_id=beneficiary_list_id) - .first() - ) - - summary_farmer_payload = BeneficiaryListSummaryFarmerPayload( - beneficiary_list_summary=BeneficiaryListSummary( - id=beneficiary_list_summary_farmer.id, - program_id=beneficiary_list_summary_farmer.program_id, - program_mnemonic=beneficiary_list_summary_farmer.program_mnemonic, - target_registry=beneficiary_list_summary_farmer.target_registry, - beneficiary_list_id=beneficiary_list_summary_farmer.beneficiary_list_id, - number_of_registrants=beneficiary_list_summary_farmer.number_of_registrants, - date_created=beneficiary_list_summary_farmer.date_created, - total_disbursement_quantity=beneficiary_list_summary_farmer.total_disbursement_quantity, - average_entitlement_per_registrant=beneficiary_list_summary_farmer.average_entitlement_per_person, - ), - registry_summary=BeneficiaryListSummaryFarmer( - estimated_age_mean=f"{beneficiary_list_summary_farmer.estimated_age_mean} {beneficiary_list_summary_farmer.estimated_age_units}" - if beneficiary_list_summary_farmer.estimated_age_mean is not None - else None, - estimated_age_q3=f"{beneficiary_list_summary_farmer.estimated_age_q3} {beneficiary_list_summary_farmer.estimated_age_units}" - if beneficiary_list_summary_farmer.estimated_age_q3 is not None - else None, - estimated_age_q2=f"{beneficiary_list_summary_farmer.estimated_age_q2} {beneficiary_list_summary_farmer.estimated_age_units}" - if beneficiary_list_summary_farmer.estimated_age_q2 is not None - else None, - estimated_age_q1=f"{beneficiary_list_summary_farmer.estimated_age_q1} {beneficiary_list_summary_farmer.estimated_age_units}" - if beneficiary_list_summary_farmer.estimated_age_q1 is not None - else None, - average_entitlement_female=beneficiary_list_summary_farmer.average_entitlement_female, - average_entitlement_male=beneficiary_list_summary_farmer.average_entitlement_male, - entitlement_amount_q3=beneficiary_list_summary_farmer.entitlement_amount_q3, - entitlement_amount_q2=beneficiary_list_summary_farmer.entitlement_amount_q2, - entitlement_amount_q1=beneficiary_list_summary_farmer.entitlement_amount_q1, - entitlement_amount_male_q3=beneficiary_list_summary_farmer.entitlement_amount_male_q3, - entitlement_amount_male_q2=beneficiary_list_summary_farmer.entitlement_amount_male_q2, - entitlement_amount_male_q1=beneficiary_list_summary_farmer.entitlement_amount_male_q1, - entitlement_amount_female_q3=beneficiary_list_summary_farmer.entitlement_amount_female_q3, - entitlement_amount_female_q2=beneficiary_list_summary_farmer.entitlement_amount_female_q2, - entitlement_amount_female_q1=beneficiary_list_summary_farmer.entitlement_amount_female_q1, - ), - ) - return summary_farmer_payload - - # ============================== - # Beneficiary Search API Methods - # ============================== - async def search_beneficiaries( - self, - bg_task_session: AsyncSession, - sr_session: AsyncSession, - beneficiary_list_id: str, - target_registry: str, - search_query, - page=1, - page_size=10, - order_by="id asc", - ) -> BeneficiarySearchResponsePayload: - registrant_details = await bg_task_session.execute( - select(BeneficiaryListDetails.registrant_details).where( - BeneficiaryListDetails.beneficiary_list_id == beneficiary_list_id - ) - ) - registrant_details = registrant_details.scalars().all() - registrant_ids = [] - for registrant_detail in registrant_details: - for registrant in registrant_detail: - registrant_ids.append(registrant["registrant_id"]) - - ( - farmer_search_query, - farmer_search_params, - ) = self.construct_beneficiary_search_sql_query( - registrant_ids, - target_registry, - search_query, - order_by, - page_size, - page, - ) - farmer_search_results = ( - (await sr_session.execute(farmer_search_query, farmer_search_params)) - .mappings() - .all() - ) - - total_beneficiary_count: int = await self._get_total_beneficiary_count( - sr_session, beneficiary_list_id, registrant_ids, search_query - ) - beneficiaries = [] - if farmer_search_results: - beneficiaries = [ - G2PFarmerRegistryPayload( - internal_record_id=farmer["internal_record_id"], - functional_record_id=farmer["functional_record_id"], - first_name=farmer["first_name"], - last_name=farmer["last_name"], - gender=farmer["gender"], - estimated_age=farmer["estimated_age"], - disabled=farmer["disabled"], - source_of_income=farmer["source_of_income"], - education_level=farmer["education_level"], - country_code=farmer["country_code"], - ) - for farmer in farmer_search_results - ] - - response_payload = BeneficiarySearchResponsePayload( - total_beneficiary_count=total_beneficiary_count, - page=page, - page_size=page_size, - beneficiaries=beneficiaries, - ) - - return response_payload - - @cache(expire=120, key_builder=beneficiary_count_key_builder) - async def _get_total_beneficiary_count( - self, - sr_session: AsyncSession, - beneficiary_list_id: str, - registrant_ids: List[str], - search_query: str, - ) -> int: - ( - beneficiary_count_query, - beneficiary_count_params, - ) = self.construct_beneficiary_search_count_sql_query( - registrant_ids, "farmer", search_query - ) - total_beneficiary_count = ( - await sr_session.execute(beneficiary_count_query, beneficiary_count_params) - ).scalar_one() - - return total_beneficiary_count - - # ================================= - # Eligibility Celery Worker Methods - # ================================= - def compute_eligibility_statistics( - self, - beneficiary_list_details: List[BeneficiaryListDetails], - base_summary, - sr_session: Session, - bg_task_session: Session, - ): - farmer_summary = BeneficiaryListSummaryFarmerModel( - program_id=base_summary.program_id, - program_mnemonic=base_summary.program_mnemonic, - target_registry=base_summary.target_registry, - beneficiary_list_id=base_summary.beneficiary_list_id, - number_of_registrants=base_summary.number_of_registrants, - date_created=base_summary.date_created, - ) - - estimated_ages = [] - - for beneficiary_list_detail in beneficiary_list_details: - registrant_ids = [] - for registrant_detail in beneficiary_list_detail.registrant_details: - registrant_detail = RegistrantDetails(**registrant_detail) - registrant_ids.append(registrant_detail.registrant_id) - - registrants = self.get_registrants_by_ids(registrant_ids, sr_session) - for farmer in registrants: - if farmer.estimated_age is not None: - estimated_ages.append(farmer.estimated_age) - - # Estimated Age Summary - if estimated_ages: - estimated_ages_array = np.array(estimated_ages) - farmer_summary.estimated_age_mean = round( - float(np.mean(estimated_ages_array)), 2 - ) - farmer_summary.estimated_age_q1 = round( - float(np.percentile(estimated_ages_array, 25, method="midpoint")), 2 - ) - farmer_summary.estimated_age_q2 = round( - float(np.percentile(estimated_ages_array, 50, method="midpoint")), 2 - ) - farmer_summary.estimated_age_q3 = round( - float(np.percentile(estimated_ages_array, 75, method="midpoint")), 2 - ) - - bg_task_session.add(farmer_summary) - - def get_registrants_by_ids( - self, registrant_ids, sr_session - ) -> List[G2PFarmerRegistry]: - farmers = sr_session.query(G2PFarmerRegistry).filter( - G2PFarmerRegistry.internal_record_id.in_(registrant_ids) - ) - - return list(farmers.yield_per(500)) - - # ================================= - # Entitlement Celery Worker Methods - # ================================= - def get_is_registant_entitled( - self, registrant_id: str, sql_query: str, sr_session: Session - ) -> bool: - sql_query_with_registrant_id = ( - self.construct_get_is_registrant_entitled_sql_query( - registrant_id, "farmer", sql_query - ) - ) - result = sr_session.execute(sql_query_with_registrant_id).fetchone() - return result is not None - - def get_entitlement_multiplier( - self, multiplier: str, registrant_id: str, sr_session: Session - ) -> int: - if not multiplier or multiplier == "none": - return 1 - - sql_query = self.construct_multiplier_sql_query( - multiplier, target_registry="farmer" - ) - params = {"registrant_id": registrant_id} - result = sr_session.execute(sql_query, params).fetchone() - multiplier_value: int = ( - int(result[0]) if result and result[0] is not None else 1 - ) - - return multiplier_value - - def compute_entitlement_statistics( - self, beneficiary_list_id: str, bg_task_session: Session, sr_session: Session - ): - beneficiary_list_details = ( - bg_task_session.query(BeneficiaryListDetails) - .filter_by(beneficiary_list_id=beneficiary_list_id) - .all() - ) - - registrant_map_from_registry: dict[str, G2PFarmerRegistry] = {} - - for beneficiary_list_detail in beneficiary_list_details: - registrant_ids = [] - for registrant_detail in beneficiary_list_detail.registrant_details: - registrant_detail = RegistrantDetails(**registrant_detail) - registrant_ids.append(registrant_detail.registrant_id) - - # Fething registrants in batches - registrants_list: List[G2PFarmerRegistry] = self.get_registrants_by_ids( - registrant_ids, sr_session - ) - - for registrant in registrants_list: - registrant_map_from_registry[ - str(registrant.internal_record_id) - ] = registrant - - # Collect entitlements per benefit_code_id - entitlements: dict[int, list[float]] = {} - entitlements_male: dict[int, list[float]] = {} - entitlements_female: dict[int, list[float]] = {} - - for beneficiary_list_detail in beneficiary_list_details: - for registrant_detail in beneficiary_list_detail.registrant_details: - registrant_detail = RegistrantDetails(**registrant_detail) - registrant = registrant_map_from_registry.get( - str(registrant_detail.registrant_id) - ) - gender = (registrant.gender or "").lower() if registrant else None - - for benefit_code_id, value in registrant_detail.entitlement.items(): - # All entitlements - entitlements.setdefault(benefit_code_id, []).append(value) - # By gender (skip non-binary / unknown genders) - if gender == Gender.MALE.value: - entitlements_male.setdefault(benefit_code_id, []).append(value) - elif gender == Gender.FEMALE.value: - entitlements_female.setdefault(benefit_code_id, []).append( - value - ) - - # Compute all summary stats per benefit_code_id - entitlement_stats = self.compute_stats_dict(entitlements) - entitlement_male_stats = self.compute_stats_dict(entitlements_male) - entitlement_female_stats = self.compute_stats_dict(entitlements_female) - - bg_task_session.execute( - update(BeneficiaryListSummaryFarmerModel) - .where( - BeneficiaryListSummaryFarmerModel.beneficiary_list_id - == beneficiary_list_id - ) - .values( - total_disbursement_quantity=dict(entitlement_stats["total"]), - average_entitlement_per_person=dict(entitlement_stats["average"]), - entitlement_amount_q1=dict(entitlement_stats["q1"]), - entitlement_amount_q2=dict(entitlement_stats["q2"]), - entitlement_amount_q3=dict(entitlement_stats["q3"]), - average_entitlement_male=dict(entitlement_male_stats["average"]), - entitlement_amount_male_q1=dict(entitlement_male_stats["q1"]), - entitlement_amount_male_q2=dict(entitlement_male_stats["q2"]), - entitlement_amount_male_q3=dict(entitlement_male_stats["q3"]), - average_entitlement_female=dict(entitlement_female_stats["average"]), - entitlement_amount_female_q1=dict(entitlement_female_stats["q1"]), - entitlement_amount_female_q2=dict(entitlement_female_stats["q2"]), - entitlement_amount_female_q3=dict(entitlement_female_stats["q3"]), - ) - ) - - def compute_stats_dict(self, entitlements_dict: dict[int, list[float]]) -> dict: - # Returns a dict of stats per benefit_code_id for each stat - stats = { - "average": {}, - "q1": {}, - "q2": {}, - "q3": {}, - "total": {}, - } - for benefit_code_id, values in entitlements_dict.items(): - if not values: - stats["average"][benefit_code_id] = 0.0 - stats["q1"][benefit_code_id] = 0.0 - stats["q2"][benefit_code_id] = 0.0 - stats["q3"][benefit_code_id] = 0.0 - stats["total"][benefit_code_id] = 0.0 - else: - arr = np.array(values) - stats["average"][benefit_code_id] = round(float(np.mean(arr)), 2) - stats["q1"][benefit_code_id] = round( - float(np.percentile(arr, 25, method="midpoint")), 2 - ) - stats["q2"][benefit_code_id] = round( - float(np.percentile(arr, 50, method="midpoint")), 2 - ) - stats["q3"][benefit_code_id] = round( - float(np.percentile(arr, 75, method="midpoint")), 2 - ) - stats["total"][benefit_code_id] = float(np.sum(arr)) - return stats diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/factory/__init__.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/factory/__init__.py deleted file mode 100644 index c234721..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/factory/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .registry_factory import RegistryFactory diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/factory/registry_factory.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/factory/registry_factory.py deleted file mode 100644 index 1926b1e..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/factory/registry_factory.py +++ /dev/null @@ -1,23 +0,0 @@ -from openg2p_bg_task_models.errors import BGTaskErrorCodes, BGTaskException - -from ..computations import ( - RegisterHousehold, - RegistryFarmer, -) -from ..interface import RegistryInterface -from ..models import G2PRegistryType - - -class RegistryFactory: - """Get the appropriate summary computation class based on the registrant type""" - - @staticmethod - def get_registry_class( - target_registry, - ) -> RegistryInterface: - if target_registry == G2PRegistryType.FARMER.value: - return RegistryFarmer() - elif target_registry == G2PRegistryType.HOUSEHOLDS.value: - return RegisterHousehold() - else: - raise BGTaskException(code=BGTaskErrorCodes.INVALID_REQUEST) diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/interface/__init__.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/interface/__init__.py deleted file mode 100644 index 505cb28..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/interface/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .registry_interface import RegistryInterface diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/interface/registry_interface.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/interface/registry_interface.py deleted file mode 100644 index 5949d09..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/interface/registry_interface.py +++ /dev/null @@ -1,240 +0,0 @@ -from abc import ABC, abstractmethod -from typing import Any, Dict, List, Tuple - -from openg2p_bg_task_models.models import BeneficiaryListDetails -from openg2p_bg_task_models.schemas import ( - BeneficiarySearchResponsePayload, - Disbursement, -) -from openg2p_pbms_models.models import G2PRegistry -from sqlalchemy import TextClause, text -from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy.orm import Session - -from ..schema import BeneficiaryListSummaryPayload - - -class RegistryInterface(ABC): - """ - Base class for Registry Interface - Defines methods for interacting with the registry classes - """ - - # ================ - # Summary methods - # ================ - @abstractmethod - async def get_summary( - self, - beneficiary_list_id: str, - bg_task_session: AsyncSession, - formated: bool = False, - ) -> BeneficiaryListSummaryPayload: - """ - Abstract method to get async summary statistics for a given beneficiary_list_id. - """ - raise NotImplementedError("Subclasses must implement get_summary()") - - @abstractmethod - def get_summary_sync( - self, beneficiary_list_id: str, bg_task_session: Session - ) -> BeneficiaryListSummaryPayload: - """ - Abstract method to get synchronous summary statistics for a given beneficiary_list_id. - """ - raise NotImplementedError("Subclasses must implement get_summary_sync()") - - @abstractmethod - def compute_eligibility_statistics( - self, - beneficiary_list_details: List[BeneficiaryListDetails], - base_summary, - sr_session: Session, - bg_task_session: Session, - ): - """ - Abstract method to compute eligibility summary statistics and update the summary table. - """ - raise NotImplementedError( - "Subclasses must implement compute_eligibility_statistics()" - ) - - @abstractmethod - def compute_entitlement_statistics( - self, beneficiary_list_id: str, bg_task_session: Session, sr_session: Session - ): - """ - Abstract method to compute entitlement statistics and update relevant summary fields. - """ - raise NotImplementedError( - "Subclasses must implement compute_entitlement_statistics()" - ) - - # ================= - # Registry methods - # ================= - @abstractmethod - def get_registrants_by_ids( - self, registrant_ids: List, sr_session: Session - ) -> List[G2PRegistry]: - """ - Abstract method to fetch registrants for given registrant_ids from the registry database. - """ - raise NotImplementedError("Subclasses must implement get_registrants_by_ids()") - - @abstractmethod - def get_is_registant_entitled( - self, registrant_id: str, sql_query: str, sr_session: Session - ) -> bool: - """ - Abstract method to check if a registrant is entitled based on custom SQL and session. - """ - raise NotImplementedError( - "Subclasses must implement get_is_registant_entitled()" - ) - - @abstractmethod - def get_entitlement_multiplier( - self, multiplier: str, registrant_id: str, sr_session: Session - ) -> int: - """ - Abstract method to get the multiplier value for entitlement calculation - for a single registrant_id by executing a SQL query. - """ - raise NotImplementedError( - "Subclasses must implement get_entitlement_multiplier()" - ) - - @abstractmethod - async def search_beneficiaries( - self, - bg_task_session: AsyncSession, - sr_session: AsyncSession, - beneficiary_list_id: str, - target_registry: str, - search_query, - page: int = 1, - page_size: int = 10, - order_by: str = "internal_record_id asc", - ) -> Tuple[BeneficiarySearchResponsePayload, int]: - """ - Abstract method to search beneficiaries for particular eligibility request id. - Returns a tuple of (response_payload, total_count) where total_count is the - total number of matching beneficiaries (used for pagination response). - """ - raise NotImplementedError("Subclasses must implement search_beneficiaries()") - - def get_bridge_disbursement_details( - self, - beneficiary_list_id: str, - registrant_ids: List[str], - bg_task_session: Session, - ) -> List[Disbursement]: - raise NotImplementedError( - "Subclasses must implement get_bridge_disbursement_details()" - ) - - # =============================== - # Registry SQL Query Constructors - # =============================== - def construct_multiplier_sql_query( - self, multiplier: str, target_registry: str - ) -> TextClause: - if not multiplier or multiplier == "none": - return None - - table_name = f"g2p_register_{target_registry}" - sql_query = text( - f""" - SELECT {multiplier} FROM {table_name} - WHERE internal_record_id = :registrant_id - """ - ) - return sql_query - - def construct_beneficiary_search_sql_query( - self, - registrant_ids: List[str], - target_registry: str, - where_clause: str, - order_by: str, - page_size: int, - page: int, - ) -> Tuple[TextClause, Dict[str, Any]]: - if not registrant_ids: - return None, {} - - # Replace curly quotes in the where clause - where_clause = where_clause.replace("“", '"').replace("”", '"') - where_clause = where_clause.replace("‘", "'").replace("’", "'") - - table_name = f"g2p_register_{target_registry}" - where_clause_sql = f" AND {where_clause}" if where_clause else "" - registrant_placeholders = ", ".join( - [f":registrant_id_{i}" for i in range(len(registrant_ids))] - ) - - sql_query = text( - f""" - SELECT * FROM {table_name} - WHERE internal_record_id IN ({registrant_placeholders}) {where_clause_sql} - ORDER BY {order_by} - OFFSET :offset - LIMIT :limit - """ - ) - - params = { - f"registrant_id_{i}": registrant_ids[i] for i in range(len(registrant_ids)) - } - params.update({"offset": page_size * (page - 1), "limit": page_size}) - - return sql_query, params - - def construct_beneficiary_search_count_sql_query( - self, registrant_ids: List[str], target_registry: str, where_clause: str - ) -> Tuple[TextClause, Dict[str, Any]]: - if not registrant_ids: - return None, {} - - # Replace curly quotes in the where clause - where_clause = where_clause.replace("“", '"').replace("”", '"') - where_clause = where_clause.replace("‘", "'").replace("’", "'") - - table_name = f"g2p_register_{target_registry}" - where_clause_sql = f" AND {where_clause}" if where_clause else "" - registrant_placeholders = ", ".join( - [f":registrant_id_{i}" for i in range(len(registrant_ids))] - ) - - sql_query = text( - f""" - SELECT COUNT(*) FROM {table_name} - WHERE internal_record_id IN ({registrant_placeholders}) {where_clause_sql} - """ - ) - - params = { - f"registrant_id_{i}": registrant_ids[i] for i in range(len(registrant_ids)) - } - - return sql_query, params - - def construct_get_is_registrant_entitled_sql_query( - self, registrant_id: str, target_registry: str, sql_query: str - ) -> TextClause: - sql_query = sql_query.strip() - - if not registrant_id: - raise ValueError("registrant_id cannot be None or zero") - if not sql_query.upper().startswith("SELECT"): - raise ValueError("Invalid SQL query: Must be a valid SELECT statement") - - if "WHERE" in sql_query.upper(): - sql_query += f" AND g2p_register_{target_registry}.internal_record_id = :registrant_id" - else: - sql_query += f" WHERE g2p_register_{target_registry}.internal_record_id = :registrant_id" - - params = {"registrant_id": registrant_id} - - return text(sql_query).params(**params) diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/migrate.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/migrate.py deleted file mode 100644 index ceded1f..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/migrate.py +++ /dev/null @@ -1,11 +0,0 @@ -from .models import ( - BeneficiaryListSummaryFarmer, - BeneficiaryListSummaryHousehold, -) - - -def get_models(): - return [ - BeneficiaryListSummaryFarmer, - BeneficiaryListSummaryHousehold, - ] diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/__init__.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/__init__.py deleted file mode 100644 index ff0f650..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -from .beneficiary_list_summary_farmer import BeneficiaryListSummaryFarmer -from .beneficiary_list_summary_household import BeneficiaryListSummaryHousehold -from .register_household import G2PRegisterHousehold -from .registry_farmer import G2PFarmerRegistry -from .registry_type import G2PRegistryType diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/beneficiary_list_summary_farmer.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/beneficiary_list_summary_farmer.py deleted file mode 100644 index 2977c71..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/beneficiary_list_summary_farmer.py +++ /dev/null @@ -1,26 +0,0 @@ -from openg2p_bg_task_models.models import BeneficiaryListSummary -from sqlalchemy import JSON, Float, String -from sqlalchemy.orm import mapped_column - - -class BeneficiaryListSummaryFarmer(BeneficiaryListSummary): - __tablename__ = "beneficiary_list_summary_farmer" - - estimated_age_q1 = mapped_column(Float, nullable=True, default=0) - estimated_age_q2 = mapped_column(Float, nullable=True, default=0) - estimated_age_q3 = mapped_column(Float, nullable=True, default=0) - estimated_age_mean = mapped_column(Float, nullable=True, default=0) - estimated_age_units = mapped_column(String, nullable=False, default="years") - - average_entitlement_female = mapped_column(JSON, nullable=True) - average_entitlement_male = mapped_column(JSON, nullable=True) - entitlement_amount_male_q1 = mapped_column(JSON, nullable=True) - entitlement_amount_male_q2 = mapped_column(JSON, nullable=True) - entitlement_amount_male_q3 = mapped_column(JSON, nullable=True) - entitlement_amount_female_q1 = mapped_column(JSON, nullable=True) - entitlement_amount_female_q2 = mapped_column(JSON, nullable=True) - entitlement_amount_female_q3 = mapped_column(JSON, nullable=True) - entitlement_amount_q1 = mapped_column(JSON, nullable=True) - entitlement_amount_q2 = mapped_column(JSON, nullable=True) - entitlement_amount_q3 = mapped_column(JSON, nullable=True) - entitlement_units = mapped_column(JSON, nullable=True) diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/beneficiary_list_summary_household.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/beneficiary_list_summary_household.py deleted file mode 100644 index 24c62f5..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/beneficiary_list_summary_household.py +++ /dev/null @@ -1,38 +0,0 @@ -from openg2p_bg_task_models.models import BeneficiaryListSummary -from sqlalchemy import JSON, Float, String -from sqlalchemy.orm import mapped_column - - -class BeneficiaryListSummaryHousehold(BeneficiaryListSummary): - __tablename__ = "beneficiary_list_summary_household" - - size_children_u5_q1 = mapped_column(Float, nullable=True, default=0) - size_children_u5_q2 = mapped_column(Float, nullable=True, default=0) - size_children_u5_q3 = mapped_column(Float, nullable=True, default=0) - size_children_u5_mean = mapped_column(Float, nullable=True, default=0) - size_children_u5_units = mapped_column(String, nullable=False, default="persons") - - size_elderly_q1 = mapped_column(Float, nullable=True, default=0) - size_elderly_q2 = mapped_column(Float, nullable=True, default=0) - size_elderly_q3 = mapped_column(Float, nullable=True, default=0) - size_elderly_mean = mapped_column(Float, nullable=True, default=0) - size_elderly_units = mapped_column(String, nullable=False, default="persons") - - rooms_count_q1 = mapped_column(Float, nullable=True, default=0) - rooms_count_q2 = mapped_column(Float, nullable=True, default=0) - rooms_count_q3 = mapped_column(Float, nullable=True, default=0) - rooms_count_mean = mapped_column(Float, nullable=True, default=0) - rooms_count_units = mapped_column(String, nullable=False, default="rooms") - - overcrowding_indicator_q1 = mapped_column(Float, nullable=True, default=0) - overcrowding_indicator_q2 = mapped_column(Float, nullable=True, default=0) - overcrowding_indicator_q3 = mapped_column(Float, nullable=True, default=0) - overcrowding_indicator_mean = mapped_column(Float, nullable=True, default=0) - overcrowding_indicator_units = mapped_column( - String, nullable=False, default="ratio" - ) - - entitlement_amount_q1 = mapped_column(JSON, nullable=True) - entitlement_amount_q2 = mapped_column(JSON, nullable=True) - entitlement_amount_q3 = mapped_column(JSON, nullable=True) - entitlement_units = mapped_column(JSON, nullable=True) diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/register_household.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/register_household.py deleted file mode 100644 index 1358358..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/register_household.py +++ /dev/null @@ -1,64 +0,0 @@ -from openg2p_pbms_models.models import G2PRegistry -from sqlalchemy import JSON, Boolean, DateTime, Integer, Numeric, String -from sqlalchemy.orm import Mapped, mapped_column - - -class G2PRegisterHousehold(G2PRegistry): - __tablename__ = "g2p_register_households" - - # G2PRegister identity fields - functional_record_id: Mapped[str] = mapped_column(String, nullable=True) - link_internal_record_id: Mapped[str] = mapped_column(String, nullable=True) - link_foundational_id: Mapped[str] = mapped_column(String, nullable=True) - record_name: Mapped[str] = mapped_column(String, nullable=True) - record_status: Mapped[str] = mapped_column(String, nullable=True) - record_status_reason: Mapped[str] = mapped_column(String, nullable=True) - - # Geo - latitude: Mapped[str] = mapped_column(String, nullable=True) - longitude: Mapped[str] = mapped_column(String, nullable=True) - altitude: Mapped[str] = mapped_column(String, nullable=True) - plus_code: Mapped[str] = mapped_column(String, nullable=True) - address_line_1: Mapped[str] = mapped_column(String, nullable=True) - address_line_2: Mapped[str] = mapped_column(String, nullable=True) - postal_code: Mapped[str] = mapped_column(String, nullable=True) - country_code: Mapped[str] = mapped_column(String, nullable=True) - geo_lowest_level_value_id: Mapped[str] = mapped_column(String, nullable=True) - geo_code_hierarchy_json: Mapped[dict] = mapped_column(JSON, nullable=True) - - # Household head - household_head_internal_record_id: Mapped[str] = mapped_column( - String, nullable=True - ) - household_head_name: Mapped[str] = mapped_column(String, nullable=True) - headship_type: Mapped[str] = mapped_column(String, nullable=True) - - # Composition - size_total: Mapped[int] = mapped_column(Integer, nullable=True) - size_adults: Mapped[int] = mapped_column(Integer, nullable=True) - size_children_u5: Mapped[int] = mapped_column(Integer, nullable=True) - size_school_age: Mapped[int] = mapped_column(Integer, nullable=True) - size_elderly: Mapped[int] = mapped_column(Integer, nullable=True) - number_of_female_members: Mapped[int] = mapped_column(Integer, nullable=True) - number_of_male_members: Mapped[int] = mapped_column(Integer, nullable=True) - elderly_member_present: Mapped[bool] = mapped_column(Boolean, nullable=True) - - # Dwelling - dwelling_type: Mapped[str] = mapped_column(String, nullable=True) - roof_material: Mapped[str] = mapped_column(String, nullable=True) - wall_material: Mapped[str] = mapped_column(String, nullable=True) - floor_material: Mapped[str] = mapped_column(String, nullable=True) - tenure_status: Mapped[str] = mapped_column(String, nullable=True) - rooms_count: Mapped[int] = mapped_column(Integer, nullable=True) - overcrowding_indicator: Mapped[float] = mapped_column(Numeric, nullable=True) - - # Utilities - water_source_type: Mapped[str] = mapped_column(String, nullable=True) - water_distance_minutes: Mapped[int] = mapped_column(Integer, nullable=True) - sanitation_type: Mapped[str] = mapped_column(String, nullable=True) - lighting_source: Mapped[str] = mapped_column(String, nullable=True) - cooking_fuel_type: Mapped[str] = mapped_column(String, nullable=True) - mobile_phone_type: Mapped[str] = mapped_column(String, nullable=True) - - husband_dead: Mapped[bool] = mapped_column(Boolean, nullable=True) - husband_death_date: Mapped[DateTime] = mapped_column(DateTime, nullable=True) diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/registry_farmer.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/registry_farmer.py deleted file mode 100644 index 26fd592..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/registry_farmer.py +++ /dev/null @@ -1,57 +0,0 @@ -from openg2p_pbms_models.models import G2PRegistry -from sqlalchemy import JSON, Boolean, Date, Integer, String -from sqlalchemy.orm import Mapped, mapped_column - - -class G2PFarmerRegistry(G2PRegistry): - __tablename__ = "g2p_register_farmer" - - # G2PRegister identity fields - functional_record_id: Mapped[str] = mapped_column(String, nullable=True) - link_internal_record_id: Mapped[str] = mapped_column(String, nullable=True) - link_foundational_id: Mapped[str] = mapped_column(String, nullable=True) - record_name: Mapped[str] = mapped_column(String, nullable=True) - record_status: Mapped[str] = mapped_column(String, nullable=True) - record_status_reason: Mapped[str] = mapped_column(String, nullable=True) - - # Person - foundational_id: Mapped[str] = mapped_column(String, nullable=True) - first_name: Mapped[str] = mapped_column(String, nullable=True) - middle_name: Mapped[str] = mapped_column(String, nullable=True) - last_name: Mapped[str] = mapped_column(String, nullable=True) - given_name: Mapped[str] = mapped_column(String, nullable=True) - prefix: Mapped[str] = mapped_column(String, nullable=True) - suffix: Mapped[str] = mapped_column(String, nullable=True) - gender: Mapped[str] = mapped_column(String, nullable=True) - birth_date: Mapped[Date] = mapped_column(Date, nullable=True) - phone_numbers: Mapped[list] = mapped_column(JSON, nullable=True) - emails: Mapped[list] = mapped_column(JSON, nullable=True) - marital_status: Mapped[str] = mapped_column(String, nullable=True) - occupation: Mapped[str] = mapped_column(String, nullable=True) - income_level: Mapped[str] = mapped_column(String, nullable=True) - language_code: Mapped[str] = mapped_column(String, nullable=True) - registration_date: Mapped[Date] = mapped_column(Date, nullable=True) - - # Geo - latitude: Mapped[str] = mapped_column(String, nullable=True) - longitude: Mapped[str] = mapped_column(String, nullable=True) - altitude: Mapped[str] = mapped_column(String, nullable=True) - plus_code: Mapped[str] = mapped_column(String, nullable=True) - address_line_1: Mapped[str] = mapped_column(String, nullable=True) - address_line_2: Mapped[str] = mapped_column(String, nullable=True) - postal_code: Mapped[str] = mapped_column(String, nullable=True) - country_code: Mapped[str] = mapped_column(String, nullable=True) - geo_lowest_level_value_id: Mapped[str] = mapped_column(String, nullable=True) - geo_code_hierarchy_json: Mapped[dict] = mapped_column(JSON, nullable=True) - - # Farmer-specific - estimated_age: Mapped[int] = mapped_column(Integer, nullable=True) - has_personal_phone: Mapped[bool] = mapped_column(Boolean, nullable=True) - disabled: Mapped[bool] = mapped_column(Boolean, nullable=True) - disability_type: Mapped[str] = mapped_column(String, nullable=True) - disability_severity: Mapped[str] = mapped_column(String, nullable=True) - source_of_income: Mapped[str] = mapped_column(String, nullable=True) - source_of_income_other: Mapped[str] = mapped_column(String, nullable=True) - language_spoken: Mapped[str] = mapped_column(String, nullable=True) - education_level: Mapped[str] = mapped_column(String, nullable=True) - national_id_masked: Mapped[str] = mapped_column(String, nullable=True) diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/registry_type.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/registry_type.py deleted file mode 100644 index 43f63cb..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/models/registry_type.py +++ /dev/null @@ -1,7 +0,0 @@ -from enum import Enum - - -class G2PRegistryType(Enum): - FARMER = "farmer" - HOUSEHOLDS = "households" - OTHER = "other" diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/__init__.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/__init__.py deleted file mode 100644 index 97161f3..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -from .beneficiary_list_summary import ( - BeneficiaryListSummary, - BeneficiaryListSummaryPayload, -) -from .beneficiary_list_summary_farmer import ( - BeneficiaryListSummaryFarmer, - BeneficiaryListSummaryFarmerPayload, -) -from .beneficiary_list_summary_household import ( - BeneficiaryListSummaryHousehold, - BeneficiaryListSummaryHouseholdPayload, -) -from .register_household import G2PRegisterHouseholdPayload -from .registry import G2PRegistryPayload -from .registry_farmer import G2PFarmerRegistryPayload diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/beneficiary_list_summary.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/beneficiary_list_summary.py deleted file mode 100644 index b097d93..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/beneficiary_list_summary.py +++ /dev/null @@ -1,21 +0,0 @@ -from datetime import datetime -from typing import Any, Optional - -from pydantic import BaseModel - - -class BeneficiaryListSummary(BaseModel): - id: str - program_id: int - program_mnemonic: str - target_registry: str - beneficiary_list_id: str - number_of_registrants: int - date_created: Optional[datetime] - total_disbursement_quantity: Optional[dict] = None - average_entitlement_per_registrant: Optional[dict] = None - - -class BeneficiaryListSummaryPayload(BaseModel): - beneficiary_list_summary: BeneficiaryListSummary - registry_summary: Optional[Any] = None diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/beneficiary_list_summary_farmer.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/beneficiary_list_summary_farmer.py deleted file mode 100644 index 595b77e..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/beneficiary_list_summary_farmer.py +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel - -from .beneficiary_list_summary import BeneficiaryListSummaryPayload - - -class BeneficiaryListSummaryFarmer(BaseModel): - estimated_age_mean: Optional[str] = None - estimated_age_q3: Optional[str] = None - estimated_age_q2: Optional[str] = None - estimated_age_q1: Optional[str] = None - average_entitlement_female: Optional[dict] = None - average_entitlement_male: Optional[dict] = None - entitlement_amount_q3: Optional[dict] = None - entitlement_amount_q2: Optional[dict] = None - entitlement_amount_q1: Optional[dict] = None - entitlement_amount_male_q3: Optional[dict] = None - entitlement_amount_male_q2: Optional[dict] = None - entitlement_amount_male_q1: Optional[dict] = None - entitlement_amount_female_q3: Optional[dict] = None - entitlement_amount_female_q2: Optional[dict] = None - entitlement_amount_female_q1: Optional[dict] = None - - -class BeneficiaryListSummaryFarmerPayload(BeneficiaryListSummaryPayload): - registry_summary: BeneficiaryListSummaryFarmer diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/beneficiary_list_summary_household.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/beneficiary_list_summary_household.py deleted file mode 100644 index 2ee35ad..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/beneficiary_list_summary_household.py +++ /dev/null @@ -1,35 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel - -from .beneficiary_list_summary import BeneficiaryListSummaryPayload - - -class BeneficiaryListSummaryHousehold(BaseModel): - size_children_u5_mean: Optional[str] = None - size_children_u5_q1: Optional[str] = None - size_children_u5_q2: Optional[str] = None - size_children_u5_q3: Optional[str] = None - - size_elderly_mean: Optional[str] = None - size_elderly_q1: Optional[str] = None - size_elderly_q2: Optional[str] = None - size_elderly_q3: Optional[str] = None - - rooms_count_mean: Optional[str] = None - rooms_count_q1: Optional[str] = None - rooms_count_q2: Optional[str] = None - rooms_count_q3: Optional[str] = None - - overcrowding_indicator_mean: Optional[str] = None - overcrowding_indicator_q1: Optional[str] = None - overcrowding_indicator_q2: Optional[str] = None - overcrowding_indicator_q3: Optional[str] = None - - entitlement_amount_q1: Optional[dict] = None - entitlement_amount_q2: Optional[dict] = None - entitlement_amount_q3: Optional[dict] = None - - -class BeneficiaryListSummaryHouseholdPayload(BeneficiaryListSummaryPayload): - registry_summary: BeneficiaryListSummaryHousehold diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/register_household.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/register_household.py deleted file mode 100644 index febe5cd..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/register_household.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Optional - -from .registry import G2PRegistryPayload - - -class G2PRegisterHouseholdPayload(G2PRegistryPayload): - functional_record_id: Optional[str] = None - household_head_name: Optional[str] = None - headship_type: Optional[str] = None - size_total: Optional[int] = None - size_children_u5: Optional[int] = None - size_elderly: Optional[int] = None - number_of_female_members: Optional[int] = None - number_of_male_members: Optional[int] = None - dwelling_type: Optional[str] = None - tenure_status: Optional[str] = None - rooms_count: Optional[int] = None - overcrowding_indicator: Optional[float] = None - water_source_type: Optional[str] = None - sanitation_type: Optional[str] = None - lighting_source: Optional[str] = None - cooking_fuel_type: Optional[str] = None - address_line_1: Optional[str] = None - address_line_2: Optional[str] = None - postal_code: Optional[str] = None - country_code: Optional[str] = None diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/registry.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/registry.py deleted file mode 100644 index e66e1e4..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/registry.py +++ /dev/null @@ -1,5 +0,0 @@ -from pydantic import BaseModel - - -class G2PRegistryPayload(BaseModel): - internal_record_id: str diff --git a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/registry_farmer.py b/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/registry_farmer.py deleted file mode 100644 index 05a531f..0000000 --- a/extensions/openg2p-bg-task-registry-adapters/src/openg2p_bg_task_registry_adapters/schema/registry_farmer.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Optional - -from .registry import G2PRegistryPayload - - -class G2PFarmerRegistryPayload(G2PRegistryPayload): - functional_record_id: Optional[str] = None - first_name: Optional[str] = None - last_name: Optional[str] = None - gender: Optional[str] = None - estimated_age: Optional[int] = None - disabled: Optional[bool] = None - source_of_income: Optional[str] = None - education_level: Optional[str] = None - country_code: Optional[str] = None diff --git a/odoo/README.md b/odoo/README.md index 2d66779..688395e 100644 --- a/odoo/README.md +++ b/odoo/README.md @@ -1,3 +1,3 @@ # openg2p-pbms-odoo -Odoo modules for OpenG2P PBMS (core `g2p_pbms`, program access, registry extensions, and community addons). +Odoo modules for OpenG2P PBMS (core `g2p_pbms`, program access, and community addons). diff --git a/odoo/extensions/.gitignore b/odoo/extensions/.gitignore deleted file mode 100644 index b7faf40..0000000 --- a/odoo/extensions/.gitignore +++ /dev/null @@ -1,207 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[codz] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py.cover -.hypothesis/ -.pytest_cache/ -cover/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# UV -# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -#uv.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -#poetry.lock -#poetry.toml - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. -# https://pdm-project.org/en/latest/usage/project/#working-with-version-control -#pdm.lock -#pdm.toml -.pdm-python -.pdm-build/ - -# pixi -# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. -#pixi.lock -# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one -# in the .venv directory. It is recommended not to include this directory in version control. -.pixi - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - -# Environments -.env -.envrc -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ - -# Abstra -# Abstra is an AI-powered process automation framework. -# Ignore directories containing user credentials, local state, and settings. -# Learn more at https://abstra.io/docs -.abstra/ - -# Visual Studio Code -# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore -# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore -# and can be added to the global gitignore or merged into this file. However, if you prefer, -# you could uncomment the following to ignore the entire vscode folder -# .vscode/ - -# Ruff stuff: -.ruff_cache/ - -# PyPI configuration file -.pypirc - -# Cursor -# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to -# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data -# refer to https://docs.cursor.com/context/ignore-files -.cursorignore -.cursorindexingignore - -# Marimo -marimo/_static/ -marimo/_lsp/ -__marimo__/ diff --git a/odoo/extensions/LICENSE b/odoo/extensions/LICENSE deleted file mode 100644 index d0a1fa1..0000000 --- a/odoo/extensions/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at https://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/odoo/extensions/README.md b/odoo/extensions/README.md deleted file mode 100644 index 50f17ae..0000000 --- a/odoo/extensions/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# openg2p-pbms-odoo-extensions - -Registry model addons and theme extensions for OpenG2P PBMS Odoo. diff --git a/odoo/extensions/g2p_registry_addon/__init__.py b/odoo/extensions/g2p_registry_addon/__init__.py deleted file mode 100644 index a0fdc10..0000000 --- a/odoo/extensions/g2p_registry_addon/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# -*- coding: utf-8 -*- -from . import models diff --git a/odoo/extensions/g2p_registry_addon/__manifest__.py b/odoo/extensions/g2p_registry_addon/__manifest__.py deleted file mode 100644 index 25e8967..0000000 --- a/odoo/extensions/g2p_registry_addon/__manifest__.py +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "PBMS Registry Addon", - "version": "3.1.1", - "summary": "OpenG2P Registry Addon", - "description": "OpenG2P Registry Addon", - "category": "G2P", - "license": "LGPL-3", - "depends": ["base_setup", "web", "g2p_pbms"], - "data": [ - "security/ir.model.access.csv", - "views/eligibility/eligibility_rule_view.xml", - "views/entitlement/entitlement_rule_view.xml", - "views/priority/priority_rule_view.xml", - "views/registry/farmer_registry_view.xml", - "views/registry/household_registry_view.xml", - "views/bgtask/bgtask_view.xml", - "views/menu.xml", - ], - "assets": { - "web.assets_backend": [ - "/g2p_registry_addon/static/src/css/registry_styles.scss", - "/g2p_registry_addon/static/src/js/beneficiaries_widget.js", - "/g2p_registry_addon/static/src/xml/g2p_beneficiaries_info_tpl.xml", - ], - }, - "installable": True, - "application": True, - "auto_install": False, -} diff --git a/odoo/extensions/g2p_registry_addon/models/__init__.py b/odoo/extensions/g2p_registry_addon/models/__init__.py deleted file mode 100644 index f9b176a..0000000 --- a/odoo/extensions/g2p_registry_addon/models/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .registry import G2PRegistry -from .farmer_registry import G2PFarmerRegistry -from .household import G2PRegisterHousehold \ No newline at end of file diff --git a/odoo/extensions/g2p_registry_addon/models/farmer_registry.py b/odoo/extensions/g2p_registry_addon/models/farmer_registry.py deleted file mode 100644 index 7e28fe4..0000000 --- a/odoo/extensions/g2p_registry_addon/models/farmer_registry.py +++ /dev/null @@ -1,126 +0,0 @@ -from odoo import models, fields - -from .registry import G2PRegistry - - -class G2PFarmerRegistry(models.Model): - _name = "g2p.register.farmer" - _description = "Farmer Registry" - _inherit = "g2p.registry" - - # G2PRegister fields - functional_record_id = fields.Char(string="Functional Record ID", index=True) - link_internal_record_id = fields.Char(string="Link Internal Record ID", index=True) - link_foundational_id = fields.Char(string="Link Foundational ID", index=True) - record_name = fields.Char(string="Record Name") - record_image_storage_id = fields.Text(string="Record Image Storage ID") - created_by = fields.Char(string="Created By") - created_at = fields.Datetime(string="Created At") - last_approved_at = fields.Datetime(string="Last Approved At") - last_approved_by = fields.Char(string="Last Approved By") - search_text = fields.Text(string="Search Text") - record_status = fields.Selection( - selection=[ - ("active", "Active"), - ("inactive", "Inactive"), - ("archived", "Archived"), - ], - string="Record Status", - default="active", - ) - record_status_reason = fields.Char(string="Record Status Reason") - - # G2PPerson fields - foundational_id = fields.Char(string="Foundational ID", index=True) - first_name = fields.Char(string="First Name") - middle_name = fields.Char(string="Middle Name") - last_name = fields.Char(string="Last Name") - given_name = fields.Char(string="Given Name") - prefix = fields.Char(string="Prefix") - suffix = fields.Char(string="Suffix") - gender = fields.Selection( - selection=[ - ("MALE", "Male"), - ("FEMALE", "Female"), - ("OTHERS", "Others"), - ("UNKNOWN", "Unknown"), - ], - string="Gender", - ) - birth_date = fields.Date(string="Birth Date") - phone_numbers = fields.Json(string="Phone Numbers") - emails = fields.Json(string="Emails") - marital_status = fields.Selection( - selection=[ - ("SINGLE", "Single"), - ("MARRIED", "Married"), - ("DIVORCED", "Divorced"), - ("WIDOWED", "Widowed"), - ("SEPARATED", "Separated"), - ("UNKNOWN", "Unknown"), - ], - string="Marital Status", - ) - occupation = fields.Char(string="Occupation") - income_level = fields.Char(string="Income Level") - language_code = fields.Char(string="Language Code") - registration_date = fields.Date(string="Registration Date") - - # G2PGeo fields - latitude = fields.Char(string="Latitude") - longitude = fields.Char(string="Longitude") - altitude = fields.Char(string="Altitude") - plus_code = fields.Char(string="Plus Code", index=True) - address_line_1 = fields.Char(string="Address Line 1") - address_line_2 = fields.Char(string="Address Line 2") - postal_code = fields.Char(string="Postal Code", index=True) - country_code = fields.Char(string="Country Code", index=True) - geo_lowest_level_value_id = fields.Char(string="Geo Lowest Level Value ID", index=True) - geo_code_hierarchy_json = fields.Json(string="Geo Code Hierarchy") - - # G2PFarmer fields - estimated_age = fields.Integer(string="Estimated Age") - has_personal_phone = fields.Boolean(string="Has Personal Phone") - disabled = fields.Boolean(string="Disabled") - disability_type = fields.Selection( - selection=[ - ("VISION", "Vision"), - ("HEARING", "Hearing"), - ("MOBILITY", "Mobility"), - ("COGNITION", "Cognition"), - ("SELF_CARE", "Self Care"), - ("COMMUNICATION", "Communication"), - ], - string="Disability Type", - ) - disability_severity = fields.Selection( - selection=[ - ("NO_DIFFICULTY", "No Difficulty"), - ("SOME_DIFFICULTY", "Some Difficulty"), - ("A_LOT_OF_DIFFICULTY", "A Lot of Difficulty"), - ("CANNOT_DO_AT_ALL", "Cannot Do At All"), - ], - string="Disability Severity", - ) - source_of_income = fields.Selection( - selection=[ - ("CROP_PRODUCTION", "Crop Production"), - ("LIVESTOCK_PRODUCTION", "Livestock Production"), - ("GOVERNMENT_NGO_SUPPORT", "Government / NGO Support"), - ("OTHERS", "Others"), - ], - string="Source of Income", - ) - source_of_income_other = fields.Char(string="Source of Income (Other)") - language_spoken = fields.Char(string="Language Spoken") - education_level = fields.Selection( - selection=[ - ("ILLITERATE", "Illiterate"), - ("CAN_READ_AND_WRITE", "Can Read and Write"), - ("BASIC", "Basic"), - ("INTERMEDIARY", "Intermediary"), - ("HIGHER_EDUCATION", "Higher Education"), - ], - string="Education Level", - ) - national_id_masked = fields.Char(string="National ID (Masked)") diff --git a/odoo/extensions/g2p_registry_addon/models/household.py b/odoo/extensions/g2p_registry_addon/models/household.py deleted file mode 100644 index 0bdf50f..0000000 --- a/odoo/extensions/g2p_registry_addon/models/household.py +++ /dev/null @@ -1,184 +0,0 @@ -from odoo import models, fields - -from .registry import G2PRegistry - - -class G2PRegisterHousehold(models.Model): - _name = "g2p.register.households" - _description = "Register Household" - _inherit = "g2p.registry" - - # G2PRegister fields - functional_record_id = fields.Char(string="Functional Record ID", index=True) - link_internal_record_id = fields.Char(string="Link Internal Record ID", index=True) - link_foundational_id = fields.Char(string="Link Foundational ID", index=True) - record_name = fields.Char(string="Record Name") - record_image_storage_id = fields.Text(string="Record Image Storage ID") - created_by = fields.Char(string="Created By") - created_at = fields.Datetime(string="Created At") - last_approved_at = fields.Datetime(string="Last Approved At") - last_approved_by = fields.Char(string="Last Approved By") - search_text = fields.Text(string="Search Text") - record_status = fields.Selection( - selection=[ - ("active", "Active"), - ("inactive", "Inactive"), - ("archived", "Archived"), - ], - string="Record Status", - default="active", - ) - record_status_reason = fields.Char(string="Record Status Reason") - - # G2PGeo fields - latitude = fields.Char(string="Latitude") - longitude = fields.Char(string="Longitude") - altitude = fields.Char(string="Altitude") - plus_code = fields.Char(string="Plus Code", index=True) - address_line_1 = fields.Char(string="Address Line 1") - address_line_2 = fields.Char(string="Address Line 2") - postal_code = fields.Char(string="Postal Code", index=True) - country_code = fields.Char(string="Country Code", index=True) - geo_lowest_level_value_id = fields.Char(string="Geo Lowest Level Value ID", index=True) - geo_code_hierarchy_json = fields.Json(string="Geo Code Hierarchy") - - # Household head - household_head_internal_record_id = fields.Char( - string="Household Head Internal Record ID", index=True - ) - household_head_name = fields.Char(string="Household Head Name") - headship_type = fields.Selection( - selection=[ - ("MALE_HEADED", "Male Headed"), - ("FEMALE_HEADED", "Female Headed"), - ("CHILD_HEADED", "Child Headed"), - ("ELDERLY_HEADED", "Elderly Headed"), - ("DISABLED_HEADED", "Disabled Headed"), - ], - string="Headship Type", - ) - - # Household composition - size_total = fields.Integer(string="Total Size") - size_adults = fields.Integer(string="Adults") - size_children_u5 = fields.Integer(string="Children Under 5") - size_school_age = fields.Integer(string="School Age") - size_elderly = fields.Integer(string="Elderly") - number_of_female_members = fields.Integer(string="Number of Female Members") - number_of_male_members = fields.Integer(string="Number of Male Members") - elderly_member_present = fields.Boolean(string="Elderly Member Present") - - # Dwelling - dwelling_type = fields.Selection( - selection=[ - ("PERMANENT", "Permanent"), - ("SEMI_PERMANENT", "Semi-Permanent"), - ("TEMPORARY", "Temporary"), - ], - string="Dwelling Type", - ) - roof_material = fields.Selection( - selection=[ - ("THATCH", "Thatch"), - ("CORRUGATED_IRON", "Corrugated Iron"), - ("CONCRETE", "Concrete"), - ("TILE", "Tile"), - ("PLASTIC_SHEET", "Plastic Sheet"), - ("OTHER", "Other"), - ], - string="Roof Material", - ) - wall_material = fields.Selection( - selection=[ - ("MUD", "Mud"), - ("WOOD", "Wood"), - ("BAMBOO", "Bamboo"), - ("STONE", "Stone"), - ("BRICK", "Brick"), - ("CONCRETE", "Concrete"), - ("OTHER", "Other"), - ], - string="Wall Material", - ) - floor_material = fields.Selection( - selection=[ - ("EARTH", "Earth"), - ("WOOD", "Wood"), - ("CEMENT", "Cement"), - ("TILE", "Tile"), - ("OTHER", "Other"), - ], - string="Floor Material", - ) - tenure_status = fields.Selection( - selection=[ - ("OWNED", "Owned"), - ("RENTED", "Rented"), - ("HOSTED", "Hosted"), - ("TEMPORARY", "Temporary"), - ], - string="Tenure Status", - ) - rooms_count = fields.Integer(string="Rooms Count") - overcrowding_indicator = fields.Float(string="Overcrowding Indicator") - - # Utilities - water_source_type = fields.Selection( - selection=[ - ("PIPED", "Piped"), - ("PUBLIC_TAP", "Public Tap"), - ("WELL", "Well"), - ("SPRING", "Spring"), - ("SURFACE_WATER", "Surface Water"), - ("RAINWATER", "Rainwater"), - ("TANKER_TRUCK", "Tanker Truck"), - ("OTHER", "Other"), - ], - string="Water Source Type", - ) - water_distance_minutes = fields.Integer(string="Water Distance (Minutes)") - sanitation_type = fields.Selection( - selection=[ - ("FLUSH_TOILET", "Flush Toilet"), - ("PIT_LATRINE", "Pit Latrine"), - ("COMPOSTING_TOILET", "Composting Toilet"), - ("SHARED", "Shared"), - ("OPEN", "Open"), - ("OTHER", "Other"), - ], - string="Sanitation Type", - ) - lighting_source = fields.Selection( - selection=[ - ("GRID", "Grid"), - ("SOLAR", "Solar"), - ("GENERATOR", "Generator"), - ("KEROSENE", "Kerosene"), - ("CANDLE", "Candle"), - ("NONE", "None"), - ], - string="Lighting Source", - ) - cooking_fuel_type = fields.Selection( - selection=[ - ("ELECTRICITY", "Electricity"), - ("GAS", "Gas"), - ("KEROSENE", "Kerosene"), - ("CHARCOAL", "Charcoal"), - ("FIREWOOD", "Firewood"), - ("BIOMASS", "Biomass"), - ("OTHER", "Other"), - ], - string="Cooking Fuel Type", - ) - mobile_phone_type = fields.Selection( - selection=[ - ("NONE", "None"), - ("BASIC", "Basic"), - ("SMARTPHONE", "Smartphone"), - ], - string="Mobile Phone Type", - ) - - husband_dead = fields.Boolean(string="Is Husband Dead") - husband_death_date = fields.Datetime(string="Husband Death Date") diff --git a/odoo/extensions/g2p_registry_addon/models/registry.py b/odoo/extensions/g2p_registry_addon/models/registry.py deleted file mode 100644 index 513078a..0000000 --- a/odoo/extensions/g2p_registry_addon/models/registry.py +++ /dev/null @@ -1,19 +0,0 @@ -from odoo import models, fields - - -class G2PRegistry(models.AbstractModel): - _name = "g2p.registry" - _description = "Abstract G2P Registry" - - internal_record_id = fields.Char(string="Internal Record ID") - - def action_open_view(self): - return { - "type": "ir.actions.act_window", - "name": "View Registry Record", - "res_model": self._name, - "res_id": self.id, - "view_mode": "form", - "target": "new", - "flags": {"mode": "readonly"}, - } diff --git a/odoo/extensions/g2p_registry_addon/security/ir.model.access.csv b/odoo/extensions/g2p_registry_addon/security/ir.model.access.csv deleted file mode 100644 index 54e7501..0000000 --- a/odoo/extensions/g2p_registry_addon/security/ir.model.access.csv +++ /dev/null @@ -1,5 +0,0 @@ -id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink -g2p_register_farmer_read,Read Farmer Registry,model_g2p_register_farmer,g2p_pbms.group_beneficiary_list_viewer,1,0,0,0 -g2p_register_farmer_write,Write Farmer Registry,model_g2p_register_farmer,g2p_pbms.group_beneficiary_list_editor,1,1,1,1 -g2p_register_household_read,Read Register Household,model_g2p_register_households,g2p_pbms.group_beneficiary_list_viewer,1,0,0,0 -g2p_register_household_write,Write Register Household,model_g2p_register_households,g2p_pbms.group_beneficiary_list_editor,1,1,1,1 diff --git a/odoo/extensions/g2p_registry_addon/static/description/icon.png b/odoo/extensions/g2p_registry_addon/static/description/icon.png deleted file mode 100644 index 5ecb429..0000000 Binary files a/odoo/extensions/g2p_registry_addon/static/description/icon.png and /dev/null differ diff --git a/odoo/extensions/g2p_registry_addon/static/src/css/registry_styles.scss b/odoo/extensions/g2p_registry_addon/static/src/css/registry_styles.scss deleted file mode 100644 index 40cd300..0000000 --- a/odoo/extensions/g2p_registry_addon/static/src/css/registry_styles.scss +++ /dev/null @@ -1,10 +0,0 @@ -.o_widget.o_widget_g2p_beneficiaries_widget { - width: 180% !important; - box-sizing: border-box; -} - -.o_form_view .o_notebook > .tab-content > .tab-pane > :first-child:not(.o_group) .o_field_x2many.o_field_x2many_list .o_list_renderer, -.o_form_view .o_notebook > .tab-content > .tab-pane > .o_invisible_modifier:first-child .o_field_x2many.o_field_x2many_list .o_list_renderer { - --ListRenderer-margin-x: 0 !important; -} - \ No newline at end of file diff --git a/odoo/extensions/g2p_registry_addon/static/src/js/beneficiaries_widget.js b/odoo/extensions/g2p_registry_addon/static/src/js/beneficiaries_widget.js deleted file mode 100644 index 7fb0b99..0000000 --- a/odoo/extensions/g2p_registry_addon/static/src/js/beneficiaries_widget.js +++ /dev/null @@ -1,110 +0,0 @@ -/** @odoo-module **/ - -import { Component, useState } from "@odoo/owl"; -import { DomainSelector } from "@web/core/domain_selector/domain_selector"; -// import { Domain, InvalidDomainError } from "@web/core/domain"; -// import { EvaluationError } from "@web/core/py_js/py_builtin"; -import { useService } from "@web/core/utils/hooks"; -import { _t } from "@web/core/l10n/translation"; -import { registry } from "@web/core/registry"; - -export class G2PBeneficiariesComponent extends Component { - static template = "g2p_beneficiaries_info_tpl"; - static components = { - DomainSelector - }; - static props = { - context: { type: Object, optional: true }, - resModel: { type: String, optional: true }, - record: { type: Object, optional: true }, - readonly: { type: Boolean, optional: true }, - }; - - setup() { - const recordData = this.props.record?.data || {}; - this.state = useState({ - title: _t("Beneficiaries"), - records: [], - page: 1, - pageSize: 3, - totalCount: 0, - totalPages: 1, - target_registry: recordData.target_registry || null, - searched: false, - domain: "[]", - showAllColumns: false, - }); - this.orm = useService("orm"); - console.log(this); - } - - onDomainChange(newDomain) { - this.state.domain = newDomain; - this.render(); - } - - getEvaluatedDomain() { - return this.state.domain; - } - - searchRegistrants() { - this.state.searched = true; // show title and pagination when search is clicked - this.state.page = 1; - this.state.pageSize = 20; - this._fetchRecords(); - } - - async _fetchRecords() { - const result = await this.orm.call( - 'g2p.bgtask.summary.wizard', - 'get_beneficiaries', - [this.props.record.resId, this.state.page, this.state.pageSize, this.getEvaluatedDomain()], - {}, - ); - - if (result?.response_body) { - const body = result.response_body; - this.state.records = body.response_payload?.beneficiaries || []; - this.state.totalCount = body.pagination_response?.number_of_items || 0; - this.state.totalPages = body.pagination_response?.number_of_pages || 1; - } else if (result?.message) { - this.state.records = result.message.beneficiaries || []; - this.state.totalCount = result.message.total_beneficiary_count || 0; - this.state.totalPages = Math.ceil(this.state.totalCount / this.state.pageSize) || 1; - } else if (result) { - this.state.records = result.records || []; - this.state.totalCount = result.total_count || 0; - this.state.totalPages = Math.ceil(this.state.totalCount / this.state.pageSize) || 1; - } - } - - async nextPage() { - if (this.state.page < this.state.totalPages) { - this.state.page++; - await this._fetchRecords(); - } - } - - async prevPage() { - if (this.state.page > 1) { - this.state.page--; - await this._fetchRecords(); - } - } - - toggleColumns() { - this.state.showAllColumns = !this.state.showAllColumns; - } -} - -export const g2pBeneficiariesWidget = { - component: G2PBeneficiariesComponent, - extractProps({ attrs }, dynamicInfo) { - console.log(attrs, dynamicInfo) - return { - resModel: attrs.model, - context: dynamicInfo.context, - }; - }, -}; -registry.category("view_widgets").add("g2p_beneficiaries_widget", g2pBeneficiariesWidget); diff --git a/odoo/extensions/g2p_registry_addon/static/src/xml/g2p_beneficiaries_info_tpl.xml b/odoo/extensions/g2p_registry_addon/static/src/xml/g2p_beneficiaries_info_tpl.xml deleted file mode 100644 index fbb4ac0..0000000 --- a/odoo/extensions/g2p_registry_addon/static/src/xml/g2p_beneficiaries_info_tpl.xml +++ /dev/null @@ -1,175 +0,0 @@ - - - - -
- -
- - -
- -
- - -
- -
-
- - -
- - Page of - -
-
- - -
- -
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Internal IDFunctional IDFirst NameLast NameGenderEst. AgeDisabledSource of IncomeEducation LevelCountryInternal IDFunctional IDHead NameHeadshipSizeChildren U5ElderlyFemaleMaleDwellingTenureRoomsOvercrowdingWaterSanitationLightingCooking FuelAddress 1Address 2PostalCountry
- - - -
- - No records found. - - - No records found. - - - No records found. -
-
- - - -
- - - Page of - - -
-
-
-
-
diff --git a/odoo/extensions/g2p_registry_addon/views/bgtask/bgtask_view.xml b/odoo/extensions/g2p_registry_addon/views/bgtask/bgtask_view.xml deleted file mode 100644 index f1ca744..0000000 --- a/odoo/extensions/g2p_registry_addon/views/bgtask/bgtask_view.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - g2p.bgtask.summary.wizard.form.inherit.beneficiaries - g2p.bgtask.summary.wizard - - - - - - - - - - - - - - \ No newline at end of file diff --git a/odoo/extensions/g2p_registry_addon/views/eligibility/eligibility_rule_view.xml b/odoo/extensions/g2p_registry_addon/views/eligibility/eligibility_rule_view.xml deleted file mode 100644 index 7f1a92c..0000000 --- a/odoo/extensions/g2p_registry_addon/views/eligibility/eligibility_rule_view.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - g2p.eligibility.rule.definition.form.inherit - g2p.eligibility.rule.definition - - - - - - - - - - - - - - - - diff --git a/odoo/extensions/g2p_registry_addon/views/entitlement/entitlement_rule_view.xml b/odoo/extensions/g2p_registry_addon/views/entitlement/entitlement_rule_view.xml deleted file mode 100644 index a0a4d91..0000000 --- a/odoo/extensions/g2p_registry_addon/views/entitlement/entitlement_rule_view.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - g2p.entitlement.rule.definition.form.inherit - g2p.entitlement.rule.definition - - - - - - - - - - - - - - - - diff --git a/odoo/extensions/g2p_registry_addon/views/menu.xml b/odoo/extensions/g2p_registry_addon/views/menu.xml deleted file mode 100644 index 7b740d9..0000000 --- a/odoo/extensions/g2p_registry_addon/views/menu.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - diff --git a/odoo/extensions/g2p_registry_addon/views/priority/priority_rule_view.xml b/odoo/extensions/g2p_registry_addon/views/priority/priority_rule_view.xml deleted file mode 100644 index faa3830..0000000 --- a/odoo/extensions/g2p_registry_addon/views/priority/priority_rule_view.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - g2p.priority.rule.definition.form.inherit - g2p.priority.rule.definition - - - - - - - - - - - - - - - - diff --git a/odoo/extensions/g2p_registry_addon/views/registry/farmer_registry_view.xml b/odoo/extensions/g2p_registry_addon/views/registry/farmer_registry_view.xml deleted file mode 100644 index cc19f91..0000000 --- a/odoo/extensions/g2p_registry_addon/views/registry/farmer_registry_view.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - - Farmer Registry - g2p.register.farmer - tree,form - - - - g2p.register.farmer.form - g2p.register.farmer - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
- - - g2p.register.farmer.tree - g2p.register.farmer - - - - - - - - - - - - -