Files

51 lines
3.5 KiB
Python

#!/usr/bin/env python3
"""Prepare synthetic profiles/history outside the measurement window."""
import argparse, csv, datetime as dt, json, os, ssl, urllib.request, urllib.error
from tls import application_context
from pathlib import Path
p=argparse.ArgumentParser()
p.add_argument('--base-url', required=True); p.add_argument('--ca', required=True)
p.add_argument('--accounts', required=True, help='Private JSON: AccountId, Password, Role')
p.add_argument('--output', required=True); p.add_argument('--days', type=int, default=30)
a=p.parse_args()
if not a.base_url.startswith('https://'): p.error('HTTPS is required')
if not 2 <= a.days <= 365: p.error('days must be 2..365')
context=application_context(cafile=a.ca)
def call(method,path,body=None,token=None):
headers={'Content-Type':'application/json'}
if token: headers['Authorization']='Bearer '+token
req=urllib.request.Request(a.base_url.rstrip('/')+path, data=json.dumps(body).encode() if body is not None else None, headers=headers,method=method)
try:
with urllib.request.urlopen(req,context=context,timeout=60) as r: return r.status,json.load(r)
except urllib.error.HTTPError as e:
if e.code==404: return 404,None
raise RuntimeError(f'{method} {path}: HTTP {e.code}') from None
out=Path(a.output)
out.mkdir(mode=0o700,parents=True,exist_ok=True); os.chmod(out,0o700)
if (out/'users.csv').exists(): p.error('Output users.csv already exists; use a new directory')
rows=[]
for account in json.loads(Path(a.accounts).read_text()):
if account['Role']!='Patient' or account['AccountId']=='installation-check': continue
_,login=call('POST','/api/authentication/login',{'accountId':account['AccountId'],'password':account['Password']})
token=login['accessToken']
status,profile=call('GET','/api/patients/me',token=token)
if status==404:
_,profile=call('POST','/api/patients',{'name':'Synthetic energy test '+account['AccountId'],'dateOfBirth':'1990-01-01','contactInfo':'energy@example.test'},token)
pid=profile['patientId']
now=dt.datetime.now(dt.timezone.utc)
# Seed only absent exact synthetic timestamps; rerunning does not duplicate baseline rows.
start=(now-dt.timedelta(days=a.days)).replace(hour=0,minute=0,second=0,microsecond=0)
_,existing=call('GET',f'/api/patients/{pid}/observations?from={start.isoformat().replace("+00:00","Z")}&to={now.isoformat().replace("+00:00","Z")}',token=token)
times={o['measuredAt'].rstrip('Z') for o in existing}
for day in range(a.days):
for hour in [8,18]:
instant=(start+dt.timedelta(days=day,hours=hour)).isoformat().replace('+00:00','Z')
if instant.rstrip('Z') in times: continue
call('POST',f'/api/patients/{pid}/observations',{'measuredAt':instant,'systolic':122+day%12,'diastolic':76+day%8,'pulse':62+day%10,'measurementContext':{'setting':'Clinic' if day%10==0 else 'Unknown' if day%10==1 else 'Home','activityCondition':'AfterActivity' if day%10==2 else 'Unknown' if day%10==1 else 'AtRest','restDurationMinutes':None if day%10 in [1,2] else 5,'bodyPosition':None if day%10==1 else 'Seated'},'note':'Synthetic energy baseline'},token)
rows.append([account['AccountId'],account['Password'],pid])
print('Prepared synthetic patient:',account['AccountId'])
with (out/'users.csv').open('x') as f:
os.chmod(f.name,0o600); w=csv.writer(f);w.writerow(['account_id','password','patient_id']);w.writerows(rows)
if not rows: raise SystemExit('No patient accounts supplied')
print(f'Prepared {len(rows)} patients; private CSV: {out / "users.csv"}')