MEGAINFRA-WEBAPP/scripts/pb-add-employers.py

72 lines
3.3 KiB
Python

#!/usr/bin/env python3
"""Create site employers and dated worker assignments. Existing records are untouched.
Run: python3 scripts/pb-add-employers.py
All collection access is server-only; the app enforces workforce and site permissions.
"""
import sys
from pb_env import http, superuser_token
def main():
token = superuser_token()
def read(name):
code, result = http("GET", f"/api/collections/{name}", token=token)
if code != 200:
raise RuntimeError(f"Cannot read {name}: HTTP {code}")
return result
def relation(name, collection, required=True):
return {"name": name, "type": "relation", "required": required,
"collectionId": collection["id"], "maxSelect": 1, "cascadeDelete": False}
def ensure(name, fields, indexes):
wanted = {"name": name, "type": "base", "fields": fields + [
{"name": "created", "type": "autodate", "onCreate": True, "onUpdate": False},
{"name": "updated", "type": "autodate", "onCreate": True, "onUpdate": True},
], "indexes": indexes, **{rule: None for rule in (
"listRule", "viewRule", "createRule", "updateRule", "deleteRule")}}
code, actual = http("GET", f"/api/collections/{name}", token=token)
if code == 404:
code, actual = http("POST", "/api/collections", wanted, token)
if code != 200:
raise RuntimeError(f"Cannot create {name}: HTTP {code}: {actual}")
print(f"Created {name}")
elif code != 200:
raise RuntimeError(f"Cannot inspect {name}: HTTP {code}")
actual = read(name)
by_name = {f["name"]: f for f in actual["fields"]}
for field in wanted["fields"]:
if any(by_name.get(field["name"], {}).get(k) != v for k, v in field.items()):
raise RuntimeError(f"Incompatible {name}.{field['name']}")
for index in indexes:
if index not in actual.get("indexes", []):
raise RuntimeError(f"Missing index on {name}")
for rule in ("listRule", "viewRule", "createRule", "updateRule", "deleteRule"):
if actual.get(rule) is not None:
raise RuntimeError(f"Expected server-only access on {name}")
return actual
sites, employees = read("sites"), read("employees")
employers = ensure("employers", [
{"name": "name", "type": "text", "required": True, "max": 160},
relation("site", sites),
], ["CREATE UNIQUE INDEX `idx_employers_site_name` ON `employers` (`site`, lower(trim(`name`)))"])
ensure("employee_employer_assignments", [
relation("employee", employees), relation("site", sites),
relation("employer", employers, False),
{"name": "effective_from", "type": "date", "required": True},
{"name": "revision", "type": "number", "required": True, "min": 1, "onlyInt": True},
], [
"CREATE UNIQUE INDEX `idx_employer_assignment_revision` ON `employee_employer_assignments` (`employee`, `site`, `revision`)",
"CREATE INDEX `idx_employer_assignment_site` ON `employee_employer_assignments` (`site`, `employee`, `effective_from`)",
])
print("Verified employer and assignment schemas. No worker or timesheet records changed.")
if __name__ == "__main__":
try:
main()
except Exception as exc:
sys.exit(str(exc))