Files
Piotr ChojnackiandClaude Opus 5.5 628a78d7d1 Demo build: publish the console's ui/ package with the page
index.html links ui/v1/tokens.css document-relatively, and tokens.css loads the Inter font
next to it, but build_demo.py copied only the brand assets into _site. The published demo
therefore got a 404 for both (checked against the live site on 2026-11-21) and rendered with
neither the shared tokens nor the font. It now copies frontend/ui/ into the output as well,
the font's licence included.

Checked: a build into an empty directory and a second one over it both succeed, and the
served demo answers 200 for tokens.css and InterVariable.woff2, with the body in Inter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 23:15:32 +01:00

269 lines
20 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Build the public live-demo page = frontend/index.html + a seeded mock-API layer (no backend).
Usage: python scripts/build_demo.py [outdir] (default outdir: _site)
Run from the repo root. Writes <outdir>/index.html (+ .nojekyll, the brand assets and the
console's ui/ package) for GitHub Pages.
The real frontend/index.html is never modified."""
import os
import shutil
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "frontend", "index.html")
OUTDIR = sys.argv[1] if len(sys.argv) > 1 else "_site"
html = open(SRC, encoding="utf-8").read()
# ── Social preview (Open Graph + Twitter Card) + apple-touch-icon — demo build only ──
# Crawlers (Telegram, Slack, X, Facebook, …) need ABSOLUTE image/URL paths and won't run
# JS, so the card must be static <head> markup. Netlify exposes $URL (the site's primary
# address) at build time; fall back to the known demo URL for local builds. The real
# frontend/index.html stays domain-agnostic — these tags live only in the published demo.
BASE = (os.environ.get("URL") or "https://super-lamington-4749f7.netlify.app").rstrip("/")
DESC = ("Self-hosted, single-tenant questionnaire and scoring engine for evaluating outside "
"counsel — live interactive demo (seeded sample data, no backend).")
HEAD_EXTRA = f"""
<meta name="description" content="{DESC}" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Counsel Scorecard" />
<meta property="og:title" content="Counsel Scorecard" />
<meta property="og:description" content="{DESC}" />
<meta property="og:url" content="{BASE}/" />
<meta property="og:image" content="{BASE}/og.png" />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:image:alt" content="Counsel Scorecard — self-hosted questionnaire and scoring engine" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Counsel Scorecard" />
<meta name="twitter:description" content="{DESC}" />
<meta name="twitter:image" content="{BASE}/og.png" />
<link rel="apple-touch-icon" href="{BASE}/icon.png" />
"""
hmark = "</head>"
assert html.count(hmark) >= 1, "no </head> in source"
html = html.replace(hmark, HEAD_EXTRA + hmark, 1)
MOCK = r"""
<script>
/* ===== DEMO MODE — seeded sample data, no backend. For screenshots only; not part of the app. ===== */
(function(){
var ME={id:'u-admin',email:'admin@counsel.example',full_name:'Avery Admin',role:'legal_ops',is_moderator:true,is_active:true};
var OPTS5=[{id:'a1',value:1,label:'Poor',display_order:1},{id:'a2',value:2,label:'Below expectations',display_order:2},{id:'a3',value:3,label:'Average',display_order:3},{id:'a4',value:4,label:'Good',display_order:4},{id:'a5',value:5,label:'Exemplary',display_order:5}];
var ENUMS={
firm_status:['active','inactive','blacklisted'],
matter_status:['open','in_progress','closed','cancelled'],
matter_type:['transactional','advisory','litigation','regulatory'],
complexity_band:['routine','standard','complex'],
value_band:['lt_50k','50k_250k','250k_1m','1m_10m','gt_10m'],
user_role:['legal_ops','matter_owner','viewer'],
questionnaire_status:['draft','active','archived'],
response_status:['draft','submitted','locked'],
ranking_status:['top_performer','solid','watch','at_risk','provisional','remove_candidate'],
answer_type:['scale','single_choice','boolean','numeric','text'],
question_category:['qualitative','quantitative']
};
var PAS=[{id:'pa1',code:'MA',label:'M&A'},{id:'pa2',code:'LIT',label:'Litigation'},{id:'pa3',code:'IP',label:'Intellectual Property'},{id:'pa4',code:'EMP',label:'Employment'},{id:'pa5',code:'REG',label:'Regulatory'}];
var JURS=[{id:'j1',code:'US-NY',label:'New York'},{id:'j2',code:'US-DE',label:'Delaware'},{id:'j3',code:'UK',label:'United Kingdom'},{id:'j4',code:'DE',label:'Germany'}];
var FIRMS=[
{id:'f1',name:'Sterling & Cooper LLP',legal_name:'Sterling Cooper LLP',status:'active',website:'https://sterlingcooper.example'},
{id:'f2',name:'Wachtell Brooks',legal_name:'Wachtell Brooks LLP',status:'active',website:'https://wbrooks.example'},
{id:'f3',name:'Hale & Dorr Partners',legal_name:'Hale Dorr Partners LLP',status:'active',website:''},
{id:'f4',name:'Greenfield Legal',legal_name:'Greenfield Legal GmbH',status:'inactive',website:''},
{id:'f5',name:'Crane, Poole & Schmidt',legal_name:'Crane Poole Schmidt',status:'blacklisted',website:''}
];
var USERS=[
{id:'u-admin',email:'admin@counsel.example',full_name:'Avery Admin',role:'legal_ops',is_moderator:true,is_active:true},
{id:'u-ops',email:'lee.ops@counsel.example',full_name:'Lee Operations',role:'legal_ops',is_moderator:false,is_active:true},
{id:'u-own',email:'morgan.owner@counsel.example',full_name:'Morgan Owner',role:'matter_owner',is_moderator:false,is_active:true},
{id:'u-view',email:'sam.viewer@counsel.example',full_name:'Sam Viewer',role:'viewer',is_moderator:false,is_active:false}
];
var MATTERS=[
{id:'m1',reference:'M-2026-001',title:'Acquisition of NorthStar Tech',firm_id:'f1',practice_area_id:'pa1',jurisdiction_id:'j2',matter_type:'transactional',complexity_band:'complex',status:'closed',billing_method:'fixed_fee',budget_estimate:'250000.00',budget_currency:'USD'},
{id:'m2',reference:'M-2026-002',title:'Patent dispute - Acme v. Globex',firm_id:'f2',practice_area_id:'pa3',jurisdiction_id:'j1',matter_type:'litigation',complexity_band:'complex',status:'in_progress',billing_method:'hourly_rate',budget_estimate:'450.00',budget_currency:'USD'},
{id:'m3',reference:'M-2026-003',title:'GDPR compliance review',firm_id:'f3',practice_area_id:'pa5',jurisdiction_id:'j4',matter_type:'regulatory',complexity_band:'standard',status:'open',billing_method:'other',billing_notes:'Capped monthly retainer'},
{id:'m4',reference:'M-2026-004',title:'Executive employment agreements',firm_id:'f1',practice_area_id:'pa4',jurisdiction_id:'j1',matter_type:'advisory',complexity_band:'routine',status:'closed',billing_method:'fixed_fee',budget_estimate:'40000.00',budget_currency:'USD'},
{id:'m5',reference:'M-2026-005',title:'Series C financing',firm_id:'f2',practice_area_id:'pa1',jurisdiction_id:'j2',matter_type:'transactional',complexity_band:'complex',status:'closed',billing_method:'hourly_rate',budget_estimate:'700.00',budget_currency:'USD'},
{id:'m6',reference:'M-2026-006',title:'Trademark portfolio audit',firm_id:'f3',practice_area_id:'pa3',jurisdiction_id:'j3',matter_type:'advisory',complexity_band:'standard',status:'open'}
];
/* The 6 canonical criteria (counsel review 2026-07-02) — mirrors backend/app/seed.py:
4 qualitative 1-5 anchors + 2 quantitative percent questions (0-100). */
var QS=[
{id:'q1',key:'quality_of_advice',label:'Quality of advice',category:'qualitative',answer_type:'scale',scale_min:1,scale_max:5,options:OPTS5},
{id:'q2',key:'responsiveness',label:'Responsiveness',category:'qualitative',answer_type:'scale',scale_min:1,scale_max:5,options:OPTS5},
{id:'q4',key:'scope_control',label:'Scope compliance',category:'qualitative',answer_type:'scale',scale_min:1,scale_max:5,options:OPTS5},
{id:'q5',key:'commerciality',label:'Business awareness',category:'qualitative',answer_type:'scale',scale_min:1,scale_max:5,options:OPTS5},
{id:'q6',key:'budget_adherence',label:'Budget adherence',category:'quantitative',answer_type:'numeric',scale_min:0,scale_max:100,options:[]},
{id:'q7',key:'billing_hygiene',label:'Billing accuracy',category:'quantitative',answer_type:'numeric',scale_min:0,scale_max:100,options:[]}
];
var QNNS=[{id:'qn1',key:'counsel_evaluation',title:'Counsel Evaluation',version:1,status:'active',description:'Standard evaluation form completed after a matter closes.',items:[
{question_id:'q1',weight:0.3,display_order:1},{question_id:'q2',weight:0.2,display_order:2},{question_id:'q4',weight:0.15,display_order:3},{question_id:'q5',weight:0.1,display_order:4},
{question_id:'q6',weight:0.15,display_order:5},{question_id:'q7',weight:0.1,display_order:6}
]}];
var CYCLES=[
{id:'c1',name:'Q1 2026 Review',start_date:'2026-01-01',end_date:'2026-03-31',min_evaluations:3,status:'closed'},
{id:'c2',name:'Q2 2026 Review',start_date:'2026-04-01',end_date:'2026-06-30',min_evaluations:3,status:'open'}
];
var SNAPS={c1:[
{firm_id:'f2',composite_score:92,data_completeness:1.0,evaluation_count:6,ranking_status:'top_performer'},
{firm_id:'f1',composite_score:84,data_completeness:0.9,evaluation_count:5,ranking_status:'solid'},
{firm_id:'f3',composite_score:71,data_completeness:0.8,evaluation_count:4,ranking_status:'watch'},
{firm_id:'f4',composite_score:58,data_completeness:0.6,evaluation_count:3,ranking_status:'at_risk'},
{firm_id:'f5',composite_score:0,data_completeness:0.0,evaluation_count:1,ranking_status:'provisional'}
]};
/* Real scoring, mirroring backend present_i (services/scoring.py): weighted mean of answers
normalized onto the 1-5 band (percent 0-100 → 1-5), ×20 → 0-100. No more canned "88". */
function _score(qnId,items){
var qn=null; QNNS.forEach(function(x){ if(x.id===qnId) qn=x; });
if(!qn||!qn.items||!qn.items.length) return null;
var w={}; qn.items.forEach(function(it){ w[it.question_id]=Number(it.weight)||0; });
var qById={}; QS.forEach(function(q){ qById[q.id]=q; });
var num=0,den=0;
(items||[]).forEach(function(it){
var q=qById[it.question_id]; var wt=w[it.question_id]||0; if(!q||wt<=0) return;
var v=null;
if(it.numeric_value!=null&&it.numeric_value!=='') v=Number(it.numeric_value);
else if(it.answer_option_id){ (q.options||[]).forEach(function(o){ if(o.id===it.answer_option_id) v=Number(o.value); }); }
if(v==null||isNaN(v)) return;
if(!(q.scale_min===1&&q.scale_max===5)) v=(q.scale_max===q.scale_min)?3:1+4*(v-q.scale_min)/(q.scale_max-q.scale_min);
num+=wt*v; den+=wt;
});
if(!den) return null;
return Math.round(num/den*20*100)/100;
}
/* Seeded evaluations + append-only revision history (counsel review 2026-07-02: submitted
scores were invisible — no list, no per-firm history, empty "Show history"). */
var REVS={};
var RESPONSES=[
{id:'r-s1',questionnaire_id:'qn1',matter_id:'m1',firm_id:'f1',review_cycle_id:'c1',status:'submitted',recommend:true,is_constrained:false,overall_comment:'Strong M&A execution, minor delays on closing docs.',submitted_at:'2026-06-21T09:30:00Z',created_at:'2026-06-20T16:12:00Z',items:[
{question_id:'q1',answer_option_id:'a4'},{question_id:'q2',answer_option_id:'a5'},{question_id:'q4',answer_option_id:'a4'},{question_id:'q5',answer_option_id:'a3'},{question_id:'q6',numeric_value:85},{question_id:'q7',numeric_value:90}]},
{id:'r-s2',questionnaire_id:'qn1',matter_id:'m4',firm_id:'f1',review_cycle_id:'c2',status:'submitted',recommend:true,is_constrained:false,overall_comment:'Solid, pragmatic employment advice.',submitted_at:'2026-05-12T14:05:00Z',created_at:'2026-05-12T13:40:00Z',items:[
{question_id:'q1',answer_option_id:'a4'},{question_id:'q2',answer_option_id:'a3'},{question_id:'q4',answer_option_id:'a4'},{question_id:'q5',answer_option_id:'a4'},{question_id:'q6',numeric_value:70},{question_id:'q7',numeric_value:80}]},
{id:'r-s3',questionnaire_id:'qn1',matter_id:'m5',firm_id:'f2',review_cycle_id:'c1',status:'submitted',recommend:true,is_constrained:false,overall_comment:'Benchmark-level financing work.',submitted_at:'2026-03-18T11:00:00Z',created_at:'2026-03-17T09:20:00Z',items:[
{question_id:'q1',answer_option_id:'a5'},{question_id:'q2',answer_option_id:'a4'},{question_id:'q4',answer_option_id:'a5'},{question_id:'q5',answer_option_id:'a4'},{question_id:'q6',numeric_value:90},{question_id:'q7',numeric_value:95}]},
{id:'r-s4',questionnaire_id:'qn1',matter_id:'m2',firm_id:'f2',review_cycle_id:'c2',status:'draft',recommend:null,is_constrained:false,overall_comment:null,submitted_at:null,created_at:'2026-06-28T10:45:00Z',items:[
{question_id:'q1',answer_option_id:'a3'},{question_id:'q2',answer_option_id:'a4'}]},
{id:'r-s5',questionnaire_id:'qn1',matter_id:'m6',firm_id:'f3',review_cycle_id:'c2',status:'submitted',recommend:false,is_constrained:false,overall_comment:'Scope drift on the audit; invoices needed corrections.',submitted_at:'2026-06-25T08:15:00Z',created_at:'2026-06-24T17:50:00Z',items:[
{question_id:'q1',answer_option_id:'a3'},{question_id:'q2',answer_option_id:'a4'},{question_id:'q4',answer_option_id:'a3'},{question_id:'q5',answer_option_id:'a3'},{question_id:'q6',numeric_value:60},{question_id:'q7',numeric_value:75}]}
];
RESPONSES.forEach(function(r){
r.score=_score(r.questionnaire_id,r.items); r.revision=1;
REVS[r.id]=[{revision_no:1,change_reason:r.status==='submitted'?'submit':'draft',snapshot:{score:r.score,status:r.status},created_at:r.submitted_at||r.created_at}];
});
/* r-s1 carries a two-step history so "Show history" has something real to show. */
REVS['r-s1'].unshift({revision_no:2,change_reason:'submit',snapshot:{score:RESPONSES[0].score,status:'submitted'},created_at:'2026-06-21T09:30:00Z'});
REVS['r-s1'][1].change_reason='draft'; REVS['r-s1'][1].snapshot={score:79.6,status:'draft'};
RESPONSES[0].revision=2;
function searchHits(q){
q=(q||'').toLowerCase();
var all=[].concat(
FIRMS.map(function(f){return {type:'firm',id:f.id,title:f.name,rank:0.92};}),
MATTERS.map(function(m){return {type:'matter',id:m.id,title:m.reference+' - '+m.title,rank:0.81};}),
QS.map(function(x){return {type:'question',id:x.id,title:x.label,rank:0.64};})
);
if(!q) return all.slice(0,6);
return all.filter(function(h){return h.title.toLowerCase().indexOf(q)>=0;}).slice(0,8);
}
function GET(path){
var p=path.split('?')[0];
if(p==='/config') return {shares_identity:false};
if(p==='/auth/me') return ME;
if(p==='/enums') return ENUMS;
if(p==='/practice-areas') return PAS;
if(p==='/jurisdictions') return JURS;
if(p==='/firms') return FIRMS;
if(p==='/matters') return MATTERS;
if(p==='/questionnaires') return QNNS;
if(p==='/questions') return QS;
if(p==='/review-cycles') return CYCLES;
if(p==='/users') return USERS;
if(p==='/responses'){
var qp={}; (path.split('?')[1]||'').split('&').forEach(function(kv){ if(!kv) return; var i=kv.indexOf('='); if(i<0) return; qp[decodeURIComponent(kv.slice(0,i))]=decodeURIComponent(kv.slice(i+1)); });
return RESPONSES.filter(function(r){
if(qp.firm_id&&r.firm_id!==qp.firm_id) return false;
if(qp.matter_id&&r.matter_id!==qp.matter_id) return false;
if(qp.status&&r.status!==qp.status) return false;
return true; });
}
if(p.indexOf('/responses/')===0 && p.indexOf('/history')>0) return REVS[p.split('/')[2]]||[];
if(p.indexOf('/review-cycles/')===0 && p.indexOf('/snapshots')>0){ return SNAPS[p.split('/')[2]]||[]; }
if(p.indexOf('/search')===0){ var q='',qi=path.indexOf('q='); if(qi>=0){ q=decodeURIComponent(path.slice(qi+2).split('&')[0]); } return {hits:searchHits(q)}; }
if(p.indexOf('/history')>0) return [];
return {};
}
var _id=100;
function _newId(base){ return ((base||'/x').replace(/[^a-z]/gi,'')||'demo')+'-'+(++_id); }
var COLLS={'/firms':FIRMS,'/matters':MATTERS,'/questions':QS,'/questionnaires':QNNS,'/users':USERS,'/review-cycles':CYCLES};
function _match(p){ for(var base in COLLS){ if(p===base) return {arr:COLLS[base],base:base,id:null}; if(p.indexOf(base+'/')===0) return {arr:COLLS[base],base:base,id:p.slice(base.length+1)}; } return null; }
function _findIx(arr,id){ for(var i=0;i<arr.length;i++){ if(arr[i].id===id) return i; } return -1; }
function _enrich(base,it){
if(base==='/firms'){ if(!it.status) it.status='active'; }
else if(base==='/matters'){ if(!it.status) it.status='open'; }
else if(base==='/users'){ if(it.is_active===undefined) it.is_active=true; }
else if(base==='/questionnaires'){ if(!it.status) it.status='active'; if(!it.version) it.version=1; if(!it.items) it.items=[]; }
else if(base==='/review-cycles'){ if(!it.status) it.status='open'; }
}
// Demo persistence: POST/PATCH/DELETE mutate the in-memory arrays so created/edited rows
// actually appear on the next GET (data resets on page reload). Mirrors the real API shape.
window.api=function(method,path,body){
var p=path.split('?')[0], out;
var mDeact=p.match(/^\/users\/(.+)\/deactivate$/), mClose=p.match(/^\/review-cycles\/(.+)\/close$/);
if(method==='GET') out=GET(path);
else if(p.indexOf('/responses')===0 && p.indexOf('/history')<0){
/* Create-or-update like the real service: one response per questionnaire+matter, score
computed from the actual answers, and every save appends a revision to the history. */
var b=body||{}; var bm=b.matter_id||null;
var mtr=null; MATTERS.forEach(function(x){ if(x.id===bm) mtr=x; });
var rex=null; RESPONSES.forEach(function(x){ if(x.questionnaire_id===b.questionnaire_id&&x.matter_id===bm) rex=x; });
var r=rex||{id:_newId('r'),questionnaire_id:b.questionnaire_id,matter_id:bm,is_constrained:false,created_at:new Date().toISOString(),revision:0};
r.firm_id=mtr?mtr.firm_id:null;
r.review_cycle_id=mtr?(b.review_cycle_id||null):null;
r.recommend=(b.recommend===undefined)?null:b.recommend;
r.overall_comment=b.overall_comment||null;
r.items=b.items||[];
r.score=_score(b.questionnaire_id,r.items);
r.status=b.submit?'submitted':'draft';
if(b.submit) r.submitted_at=new Date().toISOString();
r.revision=(r.revision||0)+1;
if(!rex) RESPONSES.push(r);
(REVS[r.id]=REVS[r.id]||[]).unshift({revision_no:r.revision,change_reason:b.submit?'submit':'draft',snapshot:{score:r.score,status:r.status},created_at:new Date().toISOString()});
out={id:r.id,score:r.score,status:r.status};
}
else if(mDeact){ var du=_findIx(USERS,mDeact[1]); if(du>=0) USERS[du].is_active=false; out=du>=0?USERS[du]:{}; }
else if(mClose){ var dc=_findIx(CYCLES,mClose[1]); if(dc>=0) CYCLES[dc].status='closed'; out=SNAPS[mClose[1]]||[]; }
else {
var m=_match(p);
if(m && method==='POST' && m.id===null){ out={}; for(var k in (body||{})) out[k]=body[k]; out.id=out.id||_newId(m.base); _enrich(m.base,out); m.arr.push(out); }
else if(m && (method==='PATCH'||method==='PUT') && m.id){ var ux=_findIx(m.arr,m.id); if(ux>=0){ for(var k2 in (body||{})) m.arr[ux][k2]=body[k2]; out=m.arr[ux]; } else out={}; }
else if(m && method==='DELETE' && m.id){ var dx=_findIx(m.arr,m.id); if(dx>=0) m.arr.splice(dx,1); out={}; }
else { out={}; for(var k3 in (body||{})) out[k3]=body[k3]; out.id=_newId('demo'); }
}
try{ if(typeof log==='function') log(method+' '+path+' -> 200 (demo)', out); }catch(e){}
return Promise.resolve(out);
};
// The real boot may have already called restore() with the original api (which 404s on a backend-less
// static server); neutralize showLogin so that late rejection can't flip back to the login screen.
window.showLogin=function(){};
try{ state.token='demo'; }catch(e){}
if(typeof restore==='function') restore();
})();
</script>
"""
marker = "</body>"
assert html.count(marker) >= 1, "no </body> in source"
# insert before the LAST </body>
idx = html.rfind(marker)
out = html[:idx] + MOCK + "\n" + html[idx:]
os.makedirs(OUTDIR, exist_ok=True)
open(os.path.join(OUTDIR, "index.html"), "w", encoding="utf-8").write(out)
open(os.path.join(OUTDIR, ".nojekyll"), "w").close()
# Brand assets referenced by the social-preview <head> tags above (absolute URLs).
for asset in ("og.png", "icon.png"):
shutil.copyfile(os.path.join(ROOT, "assets", asset), os.path.join(OUTDIR, asset))
# The family's shared design package, which index.html links document-relatively
# (ui/v1/tokens.css, and through it the Inter font). Without it the published demo gets a 404 for
# both and renders with neither the tokens nor the font.
shutil.copytree(os.path.join(ROOT, "frontend", "ui"), os.path.join(OUTDIR, "ui"), dirs_exist_ok=True)
print(f"wrote {OUTDIR}/index.html ({len(out)} bytes) + .nojekyll + og.png + icon.png + ui/")