Vision / exporter.py
kishankrish19's picture
Add resume coordination from Excel, exclude deleted users, and modern ordering UI
4de97b5
Raw History Blame Contribute Delete
16.4 kB
"""Edit a copy of the previous XLSX, retaining its original workbook package."""
from datetime import date, timedelta
from io import BytesIO
from math import ceil
from pathlib import PurePosixPath
from zipfile import ZipFile, ZIP_DEFLATED
from xml.dom import minidom
import re
S='http://schemas.openxmlformats.org/spreadsheetml/2006/main'
R='http://schemas.openxmlformats.org/officeDocument/2006/relationships'
# Report display order is independent of the weekly coordinator rotation.
REPORT_PERSON_ORDER=('madhav','gokul','harshitha','manish','kishan','honey',
'madhan','vinay','kamalakanth','sunny','rikki')
def report_person_key(name):
parts=str(name or '').casefold().split()
first=re.sub('[^a-z]','',parts[0]) if parts else ''
if first in {'kamlakant','kamlakanth','kamalakant','kamalakanth'}:
first='kamalakanth'
rank=REPORT_PERSON_ORDER.index(first) if first in REPORT_PERSON_ORDER else len(REPORT_PERSON_ORDER)
return rank,' '.join(parts)
def children(node,name):
return [n for n in node.childNodes if n.nodeType==n.ELEMENT_NODE and n.localName==name]
def nodes(node,name):
return list(node.getElementsByTagNameNS(S,name))
def text(node):
return ''.join(n.data if n.nodeType in (n.TEXT_NODE,n.CDATA_SECTION_NODE) else text(n) for n in node.childNodes)
class Sheet:
def __init__(self,raw,strings):
self.doc=minidom.parseString(raw)
self.root=self.doc.documentElement
self.data=nodes(self.root,'sheetData')[0]
self.strings=strings
self.rows={int(r.getAttribute('r')):r for r in children(self.data,'row')}
self.row_map={}
def value(self,row,col):
for c in children(row,'c'):
if re.sub(r'\d+','',c.getAttribute('r'))!=col:continue
if c.getAttribute('t')=='inlineStr':return ''.join(text(n) for n in children(c,'is')).strip()
vals=children(c,'v')
if not vals:return ''
value=text(vals[0])
return self.strings[int(value)].strip() if c.getAttribute('t')=='s' else value
return ''
def set(self,row,col,value):
ref=col+row.getAttribute('r')
cell=next((c for c in children(row,'c') if c.getAttribute('r')==ref),None)
if cell is None:
cell=self.doc.createElementNS(S,'c');cell.setAttribute('r',ref);row.appendChild(cell)
for n in list(cell.childNodes):cell.removeChild(n)
if cell.hasAttribute('t'):cell.removeAttribute('t')
if value is None or value=='':return
if isinstance(value,(int,float)):
v=self.doc.createElementNS(S,'v');v.appendChild(self.doc.createTextNode(str(value)));cell.appendChild(v)
else:
cell.setAttribute('t','inlineStr')
inline=self.doc.createElementNS(S,'is');t=self.doc.createElementNS(S,'t')
t.setAttribute('xml:space','preserve');t.appendChild(self.doc.createTextNode(str(value)))
inline.appendChild(t);cell.appendChild(inline)
def clone(self,row,number,values=None):
clone=row.cloneNode(True);clone.setAttribute('r',str(number))
for cell in children(clone,'c'):
cell.setAttribute('r',re.sub(r'\d+',str(number),cell.getAttribute('r')))
if values is not None:
for col in 'ABCDE':self.set(clone,col,values.get(col))
lines=max((sum(max(1,ceil(len(line)/100)) for line in str(v).splitlines()) for v in values.values()),default=1)
clone.setAttribute('ht',str(min(409,max(float(row.getAttribute('ht') or 20),lines*15+8))))
clone.setAttribute('customHeight','1')
return clone
def replace(self,rows):
for row in list(self.data.childNodes):self.data.removeChild(row)
for row in rows:self.data.appendChild(row)
def mapped(self,old):
if old in self.row_map:return self.row_map[old]
earlier=[r for r in self.row_map if r<=old]
if not earlier:return old
anchor=max(earlier)
return self.row_map[anchor]+old-anchor
def shift_references(self):
def ref(value):
return re.sub(r'(\$?[A-Z]{1,3}\$?)(\d+)',lambda m:m[1]+str(self.mapped(int(m[2]))),value)
for name,attrs in [('mergeCell',['ref']),('conditionalFormatting',['sqref']),('dataValidation',['sqref']),('hyperlink',['ref']),('autoFilter',['ref']),('dimension',['ref'])]:
for node in nodes(self.root,name):
for attr in attrs:
if node.hasAttribute(attr):node.setAttribute(attr,ref(node.getAttribute(attr)))
for node in nodes(self.root,'sheetView'):node.setAttribute('topLeftCell','A1')
for node in nodes(self.root,'selection'):
node.setAttribute('activeCell','A1');node.setAttribute('sqref','A1')
def bytes(self):return self.doc.toxml(encoding='UTF-8')
def worksheet_paths(package):
doc=minidom.parseString(package['xl/workbook.xml'])
rels=minidom.parseString(package['xl/_rels/workbook.xml.rels'])
mapping={n.getAttribute('Id'):n.getAttribute('Target') for n in rels.documentElement.childNodes if n.nodeType==n.ELEMENT_NODE}
result=[]
for node in nodes(doc,'sheet'):
target=mapping[node.getAttributeNS(R,'id')]
path=target.lstrip('/') if target.startswith('/') else 'xl/'+target
if '..' in PurePosixPath(path).parts:raise ValueError('Unsupported worksheet path in the previous report.')
result.append((node.getAttribute('name'),path))
return result
def add_closed_sheet(package):
book=minidom.parseString(package['xl/workbook.xml'])
book.documentElement.setAttribute('xmlns:r',R)
rels=minidom.parseString(package['xl/_rels/workbook.xml.rels'])
types=minidom.parseString(package['[Content_Types].xml'])
number=max(int(n.getAttribute('sheetId')) for n in nodes(book,'sheet'))+1
path=f'xl/worksheets/sheet{number}.xml'
while path in package:number+=1;path=f'xl/worksheets/sheet{number}.xml'
relid='rIdMOMClosed'
ids={n.getAttribute('Id') for n in rels.documentElement.childNodes if n.nodeType==n.ELEMENT_NODE}
while relid in ids:relid+='X'
sheet=book.createElementNS(S,'sheet');sheet.setAttribute('name','CLOSED');sheet.setAttribute('sheetId',str(number));sheet.setAttributeNS(R,'r:id',relid)
nodes(book,'sheets')[0].appendChild(sheet)
relation=rels.createElementNS(rels.documentElement.namespaceURI,'Relationship')
for key,value in dict(Id=relid,Type=R+'/worksheet',Target=path[3:]).items():relation.setAttribute(key,value)
rels.documentElement.appendChild(relation)
override=types.createElementNS(types.documentElement.namespaceURI,'Override')
override.setAttribute('PartName','/'+path);override.setAttribute('ContentType','application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml')
types.documentElement.appendChild(override)
package['xl/workbook.xml']=book.toxml(encoding='UTF-8');package['xl/_rels/workbook.xml.rels']=rels.toxml(encoding='UTF-8');package['[Content_Types].xml']=types.toxml(encoding='UTF-8')
package[path]=f'<worksheet xmlns="{S}"><dimension ref="A1:E1"/><sheetData><row r="1"/></sheetData></worksheet>'.encode()
return path
def export_report(data,previous_workbook,style_workbook=None):
"""Replace this week's entries, append completions, and retain all other parts."""
with ZipFile(BytesIO(previous_workbook)) as source:
infos=source.infolist();package={i.filename:source.read(i.filename) for i in infos}
paths=worksheet_paths(package)
mom_path=next((p for name,p in paths if name.casefold()=='mom'),paths[0][1])
closed_path=next((p for name,p in paths if name.casefold()=='closed'),None)
if not closed_path:closed_path=add_closed_sheet(package)
shared=minidom.parseString(package['xl/sharedStrings.xml']) if 'xl/sharedStrings.xml' in package else None
strings=[text(n) for n in nodes(shared,'si')] if shared else []
mom=Sheet(package[mom_path],strings);closed=Sheet(package[closed_path],strings)
ordered=sorted(mom.rows.items())
headers=[(i,re.sub(r'^\s*Updates from\s+','',mom.value(r,'A'),flags=re.I).strip()) for i,r in ordered if re.match(r'^\s*Updates from\s+',mom.value(r,'A'),re.I)]
action_header=next((i for i,r in ordered if mom.value(r,'B').casefold() in ('action','actions') and mom.value(r,'D').casefold()=='owner'),None)
if not headers or not action_header:raise ValueError('The previous workbook must have Updates from Name sections and Actions / Due Date / Owner columns.')
action_rows=[i for i,r in ordered if i>action_header and mom.value(r,'A').isdigit() and mom.value(r,'B')]
footer_start=max(action_rows,default=action_header)+1
update_sample=mom.rows.get(headers[0][0]+1,mom.rows[headers[0][0]])
# A previously empty section takes its row styling from a remaining update/action.
if not mom.value(update_sample,'A').isdigit():
update_sample=next((r for i,r in ordered if i<action_header and mom.value(r,'A').isdigit()),mom.rows.get(action_header+1,update_sample))
action_sample=mom.rows[action_rows[0]] if action_rows else update_sample
if style_workbook:
with ZipFile(BytesIO(style_workbook)) as styles_zip:
style_package={i.filename:styles_zip.read(i.filename) for i in styles_zip.infolist()}
style_paths=worksheet_paths(style_package)
style_path=next((p for name,p in style_paths if name.casefold()=='mom'),style_paths[0][1])
style_shared=minidom.parseString(style_package['xl/sharedStrings.xml']) if 'xl/sharedStrings.xml' in style_package else None
style_strings=[text(n) for n in nodes(style_shared,'si')] if style_shared else []
style_sheet=Sheet(style_package[style_path],style_strings)
style_action_header=next((i for i,r in style_sheet.rows.items() if style_sheet.value(r,'B').casefold() in ('action','actions') and style_sheet.value(r,'D').casefold()=='owner'),None)
if style_action_header:
update_sample=next((r for i,r in sorted(style_sheet.rows.items()) if i<style_action_header and style_sheet.value(r,'A').isdigit()),update_sample)
action_sample=next((r for i,r in sorted(style_sheet.rows.items()) if i>style_action_header and style_sheet.value(r,'A').isdigit()),action_sample)
users=[dict(u) for u in data['users']]
names_by_id={u['id']:u['name'] for u in users}
order_by_id={u['id']:u.get('report_order') for u in users}
archived_by_id={u['id']:bool(u.get('archived')) for u in users}
def person_key(uid,name):
position=order_by_id.get(uid)
return (0,position,report_person_key(name)) if position is not None else (1,0,report_person_key(name))
def find_owner(name):
from importer import suggest_owner
return data.get('owner_map',{}).get(name) or suggest_owner(name,users)
updates={u['id']:[] for u in users}
for item in data['updates']:updates.setdefault(item['user_id'],[]).append(item['body'])
output=[]
def keep(old):
new=len(output)+1;mom.row_map[old]=new;output.append(mom.clone(mom.rows[old],new))
# Retain genuine blank rows in the cover as well as rows with metadata.
for old in range(1,headers[0][0]):
if old in mom.rows:keep(old)
else:
row=mom.doc.createElementNS(S,'row');row.setAttribute('r',str(len(output)+1));output.append(row);mom.row_map[old]=len(output)
seen=set();sections=[]
for index,(start,name) in enumerate(headers):
uid=find_owner(name)
if uid is not None:seen.add(uid)
end=headers[index+1][0] if index+1<len(headers) else action_header
sample=next((mom.rows[i] for i in range(start+1,end) if i in mom.rows and mom.value(mom.rows[i],'A').isdigit()),update_sample)
sections.append((names_by_id.get(uid,name),start,end,uid,sample))
for user in users:
if not user.get('archived') and user['id'] not in seen and updates[user['id']]:
sections.append((user['name'],None,None,user['id'],update_sample))
# Determine original section boundaries before moving any section. New
# contributors belong in the same ordering, not appended after the template.
for name,start,end,uid,sample in sorted(sections,key=lambda section:person_key(section[3],section[0])):
bodies=updates.get(uid,[])
if uid is not None and archived_by_id.get(uid,False) and not bodies:
if start is not None:
for old in range(start,end):mom.row_map[old]=len(output)
continue
if start is None:
output.append(mom.clone(mom.rows[headers[-1][0]],len(output)+1,{'A':'Updates from '+name}))
else:
keep(start)
for serial,body in enumerate(bodies,1):output.append(mom.clone(sample,len(output)+1,{'A':serial,'B':body}))
if start is not None:
for old in range(start+1,end):mom.row_map[old]=mom.row_map[start]+min(old-start,max(1,len(bodies)))
keep(action_header)
epoch=date(1904,1,1) if re.search(br'date1904="(?:1|true)"',package['xl/workbook.xml']) else date(1899,12,30)
def deadline(action):return action['due_note'] or ((date.fromisoformat(action['due_date'])-epoch).days if action['due_date'] else '')
# Prior unfinished items stay in database history, never in this week's Excel.
active=sorted(data['actions'],key=lambda action:person_key(action['user_id'],names_by_id.get(action['user_id'],action['name'])))
for serial,action in enumerate(active,1):output.append(mom.clone(action_sample,len(output)+1,{'A':serial,'B':action['body'],'C':deadline(action),'D':action['name']}))
for offset,old in enumerate(action_rows,1):mom.row_map[old]=mom.row_map[action_header]+min(offset,max(1,len(active)))
for old,_ in ordered:
if old>=footer_start:keep(old)
meeting=data['meeting'];meeting_day=date.fromisoformat(meeting['meeting_date'])
fields={'meeting date':meeting_day.strftime('%A %d-%b-%Y'),'location':meeting['location'],'subject':meeting['title'],'minutes taken by':meeting['minutes_by']}
if meeting['presenter']:fields['presented by']=meeting['presenter']
for row in output:
label=mom.value(row,'A').strip().casefold()
if label in fields:mom.set(row,'C',fields[label])
if label.startswith('next weekly meeting'):mom.set(row,'A','Next weekly meeting on '+(meeting_day+timedelta(days=7)).strftime('%d-%m-%Y'))
mom.replace(output);mom.shift_references()
records=[(old,row) for old,row in sorted(closed.rows.items()) if old>1 and (closed.value(row,'B') or closed.value(row,'D') or closed.value(row,'E')) and closed.value(row,'B').casefold()!='actions']
if not closed.value(closed.rows[1],'B'):
for col,value in zip('ABCDE',['Sl No','Actions','Due Date','Owner','Status']):closed.set(closed.rows[1],col,value)
for serial,(_,row) in enumerate(records,1):
if closed.value(row,'A')!=str(serial):closed.set(row,'A',serial)
last=records[-1][0] if records else 1
sample=records[-1][1] if records else closed.doc.importNode(action_sample,True)
completed=[a for a in data['reviews'] if a['checked']]
added=[closed.clone(sample,last+i,{'A':len(records)+i,'B':a['body'],'C':deadline(a),'D':a['name'],'E':'Completed'}) for i,a in enumerate(completed,1)]
tail=[]
for old,row in sorted(closed.rows.items()):
if old>last:tail.append(closed.clone(row,old+len(added)))
closed.row_map[old]=old+(len(added) if old>last else 0)
closed.replace([row for old,row in sorted(closed.rows.items()) if old<=last]+added+tail);closed.shift_references()
dimension=nodes(closed.root,'dimension')
if dimension:
current=dimension[0].getAttribute('ref')
max_row=max(int(r.getAttribute('r')) for r in children(closed.data,'row'))
match=re.search(r'([A-Z]+)(\d+)$',current)
if match and int(match[2])<max_row:
dimension[0].setAttribute('ref',current[:match.start()]+match[1]+str(max_row))
package[mom_path]=mom.bytes();package[closed_path]=closed.bytes()
result=BytesIO()
with ZipFile(result,'w',ZIP_DEFLATED) as target:
original_names={i.filename for i in infos}
for info in infos:target.writestr(info,package[info.filename])
for name in package.keys()-original_names:target.writestr(name,package[name])
result.seek(0)
return result