"""Bounded, data-only parser for the team's Excel MOM layout and app exports.""" from datetime import datetime, timedelta from io import BytesIO from pathlib import PurePosixPath from zipfile import ZipFile, BadZipFile import re import xml.etree.ElementTree as ET NS={'s':'http://schemas.openxmlformats.org/spreadsheetml/2006/main'} def parse_report(content): def xml(data): if b'80*1024*1024: raise ValueError('The uncompressed workbook is too large (80 MB maximum).') strings=[] if 'xl/sharedStrings.xml' in z.namelist(): strings=[''.join(n.itertext()) for n in xml(z.read('xl/sharedStrings.xml')).findall('s:si',NS)] book=xml(z.read('xl/workbook.xml')) sheet=book.find('s:sheets/s:sheet',NS) rel_id=sheet.attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id'] rels=xml(z.read('xl/_rels/workbook.xml.rels')) target=next(r.attrib['Target'] for r in rels if r.attrib['Id']==rel_id) target=target.lstrip('/') if target.startswith('/') else 'xl/'+target if '..' in PurePosixPath(target).parts: raise ValueError('Unsupported worksheet path.') rows={} for c in xml(z.read(target)).findall('.//s:sheetData/s:row/s:c',NS): ref=c.attrib['r'] match=re.fullmatch(r'([A-Z]+)(\d+)',ref) col,row=match[1],int(match[2]) if row>20000 or col not in ('A','B','C','D','E'): continue value=c.find('s:v',NS) if c.attrib.get('t')=='inlineStr': node=c.find('s:is',NS) text=''.join(node.itertext()) if node is not None else '' elif value is not None and value.text: text=strings[int(value.text)] if c.attrib.get('t')=='s' else value.text else: text='' if text.strip(): rows.setdefault(row,{})[col]=text.strip() except (BadZipFile,ET.ParseError,KeyError,IndexError,StopIteration,AttributeError,RuntimeError) as error: raise ValueError('Unable to read this .xlsx workbook. Use the MOM layout with Actions, Due Date and Owner columns.') from error epoch=datetime(1904,1,1) if (book.find('s:workbookPr',NS) is not None and book.find('s:workbookPr',NS).attrib.get('date1904') in ('1','true')) else datetime(1899,12,30) result=dict(title='Weekly Technical Meeting',location='Opticent, Bangalore',presenter='',updates=[],actions=[],owners=[]) current=None in_actions=False found_action_table=False for number,row in sorted(rows.items()): a,b,c,d,e=[row.get(col,'') for col in 'ABCDE'] if a.lower() in ('subject','location','presented by'): key={'subject':'title','location':'location','presented by':'presenter'}[a.lower()] result[key]=c or b or result[key] match=re.match(r'Updates from\s+(.+)',a,re.I) if match: current=re.sub(r'\s*\((Imported|Submitted|Draft|No entry)\)\s*$','',match[1],flags=re.I).strip() in_actions=False elif b.lower() in ('actions','action') and d.lower()=='owner': in_actions=True found_action_table=True current=None elif a.lower() in ('previous action review','actions from this meeting'): in_actions=True current=None elif in_actions and b and d and a.isdigit(): due=None if re.fullmatch(r'\d+(\.\d+)?',c): try: due=(epoch+timedelta(days=float(c))).date().isoformat() except (OverflowError,ValueError): raise ValueError(f'Invalid date in row {number}.') from None else: for fmt in ('%Y-%m-%d','%d-%m-%Y','%d/%m/%Y','%d-%b-%Y'): try: due=datetime.strptime(c,fmt).date().isoformat() break except ValueError: pass result['actions'].append(dict(owner=d,body=b,due_date=due,due_note='' if due else c,completed=e.lower() in ('completed','complete','done'),row=number)) elif current and a.isdigit() and b and b!='No updates recorded.': result['updates'].append(dict(owner=current,body=b,row=number)) if not found_action_table: raise ValueError('No action table was found. The first worksheet must contain Actions, Due Date and Owner columns (B, C and D).') result['owners']=sorted({x['owner'] for x in result['updates']+result['actions']},key=str.casefold) if len(result['owners'])>100 or len(result['actions'])>2000 or len(result['updates'])>5000: raise ValueError('This workbook exceeds the supported MOM report size.') return result def suggest_owner(name,users): normal=lambda s:re.sub('[^a-z0-9]','',s.lower()) exact=[u for u in users if normal(u['name'])==normal(name)] if len(exact)==1: return exact[0]['id'] first=[u for u in users if u['name'].split()[0].lower()==name.split()[0].lower()] return first[0]['id'] if len(first)==1 else None