#!/usr/bin/env python3 import re import datetime import util import autoproc import logging logger = logging.getLogger(__name__) def isnew(text): return text.startswith('\r\n\r\nNOTE DATED: ') or re.match(r'\x1b\[H\x1b\[J\x1b\[2J\x1b\[H\r(-{10,})\r\n.*?Progress Notes\r\n\1\r\nNOTE DATED: ', text) def collapse(text): return re.sub(r'\x1b\[H\x1b\[J\x1b\[2J\x1b\[H\r(-{10,})\r\n.*?Progress Notes\r\n\1\r\n(.*?\*\* CONTINUED FROM PREVIOUS SCREEN \*\*\r\n)?', '', text).strip() local_tzinfo = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo def parse(text): data = re.match(r'NOTE DATED: (?P.*?)\r\n(?:LOCAL TITLE: (?P.*?)\r\n)?(?:STANDARD TITLE: (?P.*?)\r\n)?(?:VISIT: (?P.*?)\r\n)?(?:ADMITTED: (?P.*?)\r\n)?', text).groupdict() data['note_dated'] = datetime.datetime.strptime(data['note_dated'], '%m/%d/%Y %H:%M').replace(tzinfo=local_tzinfo) if ':' in data['note_dated'] else datetime.datetime.strptime(data['note_dated'], '%m/%d/%Y').replace(tzinfo=local_tzinfo) data['body'] = text return data async def cmd_reports(proc, mrn, alpha, omega): """Fetch progress notes""" async with proc.sendline, autoproc.expect_async(proc) as expect: proc.sendline('^PNPT') assert await expect.endswith('\r\nSelect PATIENT NAME: ') proc.sendline(mrn) assert await expect.endswith('\r\nPrint Notes Beginning: ') proc.sendline(util.vista_strftime(omega)) assert await expect.endswith('\r\n Thru: ') proc.sendline(util.vista_strftime(alpha)) found = True match await expect.endswith('\r\nDo you want WORK copies or CHART copies? CHART// ', '\r\nPrint Notes Beginning: '): case autoproc.ExpectMatch(index=0): proc.sendline() # default CHART if await expect.endswith('\r\nDo you want to start each note on a new page? NO// '): proc.sendline() # default NO assert await expect.endswith('\r\nDEVICE: HOME// ') proc.sendline('HOME;;1023') assert await expect.earliest(' HOME(CRT)\r\n') case autoproc.ExpectMatch(index=1): proc.sendline('^') assert await expect.endswith('\r\nSelect PATIENT NAME: ') proc.sendline('^') assert await expect.endswith('\r\nSelect Progress Notes Print Options Option: ') found = False case _: assert False pages = [] while found: match m_delimiter := await expect.endswith('\r\nType to continue or \'^\' to exit: ', '\r\nSelect PATIENT NAME: '): case autoproc.ExpectMatch(index=0, before=before): if isnew(before) and len(pages) > 0: yield parse(collapse('\r\n'.join(pages))) pages = [] pages.append(before) proc.sendline() case autoproc.ExpectMatch(index=1, before=before): if isnew(before) and len(pages) > 0: yield parse(collapse('\r\n'.join(pages))) pages = [] pages.append(before) yield parse(collapse('\r\n'.join(pages))) proc.sendline('^') assert await expect.endswith('\r\nSelect Progress Notes Print Options Option: ') break case _: assert False proc.sendline('^') proc.sendline('^Patient information AND OE/RR') assert await expect.endswith('\r\nSelect Patient Information and OE/RR Option: ', '\r\nSelect Patient Information and OE/RR Option: ') expect.clear()