Vision / tests /test_workbook_copy.py
kishankrish19's picture
Update MoM application with admin changes
10fc7f2
Raw History Blame Contribute Delete
11 kB
from datetime import date,timedelta
from io import BytesIO
from pathlib import Path
from zipfile import ZipFile
import hashlib
import sqlite3
from xml.dom import minidom
from exporter import export_report,Sheet,nodes,text,worksheet_paths
from tests.test_app import active,query
from tests.test_preparation_date import sign_in
SOURCE=Path(__file__).resolve().parents[1]/'sources'/'MOM_Technical Report on 15-09-2026.xlsx'
def unpack(content):
with ZipFile(BytesIO(content)) as z:parts={i.filename:z.read(i.filename) for i in z.infolist()}
shared=minidom.parseString(parts['xl/sharedStrings.xml']) if 'xl/sharedStrings.xml' in parts else None
strings=[text(n) for n in nodes(shared,'si')] if shared else []
sheets={name:Sheet(parts[path],strings) for name,path in worksheet_paths(parts)}
return parts,sheets
def records(sheet):
return [[sheet.value(r,col) for col in 'ABCDE'] for n,r in sorted(sheet.rows.items()) if n>1 and any(sheet.value(r,c) for c in 'BDE')]
def sample(app,mid=None):
mid=mid or active(app)['id']
meeting=dict(query(app,'SELECT * FROM meetings WHERE id=?',(mid,))[0])
users=query(app,'SELECT * FROM users ORDER BY id')
user_ids={u['username']:u['id'] for u in users}
reviews=[dict(r) for r in query(app,'SELECT a.*,u.name,rv.completed checked FROM reviews rv JOIN actions a ON a.id=rv.action_id JOIN users u ON u.id=a.user_id WHERE rv.meeting_id=?',(mid,))]
reviews[0]['checked']=1;reviews[1]['checked']=1
return dict(meeting=meeting,users=users,
updates=[dict(user_id=user_ids['madhav'],body=f'New update {i}') for i in range(12)]+[dict(user_id=user_ids['kishan'],body='=literal update')]+[dict(user_id=user_ids['niranjan'],body='New participant update')],
actions=[dict(user_id=user_ids['kishan'],name='Kishan H M',body='Only this week action',due_date=meeting['meeting_date'],due_note='')],reviews=reviews)
def test_copy_replaces_resizes_renumbers_and_preserves_archive(app):
original=SOURCE.read_bytes();digest=hashlib.sha256(original).hexdigest()
data=sample(app)
result=export_report(data,original).getvalue()
oldparts,old=unpack(original);parts,sheets=unpack(result)
assert set(sheets)=={'MOM','CLOSED'}
changed={name for name in oldparts if oldparts[name]!=parts[name]}
assert changed=={'xl/worksheets/sheet1.xml','xl/worksheets/sheet2.xml'}
assert hashlib.sha256(SOURCE.read_bytes()).hexdigest()==digest
mom=sheets['MOM'];owner=None;sections={};action_rows=[]
for _,r in sorted(mom.rows.items()):
a,b,c,d=[mom.value(r,col) for col in 'ABCD']
if a.startswith('Updates from '):owner=a.removeprefix('Updates from ').strip();sections[owner]=[]
elif b=='Actions':owner=None
elif a.isdigit() and owner:sections[owner].append((int(a),b))
elif a.isdigit() and b:action_rows.append((int(a),b,c,d))
assert len(sections['Madhav'])==12
assert sections['Kishan']==[(1,'=literal update')]
assert sections['Harshitha']==[]
assert sections['Niranjan']==[(1,'New participant update')]
assert [n for n,_ in sections['Madhav']]==list(range(1,13))
assert len(action_rows)==1 and action_rows[0][1]=='Only this week action'
assert all(a['body'] not in [r[1] for r in action_rows] for a in data['reviews'])
oldrecords=records(old['CLOSED']);closedrecords=records(sheets['CLOSED'])
assert [r[1:] for r in closedrecords[:len(oldrecords)]]==[r[1:] for r in oldrecords]
assert len(closedrecords)==len(oldrecords)+2
assert [int(r[0]) for r in closedrecords]==list(range(1,len(closedrecords)+1))
assert [r[4] for r in closedrecords[-2:]]==['Completed','Completed']
assert closedrecords[-2][1]==data['reviews'][0]['body']
assert closedrecords[-2][3]==data['reviews'][0]['name']
assert mom.value(mom.rows[4],'C')==date.fromisoformat(data['meeting']['meeting_date']).strftime('%A %d-%b-%Y')
assert any('Next weekly meeting on '+(date.fromisoformat(data['meeting']['meeting_date'])+timedelta(days=7)).strftime('%d-%m-%Y')==mom.value(r,'A') for r in mom.rows.values())
assert export_report(data,original).getvalue()==result
def test_next_copy_keeps_closed_history_but_not_old_week_entries(app):
source=SOURCE.read_bytes();first=sample(app)
previous=export_report(first,source).getvalue()
second=sample(app);second['meeting']['meeting_date']=(date.fromisoformat(first['meeting']['meeting_date'])+timedelta(days=7)).isoformat()
second['updates']=[];second['actions']=[];second['reviews']=[dict(first['reviews'][2],checked=1)]
result=export_report(second,previous,style_workbook=source).getvalue()
_,old=unpack(source);_,new=unpack(result)
assert len(records(new['CLOSED']))==len(records(old['CLOSED']))+3
assert not any(new['MOM'].value(row,'A').isdigit() and new['MOM'].value(row,'B') for row in new['MOM'].rows.values())
from importer import parse_report
assert parse_report(result)['actions']==[]
# Empty weeks must not lose the original row styles for a later populated week.
third=sample(app);third['reviews']=[]
later=export_report(third,result,style_workbook=source).getvalue()
_,sheets=unpack(later)
assert any(sheets['MOM'].value(r,'B')=='Only this week action' for r in sheets['MOM'].rows.values())
def test_route_creates_copy_and_keeps_unfinished_in_database(client,app):
sign_in(client,app)
meeting=active(app);before=query(app,'SELECT * FROM actions')
uid=query(app,"SELECT id FROM users WHERE username='harshitha'")[0]['id']
with sqlite3.connect(app.config['DATABASE']) as db:
db.execute('INSERT INTO updates(meeting_id,user_id,body) VALUES(?,?,?)',(meeting['id'],uid,'Current update'))
db.execute('INSERT INTO actions(meeting_id,user_id,body,due_date) VALUES(?,?,?,?)',(meeting['id'],uid,'Current action',meeting['meeting_date']))
db.execute('UPDATE reviews SET completed=1 WHERE meeting_id=? AND action_id=(SELECT MIN(action_id) FROM reviews WHERE meeting_id=?)',(meeting['id'],meeting['id']))
response=client.get(f"/reports/{meeting['id']}/excel")
assert response.status_code==200
_,sheets=unpack(response.data)
bodies=[sheets['MOM'].value(r,'B') for r in sheets['MOM'].rows.values()]
assert 'Current action' in bodies
assert all(a['body'] not in bodies for a in before)
assert len(query(app,'SELECT * FROM actions'))==len(before)+1
filename=f"MOM_Technical Report on {date.fromisoformat(meeting['meeting_date']).strftime('%d-%m-%Y')}.xlsx"
assert (Path(app.config['DATABASE']).parent/'reports'/filename).exists()
assert client.get(f"/reports/{meeting['id']}/excel").data==response.data
def test_action_rows_expand_and_dates_survive_roundtrip(app):
from openpyxl import load_workbook
data=sample(app)
data['actions']=[dict(data['actions'][0],body=f'Weekly action {i}') for i in range(55)]
result=export_report(data,SOURCE.read_bytes()).getvalue()
book=load_workbook(BytesIO(result),read_only=True)
rows=list(book['MOM'].iter_rows(max_col=5,values_only=True))
actions=[row for row in rows if isinstance(row[1],str) and row[1].startswith('Weekly action')]
assert [r[0] for r in actions]==list(range(1,56))
assert all(hasattr(r[2],'date') for r in actions)
book.close()
def test_action_picker_exposes_preceding_workweek_dates(client,app):
from tests.test_app import review,add
sign_in(client,app,'kishan');review(client,app)
meeting=active(app)
monday=date.fromisoformat(meeting['meeting_date'])
page=client.get('/entry/3')
assert f'min="{(monday-timedelta(days=7)).isoformat()}"'.encode() in page.data
assert f'max="{(monday+timedelta(days=7)).isoformat()}"'.encode() in page.data
assert add(client,app,3,'Working-week action',due_date=(monday-timedelta(days=5)).isoformat()).status_code==302
def test_requested_people_order_in_updates_and_actions(app):
data=sample(app)
by_name={u['username']:dict(u) for u in data['users']}
expected=['madhav','gokul','harshitha','manish','kishan','honey','madhan','vinay','kamlakant','sunny','rikki']
ordered=[by_name[name] for name in expected]
extras=sorted((dict(u) for u in data['users'] if u['username'] not in expected),key=lambda u:u['name'].casefold())
ordered+=extras
# Deliberately reverse people and interleave their entries. Preserve each
# person's own entry order while grouping people in the requested order.
data['updates']=[dict(user_id=u['id'],body=f"{u['username']} update {n}") for n in (1,2) for u in reversed(ordered)]
data['actions']=[dict(user_id=u['id'],name=u['name'],body=f"{u['username']} action {n}",due_date=data['meeting']['meeting_date'],due_note='') for n in (1,2) for u in reversed(ordered)]
data['reviews']=[]
original=SOURCE.read_bytes()
result=export_report(data,original).getvalue()
original_parts,old=unpack(original);parts,sheets=unpack(result)
sheet=sheets['MOM'];headers=[];updates=[];actions=[];in_actions=False
from importer import suggest_owner
for _,row in sorted(sheet.rows.items()):
a,b,c,d=[sheet.value(row,col) for col in 'ABCD']
if a.startswith('Updates from '):
headers.append(suggest_owner(a.removeprefix('Updates from '),data['users']))
elif b=='Actions':
in_actions=True
elif a.isdigit() and b:
(actions if in_actions else updates).append((int(a),b,d))
assert headers==[u['id'] for u in ordered]
assert [body for _,body,_ in updates]==[f"{u['username']} update {n}" for u in ordered for n in (1,2)]
assert [serial for serial,_,_ in updates]==[1,2]*len(ordered)
assert [owner for _,_,owner in actions]==[u['name'] for u in ordered for _ in (1,2)]
assert [body for _,body,_ in actions]==[f"{u['username']} action {n}" for u in ordered for n in (1,2)]
assert [serial for serial,_,_ in actions]==list(range(1,len(actions)+1))
assert records(sheets['CLOSED'])==records(old['CLOSED'])
assert all(parts[name]==content for name,content in original_parts.items() if name not in {'xl/worksheets/sheet1.xml','xl/worksheets/sheet2.xml'})
# Reusing the generated copy must keep the same order and valid merged rows.
repeated=export_report(data,result,style_workbook=original).getvalue()
_,repeated_sheets=unpack(repeated)
assert records(repeated_sheets['MOM'])==records(sheet)
from openpyxl import load_workbook
workbook=load_workbook(BytesIO(result))
assert workbook.sheetnames==['MOM','CLOSED']
for merged in workbook['MOM'].merged_cells.ranges:
assert merged.min_row<=merged.max_row
workbook.close()
def test_order_handles_full_names_case_and_kamalakanth_spelling():
from exporter import report_person_key
assert report_person_key('Kamlakant')[0]==report_person_key('Kamalakanth')[0]==8
assert report_person_key(' MADHAV S ')[0]==0
assert report_person_key('Madhan D')[0]==6
assert report_person_key('New Employee')[0]>report_person_key('Rikki')[0]