Vision / setup_routes.py
kishankrish19's picture
Add resume coordination from Excel, exclude deleted users, and modern ordering UI
4de97b5
Raw History Blame Contribute Delete
19.2 kB
import json
import re
import secrets
from datetime import date, timedelta
from pathlib import Path
from flask import abort, flash, g, redirect, render_template, request, session, url_for
from werkzeug.security import generate_password_hash
from werkzeug.utils import secure_filename
from importer import parse_report, suggest_owner
from seed import DEFAULT_PASSWORD
def register_setup(app,db,admin_only):
def pending():
key=session.get('pending_import','')
if not re.fullmatch('[a-f0-9]{32}',key):
return None
path=Path(app.config['DATABASE']).parent/'imports'/(key+'.json')
return json.loads(path.read_text(encoding='utf-8')) if path.exists() else None
@app.route('/setup',methods=['GET','POST'])
@admin_only
def setup():
complete=db().execute("SELECT 1 FROM metadata WHERE key='setup_complete'").fetchone()
if complete:
flash('First-run setup is already complete. Your weekly meetings now carry actions forward automatically.','info')
return redirect(url_for('admin'))
users=db().execute('SELECT * FROM users ORDER BY name').fetchall()
preview=pending()
if request.method=='POST':
try:
operation=request.form.get('operation')
if operation=='upload':
file=request.files.get('report')
if not file or not file.filename.lower().endswith('.xlsx'):
raise ValueError('Select an Excel .xlsx MOM report.')
content=file.read(10*1024*1024+1)
if len(content)>10*1024*1024:
raise ValueError('The workbook must be 10 MB or smaller.')
preview=parse_report(content)
key=secrets.token_hex(16)
directory=Path(app.config['DATABASE']).parent/'imports'
directory.mkdir(exist_ok=True)
name=secure_filename(file.filename) or 'previous-report.xlsx'
preview.update(filename=name,key=key)
(directory/(key+'.xlsx')).write_bytes(content)
(directory/(key+'.json')).write_text(json.dumps(preview),encoding='utf-8')
session['pending_import']=key
db().commit()
return redirect(url_for('setup'))
if operation not in ('confirm','sample'):
abort(400)
if operation=='confirm' and not preview:
raise ValueError('Upload the previous report first.')
try:
meeting_date=date.fromisoformat(request.form.get('meeting_date',''))
report_date=date.fromisoformat(request.form.get('report_date','')) if operation=='confirm' else date(2026,9,21)
except ValueError:
raise ValueError('Enter valid previous and upcoming meeting dates.') from None
if meeting_date.weekday()!=0 or report_date.weekday()!=0:
raise ValueError('Both meeting dates must be Mondays. Use the actual date if the filename is old.')
if meeting_date<=report_date:
raise ValueError('The upcoming meeting must be after the previous report.')
coordinator=db().execute('SELECT * FROM users WHERE id=? AND active=1 AND rotation_order IS NOT NULL',(request.form.get('coordinator_id'),)).fetchone()
if not coordinator:
raise ValueError('Choose the coordinator for the upcoming meeting.')
current=db().execute("SELECT * FROM meetings WHERE status='active'").fetchone()
existing=db().execute('SELECT * FROM meetings WHERE meeting_date=? AND id!=?',(meeting_date.isoformat(),current['id'])).fetchone()
if existing:
raise ValueError('A historical meeting already uses the upcoming date. Choose a later Monday.')
if db().execute('SELECT 1 FROM updates WHERE meeting_id=? UNION SELECT 1 FROM actions WHERE meeting_id=?',(current['id'],current['id'])).fetchone():
raise ValueError('Setup cannot replace the checklist after people have started entering updates.')
db().execute('UPDATE meetings SET meeting_date=? WHERE id=?',(meeting_date.isoformat(),current['id']))
if operation=='confirm':
mappings={}
for index,name in enumerate(preview['owners']):
value=request.form.get(f'owner_{index}','')
user=db().execute('SELECT * FROM users WHERE id=?',(value,)).fetchone()
if value=='new':
username=secure_filename(name).lower().replace(' ','_') or 'participant'
username=username[:50]+'_'+secrets.token_hex(3)
report_position=db().execute('SELECT COALESCE(MAX(report_order),0)+1 FROM users').fetchone()[0]
uid=db().execute('INSERT INTO users(name,username,password_hash,active,rotation_order,report_order) VALUES(?,?,?,0,NULL,?)',(name[:100],username,generate_password_hash(DEFAULT_PASSWORD),report_position)).lastrowid
elif user:
uid=user['id']
else:
raise ValueError(f'Choose the matching person for {name}.')
mappings[name]=uid
# Sample reports are only baseline data until this first-run confirmation.
db().execute('DELETE FROM reviews WHERE meeting_id=?',(current['id'],))
db().execute('UPDATE actions SET archived=1')
collision=db().execute('SELECT * FROM meetings WHERE meeting_date=? AND id!=?',(report_date.isoformat(),current['id'])).fetchone()
if collision:
if not collision['source_file']:
raise ValueError('A meeting already exists for the previous report date.')
mid=collision['id']
db().execute('DELETE FROM reviews WHERE action_id IN (SELECT id FROM actions WHERE meeting_id=?)',(mid,))
db().execute('DELETE FROM updates WHERE meeting_id=?',(mid,))
db().execute('DELETE FROM actions WHERE meeting_id=?',(mid,))
db().execute('DELETE FROM submissions WHERE meeting_id=?',(mid,))
else:
mid=db().execute('INSERT INTO meetings(meeting_date,title,location,status) VALUES(?,?,?,?)',(report_date.isoformat(),preview['title'],preview['location'],'closed')).lastrowid
db().execute('UPDATE meetings SET title=?,location=?,presenter=?,source_file=?,minutes_by=? WHERE id=?',
(preview['title'],preview['location'],preview['presenter'],'upload:'+preview['key']+'.xlsx','Imported report',mid))
for name,uid in mappings.items():
db().execute('INSERT OR REPLACE INTO report_owner_aliases(meeting_id,source_name,user_id) VALUES(?,?,?)',(mid,name,uid))
for update in preview['updates']:
db().execute('INSERT INTO updates(meeting_id,user_id,body) VALUES(?,?,?)',(mid,mappings[update['owner']],update['body']))
for action in preview['actions']:
db().execute('INSERT INTO actions(meeting_id,user_id,body,due_date,due_note,completed) VALUES(?,?,?,?,?,?)',
(mid,mappings[action['owner']],action['body'],action['due_date'],action['due_note'],int(action['completed'])))
for uid in set(mappings.values()):
db().execute('INSERT INTO submissions(meeting_id,user_id,reviewed,submitted_at) VALUES(?,?,1,?)',(mid,uid,report_date.isoformat()+' 00:00:00'))
db().execute('INSERT INTO reviews(meeting_id,action_id) SELECT ?,id FROM actions WHERE meeting_id=? AND completed=0',(current['id'],mid))
db().execute('UPDATE meetings SET meeting_date=?,coordinator_id=?,minutes_by=? WHERE id=?',(meeting_date.isoformat(),coordinator['id'],coordinator['name'],current['id']))
db().execute("INSERT INTO metadata(key,value) VALUES('setup_complete','1')")
db().commit()
session.pop('pending_import',None)
flash('Setup complete. Previous actions are ready for the team and this week’s report coordinator.','success')
return redirect(url_for('dashboard'))
except ValueError as error:
db().rollback()
flash(str(error),'error')
current=db().execute("SELECT * FROM meetings WHERE status='active'").fetchone()
mapping={name:suggest_owner(name,users) for name in preview['owners']} if preview else {}
return render_template('setup.html',preview=preview,users=users,mapping=mapping,meeting=current)
def register_resume(app,db,admin_only):
def pending_resume():
key=session.get('pending_resume','')
if not re.fullmatch('[a-f0-9]{32}',key):
return None
path=Path(app.config['DATABASE']).parent/'imports'/(key+'.json')
return json.loads(path.read_text(encoding='utf-8')) if path.exists() else None
@app.route('/admin/resume',methods=['GET','POST'])
@admin_only
def resume_coordination():
users=db().execute('SELECT * FROM users WHERE archived=0 ORDER BY name').fetchall()
preview=pending_resume()
current_meeting=db().execute("SELECT * FROM meetings WHERE status='active'").fetchone()
if request.method=='POST':
try:
operation=request.form.get('operation')
if operation=='upload':
file=request.files.get('report')
if not file or not file.filename.lower().endswith('.xlsx'):
raise ValueError('Select an Excel .xlsx MOM report.')
content=file.read(10*1024*1024+1)
if len(content)>10*1024*1024:
raise ValueError('The workbook must be 10 MB or smaller.')
preview=parse_report(content)
key=secrets.token_hex(16)
directory=Path(app.config['DATABASE']).parent/'imports'
directory.mkdir(exist_ok=True)
name=secure_filename(file.filename) or 'previous-report.xlsx'
preview.update(filename=name,key=key)
(directory/(key+'.xlsx')).write_bytes(content)
(directory/(key+'.json')).write_text(json.dumps(preview),encoding='utf-8')
session['pending_resume']=key
db().commit()
flash('Excel file uploaded and parsed successfully. Confirm report details and member mappings below.','info')
return redirect(url_for('resume_coordination'))
elif operation=='cancel':
session.pop('pending_resume',None)
flash('Resume operation cancelled.','info')
return redirect(url_for('admin'))
elif operation=='confirm':
if not preview:
raise ValueError('Upload the previous Excel report first.')
try:
report_date=date.fromisoformat(request.form.get('report_date',''))
meeting_date=date.fromisoformat(request.form.get('meeting_date',''))
except ValueError:
raise ValueError('Enter valid previous and upcoming meeting dates.') from None
if meeting_date.weekday()!=0 or report_date.weekday()!=0:
raise ValueError('Both meeting dates must be Mondays.')
if meeting_date<=report_date:
raise ValueError('The upcoming meeting must be after the previous report.')
coordinator=db().execute('SELECT * FROM users WHERE id=? AND active=1 AND archived=0',
(request.form.get('coordinator_id'),)).fetchone()
if not coordinator:
raise ValueError('Choose the coordinator for the upcoming meeting.')
mappings={}
for index,name in enumerate(preview['owners']):
value=request.form.get(f'owner_{index}','')
user=db().execute('SELECT * FROM users WHERE id=? AND archived=0',(value,)).fetchone()
if value=='new':
username=secure_filename(name).lower().replace(' ','_') or 'participant'
username=username[:40]+'_'+secrets.token_hex(3)
report_pos=db().execute('SELECT COALESCE(MAX(report_order),0)+1 FROM users').fetchone()[0]
uid=db().execute(
'INSERT INTO users(name,username,password_hash,active,rotation_order,report_order) VALUES(?,?,?,1,NULL,?)',
(name[:100],username,generate_password_hash(DEFAULT_PASSWORD),report_pos)
).lastrowid
elif user:
uid=user['id']
else:
raise ValueError(f'Choose the matching person for {name}.')
mappings[name]=uid
db().execute("UPDATE meetings SET status='closed' WHERE status='active'")
collision=db().execute('SELECT * FROM meetings WHERE meeting_date=?',(report_date.isoformat(),)).fetchone()
if collision:
mid=collision['id']
db().execute('DELETE FROM reviews WHERE action_id IN (SELECT id FROM actions WHERE meeting_id=?)',(mid,))
db().execute('DELETE FROM reviews WHERE meeting_id=?',(mid,))
db().execute('DELETE FROM updates WHERE meeting_id=?',(mid,))
db().execute('DELETE FROM actions WHERE meeting_id=?',(mid,))
db().execute('DELETE FROM submissions WHERE meeting_id=?',(mid,))
db().execute('DELETE FROM report_owner_aliases WHERE meeting_id=?',(mid,))
db().execute(
"UPDATE meetings SET title=?,location=?,presenter=?,source_file=?,status='closed',minutes_by=? WHERE id=?",
(preview['title'],preview['location'],preview['presenter'],'upload:'+preview['key']+'.xlsx','Imported report',mid)
)
else:
mid=db().execute(
"INSERT INTO meetings(meeting_date,title,location,presenter,status,source_file,minutes_by) VALUES(?,?,?,?,?,?,?)",
(report_date.isoformat(),preview['title'],preview['location'],preview['presenter'],'closed','upload:'+preview['key']+'.xlsx','Imported report')
).lastrowid
for name,uid in mappings.items():
db().execute('INSERT OR REPLACE INTO report_owner_aliases(meeting_id,source_name,user_id) VALUES(?,?,?)',(mid,name,uid))
for update in preview['updates']:
db().execute('INSERT INTO updates(meeting_id,user_id,body) VALUES(?,?,?)',(mid,mappings[update['owner']],update['body']))
for action in preview['actions']:
db().execute('INSERT INTO actions(meeting_id,user_id,body,due_date,due_note,completed) VALUES(?,?,?,?,?,?)',
(mid,mappings[action['owner']],action['body'],action['due_date'],action['due_note'],int(action['completed'])))
for uid in set(mappings.values()):
db().execute('INSERT OR REPLACE INTO submissions(meeting_id,user_id,reviewed,submitted_at) VALUES(?,?,1,?)',
(mid,uid,report_date.isoformat()+' 00:00:00'))
upcoming_collision=db().execute('SELECT * FROM meetings WHERE meeting_date=?',(meeting_date.isoformat(),)).fetchone()
if upcoming_collision:
active_mid=upcoming_collision['id']
db().execute(
"UPDATE meetings SET title=?,location=?,presenter='',status='active',coordinator_id=?,minutes_by=? WHERE id=?",
(preview['title'],preview['location'],coordinator['id'],coordinator['name'],active_mid)
)
db().execute('DELETE FROM reviews WHERE meeting_id=?',(active_mid,))
else:
active_mid=db().execute(
"INSERT INTO meetings(meeting_date,title,location,presenter,minutes_by,status,coordinator_id) VALUES(?,?,?,?,?,?,?)",
(meeting_date.isoformat(),preview['title'],preview['location'],'',coordinator['name'],'active',coordinator['id'])
).lastrowid
db().execute(
"INSERT INTO reviews(meeting_id,action_id) "
"SELECT ?,a.id FROM actions a "
"JOIN users u ON u.id=a.user_id "
"WHERE a.meeting_id=? AND a.completed=0 AND a.archived=0 AND u.archived=0",
(active_mid,mid)
)
db().commit()
session.pop('pending_resume',None)
flash('Coordination resumed from uploaded Excel. Unfinished actions are ready for review.','success')
return redirect(url_for('coordinator'))
else:
abort(400)
except ValueError as error:
db().rollback()
flash(str(error),'error')
today=date.today()
days_ahead=(0-today.weekday())%7
if days_ahead==0:
days_ahead=7
default_meeting_date=(today+timedelta(days=days_ahead)).isoformat()
default_report_date=(today+timedelta(days=days_ahead-7)).isoformat()
mapping={name:suggest_owner(name,users) for name in preview['owners']} if preview else {}
open_actions_count=sum(1 for a in preview['actions'] if not a['completed']) if preview else 0
completed_actions_count=sum(1 for a in preview['actions'] if a['completed']) if preview else 0
return render_template(
'resume_excel.html',
preview=preview,
users=users,
mapping=mapping,
meeting=current_meeting,
default_meeting_date=default_meeting_date,
default_report_date=default_report_date,
open_actions_count=open_actions_count,
completed_actions_count=completed_actions_count
)