Files
Piotr ChojnackiandClaude Opus 5.5 f304faf06f Console a11y: the sidebar, row menus and dialogs work from the keyboard
A pass against the Web Interface Guidelines. The console could not be driven from the
keyboard at all:

- Every sidebar entry was a <div onclick>, which takes no focus, so a keyboard user could
  not reach a single screen. They are links now (href="#/<id>", aria-current on the
  current one; go() still closes the drawer), and a group heading is a button with
  aria-expanded. Same look: the links keep .nav-item's colour and no underline.
- A dialog is role=dialog + aria-modal, named by its title, starts on its first field,
  makes the page behind it inert (aria-modal alone does not stop Tab) and gives focus back
  to whatever opened it. The command palette does the same, and its input is labelled.
- The ⋯ row menu button is named ("Actions"/"Akcje"); opening it moves focus to its first
  item, Escape or Tab-ing out closes it, and focus returns to the button — so the Edit
  dialog an item opens hands focus back there as well.
- Icon-only buttons (sidebar toggle, request log, search, theme, the log's close) carry an
  aria-label; the EN/PL toggle's label is its localized tooltip.
- The sign-in error is role=alert; a skip link reaches the main content (tabindex=-1);
  prefers-reduced-motion switches transitions off.

New strings have I18N.pl entries (Skip to content, Close, Search). Checked in the demo
build (scripts/build_demo.py) with real key presses; test_smoke.py's frontend tripwires
re-checked by hand, and node --check on the inline script passes.

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

1358 lines
125 KiB
HTML
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.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Counsel Scorecard</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZmlsbD0iI2Y3NjcwNyIgZD0iTTE5IDJoLTE0YTMgMyAwIDAgMCAtMyAzdjE0YTMgMyAwIDAgMCAzIDNoMTRhMyAzIDAgMCAwIDMgLTN2LTE0YTMgMyAwIDAgMCAtMyAtM3oiLz48ZyBmaWxsPSJub25lIiBzdHJva2U9IiNmZmY0ZTYiIHN0cm9rZS13aWR0aD0iMi42IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEyIDEyKSBzY2FsZSguOCkgdHJhbnNsYXRlKC0xMiAtMTIpIj48cGF0aCBkPSJNMTYgMTdhMSAxIDAgMSAwIDIgMGExIDEgMCAxIDAgLTIgMCIvPjxwYXRoIGQ9Ik02IDdhMSAxIDAgMSAwIDIgMGExIDEgMCAxIDAgLTIgMCIvPjxwYXRoIGQ9Ik02IDE4bDEyIC0xMiIvPjwvZz48L3N2Zz4=" />
<script>/* set theme before first paint to avoid a flash */
(function(){try{var m=localStorage.getItem('cs_theme')||'system';
var dark=m==='dark'||(m==='system'&&window.matchMedia&&matchMedia('(prefers-color-scheme:dark)').matches);
document.documentElement.dataset.theme=dark?'dark':'light';}catch(e){}})();</script>
<link rel="stylesheet" href="ui/v1/tokens.css" />
<style>
:root{
/* The values are the family's (ui/v1/tokens.css, legalwork's look); this block maps Counsel's own
names onto them, so the rules below did not have to change. What stays Counsel's own: the link
accent, the status dots and badges, and the brand orange on the mark. */
--bg-app:var(--at-canvas); --bg-canvas:var(--at-chrome); --surface:var(--at-surface); --surface-muted:var(--at-surface-hover); --surface-muted-2:var(--at-active);
--surface-subtle:var(--at-surface-hover); --surface-chip:var(--at-active); --surface-code:var(--at-active); --row-hover:var(--at-hover);
--border:var(--at-border); --border-input:var(--at-border); --border-hover:var(--at-border-strong);
--text-primary:var(--at-text); --text-heading:var(--at-text); --text-secondary:var(--at-text-secondary); --text-muted:var(--at-text-muted); --text-faint:var(--at-text-faint); --text-on-primary:var(--at-primary-fg);
--primary:var(--at-primary); --primary-hover:var(--at-primary-hover); --primary-active:var(--at-primary-active); --primary-fg:var(--at-primary-fg);
--secondary-bg:var(--at-active); --secondary-fg:var(--at-text); --secondary-hover:var(--at-selected);
--accent-blue:#4263eb;
--info-bg:#edf2ff; --info-border:#bac8ff; --info-text:#364fc7; --info-icon:#4263eb; --info-code-bg:#dbe4ff;
--warning-bg:var(--at-warning-soft); --warning-border:transparent; --warning-label:var(--at-warning-text); --warning-text:var(--at-warning-text);
--dot-open:#4263eb; --dot-progress:#e67700; --dot-complete:#2f9e44; --dot-neutral:#868e96; --dot-danger:#e03131; --dot-special:#d6336c;
--badge-success-bg:#ebfbee; --badge-success-border:#b2f2bb; --badge-success-text:#2b8a3e;
--badge-active-bg:#ebfbee; --badge-active-border:#b2f2bb; --badge-active-text:#2b8a3e;
--badge-warn-bg:#fff9db; --badge-warn-border:#ffec99; --badge-warn-text:#d9480f;
--badge-danger-bg:#fff5f5; --badge-danger-border:#ffc9c9; --badge-danger-text:#c92a2a;
--badge-neutral-bg:var(--at-active); --badge-neutral-border:var(--at-border); --badge-neutral-text:var(--at-text-secondary);
--success:var(--at-success); --danger:var(--at-danger-text); --danger-hover-bg:var(--at-danger-soft); --danger-border:var(--at-danger-soft);
--ring-input:0 0 0 3px var(--at-focus-ring); --ring-input-border:var(--at-border-strong);
--font-sans:var(--at-font-sans); --font-mono:var(--at-font-mono);
--shadow-card:var(--at-shadow-xs); --shadow-menu:var(--at-shadow-pop); --shadow-login:var(--at-shadow-md); --shadow-dialog:var(--at-shadow-pop);
--sidebar-w:var(--at-sidebar-w); --sidebar-collapsed-w:72px; --topbar-h:var(--at-topbar-h); --content-pad:40px;
}
*{box-sizing:border-box;}
html,body{margin:0;}
html{font-family:var(--font-sans);font-size:14px;line-height:1.5;letter-spacing:var(--at-tracking-body);font-feature-settings:"cv11","ss01";color:var(--text-primary);background:var(--bg-app);-webkit-font-smoothing:antialiased;color-scheme:light;}
/* ── dark — Open Color dark theme: black canvas, gray-9 cards/sidebar, gray-3 primary (dark text),
translucent-white borders, indigo info, translucent Open Color status tints ── */
[data-theme="dark"]{
--accent-blue:#748ffc;
--info-bg:rgba(76,110,245,.15); --info-border:#364fc7; --info-text:#91a7ff; --info-icon:#5c7cfa; --info-code-bg:rgba(76,110,245,.25);
--dot-open:#5c7cfa; --dot-progress:#f59f00; --dot-complete:#40c057; --dot-neutral:#adb5bd; --dot-danger:#f03e3e; --dot-special:#e64980;
--badge-success-bg:rgba(64,192,87,.15); --badge-success-border:#2b8a3e; --badge-success-text:#8ce99a;
--badge-active-bg:rgba(64,192,87,.15); --badge-active-border:#2b8a3e; --badge-active-text:#8ce99a;
--badge-warn-bg:rgba(250,176,5,.15); --badge-warn-border:#d9480f; --badge-warn-text:#ffd43b;
--badge-danger-bg:rgba(250,82,82,.15); --badge-danger-border:#c92a2a; --badge-danger-text:#ffa8a8;
color-scheme:dark;
}
a{color:var(--accent-blue);text-decoration:none;} a:hover{text-decoration:underline;}
.hidden{display:none !important;}
.muted{color:var(--text-muted);} .faint{color:var(--text-faint);}
.mono{font-family:var(--font-mono);}
/* ── buttons ── */
.btn{display:inline-flex;align-items:center;gap:8px;height:36px;padding:0 16px;border-radius:var(--at-radius-lg);border:1px solid transparent;
font:500 14px/1 var(--font-sans);cursor:pointer;white-space:nowrap;background:transparent;color:var(--text-secondary);transition:background .12s,border-color .12s,filter .12s;}
.btn svg{width:16px;height:16px;flex:none;}
.btn.primary{background:var(--primary);color:var(--primary-fg);font-weight:500;} .btn.primary:hover{background:var(--primary-hover);} .btn.primary:active{background:var(--primary-active);}
.btn.secondary{background:var(--secondary-bg);color:var(--secondary-fg);} .btn.secondary:hover{background:var(--secondary-hover);}
.btn.ghost{border-color:var(--border);background:var(--surface);color:var(--text-secondary);} .btn.ghost:hover{background:var(--surface-muted);border-color:var(--border-hover);}
.btn.danger{border-color:var(--danger-border);color:var(--danger);background:var(--surface);} .btn.danger:hover{background:var(--danger-hover-bg);}
.btn.sm{height:30px;padding:0 10px;font-size:13px;}
.btn:disabled{opacity:.5;cursor:not-allowed;}
.btn.icon{width:32px;height:32px;padding:0;justify-content:center;border-color:var(--border);background:var(--surface);color:var(--text-secondary);}
.btn.icon:hover{background:var(--surface-muted);}
.btn:focus-visible{outline:2px solid var(--primary);outline-offset:2px;}
/* ── inputs ── */
label.field{display:flex;flex-direction:column;gap:6px;font:600 14px/1.3 var(--font-sans);color:var(--text-primary);}
label.field .req{color:var(--danger);}
input,select,textarea{font:400 14px/1.4 var(--font-sans);color:var(--text-primary);background:var(--surface);
border:1px solid var(--border-input);border-radius:8px;padding:8px 12px;height:36px;width:100%;transition:border-color .12s,box-shadow .12s;}
textarea{height:auto;min-height:84px;resize:vertical;}
input:hover,select:hover,textarea:hover{border-color:var(--border-hover);}
input:focus,select:focus,textarea:focus{outline:none;border-color:var(--ring-input-border);box-shadow:var(--ring-input);}
input::placeholder,textarea::placeholder{color:var(--text-muted);}
select{appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23868e96' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M6 9l6 6l6 -6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 10px center;padding-right:34px;cursor:pointer;}
.checkbox{display:inline-flex;align-items:center;gap:8px;font:400 14px/1 var(--font-sans);color:var(--text-secondary);cursor:pointer;}
.checkbox input{width:16px;height:16px;accent-color:var(--primary);}
/* ── badges / dots / chips ── */
.badge{display:inline-flex;align-items:center;gap:6px;padding:2px 9px;border-radius:9999px;font:500 12px/1.4 var(--font-sans);border:1px solid var(--badge-neutral-border);background:var(--badge-neutral-bg);color:var(--badge-neutral-text);}
.badge .dot{width:8px;height:8px;border-radius:9999px;background:var(--dot-neutral);flex:none;}
.badge.success{background:var(--badge-active-bg);border-color:var(--badge-active-border);color:var(--badge-active-text);}
.badge.warn{background:var(--badge-warn-bg);border-color:var(--badge-warn-border);color:var(--badge-warn-text);}
.badge.danger{background:var(--badge-danger-bg);border-color:var(--badge-danger-border);color:var(--badge-danger-text);}
.dot-open{background:var(--dot-open);} .dot-progress{background:var(--dot-progress);} .dot-complete{background:var(--dot-complete);}
.dot-neutral{background:var(--dot-neutral);} .dot-danger{background:var(--dot-danger);} .dot-special{background:var(--dot-special);}
.chip{display:inline-flex;align-items:center;gap:6px;padding:3px 9px;border-radius:6px;background:var(--surface-chip);border:1px solid var(--border);font-size:12px;color:var(--text-secondary);}
.avatar{width:24px;height:24px;border-radius:9999px;background:var(--surface-muted-2);color:var(--text-secondary);display:inline-flex;align-items:center;justify-content:center;font-size:10px;font-weight:600;}
/* ── card / panel ── */
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--at-radius-2xl);}
.card.pad{padding:24px;}
.card-head{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:18px 24px;border-bottom:1px solid var(--border);}
.card-head h2{margin:0;font:600 18px/1.3 var(--font-sans);color:var(--text-primary);}
.card-body{padding:24px;}
/* ── banners ── */
.banner{display:flex;gap:10px;align-items:flex-start;padding:11px 14px;border-radius:8px;border:1px solid var(--info-border);background:var(--info-bg);color:var(--info-text);font-size:13px;font-weight:500;}
.banner svg{width:16px;height:16px;flex:none;color:var(--info-icon);margin-top:1px;}
.banner.warn{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text);}
.banner.warn svg{color:var(--warning-label);}
.banner.err{background:var(--badge-danger-bg);border-color:var(--danger-border);color:var(--badge-danger-text);}
.banner.err svg{color:var(--danger);}
/* ── data table ── */
.toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 24px;}
.toolbar .search{position:relative;width:280px;max-width:50vw;}
.toolbar .search svg{position:absolute;left:10px;top:50%;transform:translateY(-50%);width:15px;height:15px;color:var(--text-muted);}
.toolbar .search input{padding-left:32px;height:36px;}
table.dt{width:100%;border-collapse:collapse;}
table.dt th{text-align:left;font:500 13px/1.3 var(--font-sans);color:var(--text-muted);padding:10px 16px;border-bottom:1px solid var(--border);white-space:nowrap;}
table.dt th.sorted{color:var(--text-primary);}
table.dt td{padding:13px 16px;border-bottom:1px solid var(--border);font-size:14px;vertical-align:middle;}
table.dt tbody tr:last-child td{border-bottom:0;}
table.dt tbody tr:hover{background:var(--row-hover);}
table.dt td.actions,table.dt th.actions{text-align:right;width:56px;}
table.dt .primary-cell{font-weight:500;color:var(--text-primary);}
table.dt .sub{display:block;color:var(--text-muted);font-size:12.5px;font-weight:400;}
.pager{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 24px;color:var(--text-muted);font-size:13px;}
.pager .pg{display:flex;align-items:center;gap:8px;}
.empty{padding:48px 24px;text-align:center;color:var(--text-muted);}
.iconbtn{display:inline-flex;width:28px;height:28px;align-items:center;justify-content:center;border-radius:6px;color:var(--text-muted);cursor:pointer;border:none;background:transparent;}
.iconbtn:hover{background:var(--surface-muted);color:var(--text-primary);}
.iconbtn svg{width:16px;height:16px;}
/* ── menu (overflow) ── */
.menu{position:fixed;z-index:60;min-width:160px;background:var(--surface);border:1px solid var(--border);border-radius:8px;box-shadow:var(--shadow-menu);padding:4px;}
.menu button{display:flex;width:100%;align-items:center;gap:8px;padding:7px 10px;border:0;background:transparent;border-radius:6px;font:400 13px/1 var(--font-sans);color:var(--text-secondary);cursor:pointer;text-align:left;}
.menu button:hover{background:var(--surface-muted);}
.menu button.danger{color:var(--danger);} .menu button.danger:hover{background:var(--danger-hover-bg);}
/* ── tabs ── */
.tabs{display:flex;gap:4px;border-bottom:1px solid var(--border);margin-bottom:20px;}
.tabs button{appearance:none;background:transparent;border:0;border-bottom:2px solid transparent;padding:10px 4px;margin-right:16px;font:500 14px/1 var(--font-sans);color:var(--text-muted);cursor:pointer;}
.tabs button.active{color:var(--text-primary);border-bottom-color:var(--primary);}
/* ── page header ── */
.page{padding:var(--content-pad);max-width:calc(var(--at-content-max) + 2 * var(--content-pad));margin:0 auto;width:100%;}
.page-head{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;margin-bottom:32px;flex-wrap:wrap;}
.page-head h1{margin:0;font:600 30px/1.2 var(--font-sans);letter-spacing:var(--at-tracking-title);color:var(--text-heading);}
.page-head .sub{color:var(--text-secondary);font-size:14px;margin-top:8px;}
.page-actions{display:flex;gap:8px;align-items:center;}
.kicker{font:600 11px/1 var(--font-sans);text-transform:uppercase;letter-spacing:.06em;color:var(--text-faint);margin-bottom:6px;}
/* ── form grid / sections ── */
.form-card{border-radius:12px;}
.form-section{padding:20px 24px;}
.form-section h3{margin:0 0 16px;font:600 16px/1.3 var(--font-sans);}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:16px;}
.grid2 .full{grid-column:1/-1;}
.form-foot{display:flex;justify-content:flex-end;gap:8px;padding:16px 24px;border-top:1px solid var(--border);}
/* ── field cards (detail) ── */
.fieldcards{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:12px;margin-bottom:20px;}
.fieldcard{border:1px solid var(--border);border-radius:10px;padding:14px 16px;position:relative;background:var(--surface);}
.fieldcard .lbl{font:600 11px/1 var(--font-sans);text-transform:uppercase;letter-spacing:.06em;color:var(--text-faint);margin-bottom:8px;}
.fieldcard .val{font-size:14px;color:var(--text-primary);}
/* ── widgets / dashboard ── */
.widgets{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px;}
.widget{border:1px solid var(--border);border-radius:10px;padding:16px;background:var(--surface);}
.widget h3{margin:0 0 2px;font:600 14px/1.3 var(--font-sans);}
.widget .wd-desc{color:var(--text-muted);font-size:13px;margin:0 0 12px;}
.metric{font:600 28px/1 var(--font-sans);letter-spacing:var(--at-tracking-title);color:var(--text-heading);}
.kv{display:flex;justify-content:space-between;padding:7px 0;border-top:1px solid var(--border);font-size:13px;}
.kv:first-of-type{border-top:0;} .kv .k{color:var(--text-muted);}
/* ── about page ── */
.about{max-width:720px;}
.about .card2{border:1px solid var(--border);border-radius:10px;padding:18px 20px;background:var(--surface);box-shadow:var(--shadow-card);margin-bottom:14px;}
.about h3{margin:0 0 8px;font:600 15px/1.3 var(--font-sans);color:var(--text-heading);}
.about p{margin:0 0 10px;color:var(--text-secondary);line-height:1.6;}
.about p:last-child{margin-bottom:0;}
.about ol,.about ul{margin:0;padding-left:20px;color:var(--text-secondary);line-height:1.6;}
.about li{margin:5px 0;}
.about a{color:var(--accent-blue);text-decoration:none;}
.about a:hover{text-decoration:underline;}
/* ── kanban ── */
.lanes{display:flex;gap:16px;overflow-x:auto;padding-bottom:8px;}
.lane{flex:0 0 280px;border:1px solid var(--border);border-radius:10px;background:var(--surface-subtle);}
.lane-head{padding:12px 14px;border-bottom:1px solid var(--border);}
.lane-head .nm{font-weight:600;font-size:14px;} .lane-head .ct{color:var(--text-muted);font-size:12px;}
.lane-body{padding:12px;display:flex;flex-direction:column;gap:10px;min-height:80px;}
.kcard{border:1px solid var(--border);border-radius:8px;background:var(--surface);padding:12px;box-shadow:var(--shadow-card);}
.kcard .kt{font-weight:600;font-size:13px;margin-bottom:8px;}
/* ── shell ── */
#app{display:flex;min-height:100vh;}
.sidebar{flex:0 0 var(--sidebar-w);position:sticky;top:0;height:100vh;overflow-y:auto;background:var(--at-sidebar);border-right:1px solid var(--at-border-subtle);}
.brand{display:flex;align-items:center;gap:10px;padding:16px;}
.brand .logo{width:30px;height:30px;flex:none;display:flex;align-items:center;justify-content:center;}
.brand .nm{font:600 15px/1.1 var(--font-sans);letter-spacing:-0.02em;color:var(--text-heading);}
.brand .nm small{display:block;font:400 11px/1.2 var(--font-sans);color:var(--text-muted);letter-spacing:.02em;}
.nav-group{padding:6px 12px 2px;}
.nav-group .gh{display:flex;align-items:center;gap:8px;width:100%;padding:14px 12px 8px;border:0;background:none;text-align:left;font:600 10px/1 var(--font-sans);text-transform:uppercase;letter-spacing:.12em;color:var(--text-muted);cursor:pointer;user-select:none;}
.nav-group .gh::before{content:"";width:6px;height:6px;border-radius:1px;background:var(--text-primary);flex:none;} /* legalwork's section mark */
.nav-group .gh svg{width:14px;height:14px;margin-left:auto;transition:transform .15s;}
.nav-group.collapsed .gh svg{transform:rotate(-90deg);}
.nav-group.collapsed .nav-item{display:none;}
.nav-item{display:flex;align-items:center;gap:12px;min-height:38px;padding:0 12px;border-radius:var(--at-radius-lg);font:400 14px/1 var(--font-sans);color:var(--text-primary);cursor:pointer;position:relative;margin:2px 0;border:1px solid transparent;text-decoration:none;}
.nav-item svg{width:18px;height:18px;flex:none;color:var(--text-secondary);position:relative;top:1px;} /* nudge 1px down: align-items:center centers boxes, but the line-height:1 text sits optically lower, so icons read as too high */
.nav-item:hover{background:var(--at-hover);text-decoration:none;}
.nav-item.active{background:var(--at-active);color:var(--text-primary);font-weight:500;border-color:transparent;}
.nav-item.active svg{color:var(--text-primary);}
/* nav search + collapse-to-rail (Open Mercato AppShell behaviour) */
.navsearch{padding:0 12px 8px;}
.navsearch input{height:34px;font-size:13px;}
.sidebar{transition:flex-basis .18s ease, width .18s ease;}
#app.nav-collapsed .sidebar{flex:0 0 var(--sidebar-collapsed-w);width:var(--sidebar-collapsed-w);}
#app.nav-collapsed .brand{justify-content:center;padding:16px 8px;}
#app.nav-collapsed .brand .nm,#app.nav-collapsed .navsearch{display:none;}
#app.nav-collapsed .nav-group{padding:6px 10px 2px;}
#app.nav-collapsed .nav-group .gh{display:none;}
#app.nav-collapsed .nav-group .nav-item,#app.nav-collapsed .nav-group.collapsed .nav-item{display:flex;justify-content:center;padding:9px;gap:0;}
#app.nav-collapsed .nav-item span{display:none;}
#app.nav-collapsed .nav-item.active::before{left:-10px;}
.main{flex:1;min-width:0;display:flex;flex-direction:column;}
.topbar{height:var(--topbar-h);flex:none;display:flex;align-items:center;gap:14px;padding:0 14px 0 18px;border-bottom:1px solid var(--at-border-subtle);background:var(--at-canvas);position:sticky;top:0;z-index:30;}
.crumb{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--text-muted);white-space:nowrap;}
.crumb .sep{font-size:0;width:1px;height:16px;background:var(--border);margin:0 4px;flex:none;} /* a hairline, not a slash */ .crumb b{color:var(--text-primary);font-weight:500;}
.topbar .spacer{flex:1;}
.org{display:flex;align-items:center;gap:6px;height:34px;padding:0 10px;border:1px solid var(--border);border-radius:6px;font-size:13px;color:var(--text-secondary);background:var(--surface);white-space:nowrap;overflow:hidden;min-width:0;}
.org.org-hide{display:none;}
.usermenu{display:flex;align-items:center;gap:8px;cursor:pointer;padding:4px 6px;border-radius:8px;}
.usermenu:hover{background:var(--surface-muted);}
.content{flex:1;}
/* ── login ── */
#login{min-height:100vh;display:flex;align-items:center;justify-content:center;background:var(--bg-canvas);padding:24px;}
.login-card{width:380px;max-width:100%;background:var(--surface);border:1px solid var(--border);border-radius:var(--at-radius-3xl);box-shadow:var(--shadow-login);padding:32px;}
.login-card .lhead{text-align:center;margin-bottom:24px;}
.login-card .logo{width:64px;height:64px;margin:0 auto 16px;display:flex;align-items:center;justify-content:center;}
.login-card h1{margin:0 0 4px;font:700 22px/1.2 var(--font-sans);}
.login-card .lsub{color:var(--text-muted);font-size:14px;}
.login-card .field{margin-bottom:14px;}
.login-card .btn.primary{width:100%;height:44px;justify-content:center;}
.login-foot{text-align:center;margin-top:14px;}
.login-foot a{color:var(--text-muted);font-size:13px;text-decoration:underline;}
/* ── dialog / command palette ── */
.overlay{position:fixed;inset:0;background:var(--at-overlay);backdrop-filter:blur(3px);-webkit-backdrop-filter:blur(3px);z-index:80;display:flex;align-items:flex-start;justify-content:center;padding-top:12vh;}
.palette{width:560px;max-width:92vw;background:var(--at-glass-strong);backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px);border:1px solid var(--at-border-subtle);border-radius:28px;box-shadow:var(--shadow-dialog);overflow:hidden;}
.palette .pinp{display:flex;align-items:center;gap:10px;padding:14px 16px;border-bottom:1px solid var(--border);}
.palette .pinp svg{width:18px;height:18px;color:var(--text-muted);}
.palette .pinp input{border:0;padding:0;height:auto;font-size:18px;background:none;}
.palette .pinp input:focus{box-shadow:none;}
.palette .presults{max-height:50vh;overflow:auto;padding:8px;}
.pgroup{font:600 11px/1 var(--font-sans);text-transform:uppercase;letter-spacing:.06em;color:var(--text-faint);padding:10px 8px 6px;}
.presult{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:9px 10px;border-radius:6px;cursor:pointer;}
.presult:hover{background:var(--surface-muted);}
.presult .pt{font-weight:600;font-size:14px;} .presult .pr{color:var(--text-muted);font-size:12px;}
/* ── request log slide-over ── */
.slideover{position:fixed;top:0;right:0;height:100vh;width:380px;max-width:90vw;background:var(--surface);border-left:1px solid var(--border);box-shadow:var(--shadow-dialog);z-index:70;display:flex;flex-direction:column;}
.slideover .sh{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid var(--border);font-weight:600;}
.slideover .sb{flex:1;overflow:auto;padding:10px;}
.logentry{border:1px solid var(--border);border-radius:6px;margin-bottom:6px;}
.logentry summary{cursor:pointer;padding:7px 9px;font:500 12px/1.3 var(--font-mono);}
.logentry.ok summary{color:var(--success);} .logentry.err summary{color:var(--danger);}
.logentry pre{margin:0;padding:8px 9px;background:#212529;color:#dbe4ff;border-radius:0 0 6px 6px;overflow:auto;font:11.5px var(--font-mono);}
/* ── toast ── */
#toast{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);z-index:90;}
.toast{display:flex;align-items:center;gap:8px;background:var(--primary);color:var(--primary-fg);padding:12px 16px;border-radius:var(--at-radius-2xl);box-shadow:var(--shadow-menu);font-size:13px;}
/* ── keyboard: skip link, focus target, reduced motion ── */
.skip{position:fixed;left:12px;top:-60px;z-index:100;padding:8px 14px;border-radius:8px;border:1px solid var(--border);background:var(--surface);color:var(--text-primary);font-size:14px;}
.skip:focus{top:12px;text-decoration:none;}
#content:focus{outline:none;} /* the skip link lands here; the page itself needs no ring */
@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important;}}
.nav-scrim{display:none;}
@media(max-width:880px){
.sidebar{position:fixed;left:0;top:0;z-index:50;transform:translateX(-100%);transition:transform .2s ease;will-change:transform;}
.sidebar.open{transform:none;box-shadow:var(--shadow-dialog);}
.nav-scrim{display:block;position:fixed;inset:0;z-index:45;background:rgba(0,0,0,.45);opacity:0;pointer-events:none;transition:opacity .2s ease;}
.sidebar.open ~ .nav-scrim{opacity:1;pointer-events:auto;}
.topbar{padding:0 12px;gap:8px;}
.topbar .org,.topbar .crumb,#userEmail{display:none;}
.page{padding:20px 16px 32px;}
.page-head{margin-bottom:20px;} .page-head h1{font-size:24px;}
.toolbar{padding:12px 16px;}
.dt-scroll{overflow-x:auto;-webkit-overflow-scrolling:touch;}
.grid2{grid-template-columns:1fr;}
}
</style>
</head>
<body>
<!-- ───────── Login ───────── -->
<!-- Hidden until the console knows which screen this is: ONLY showLogin() reveals it. restore()
resolves the session with an awaited GET /auth/me, so a pane that is visible by default paints
the sign-in card for a frame on every single load — and on the platform the card it flashes is a
password form this module does not even have any more (state.platform is only set by loadConfig(),
which runs inside restore()). Nothing is lost by waiting: without the script the form cannot
submit anyway. -->
<div id="login" class="hidden">
<button class="iconbtn js-theme" id="btnThemeLogin" title="Theme" aria-label="Theme" style="position:fixed;top:16px;right:16px;background:var(--surface);border:1px solid var(--border-input);box-shadow:var(--shadow-card);color:var(--text-secondary);"></button>
<form class="login-card" id="loginForm">
<div class="lhead">
<div class="logo"><svg viewBox="0 0 24 24" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path fill="#f76707" d="M19 2h-14a3 3 0 0 0 -3 3v14a3 3 0 0 0 3 3h14a3 3 0 0 0 3 -3v-14a3 3 0 0 0 -3 -3z"/><g fill="none" stroke="#fff4e6" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" transform="translate(12 12) scale(0.8) translate(-12 -12)"><path d="M16 17a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M6 7a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M6 18l12 -12"/></g></svg></div>
<h1>Counsel Scorecard</h1>
<div class="lsub">Access your workspace</div>
</div>
<div class="banner" style="margin-bottom:18px"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"/> <path d="M12 9h.01"/> <path d="M11 12h1v4h1"/></svg><span>Sign in with your workspace credentials</span></div>
<label class="field">Email <input id="email" type="email" value="admin@example.com" autocomplete="username" /></label>
<label class="field">Password <input id="password" type="password" placeholder="bootstrap password" autocomplete="current-password" /></label>
<label class="checkbox" style="margin:4px 0 16px"><input type="checkbox" id="remember" /> Remember me</label>
<div id="loginErr" class="banner err hidden" role="alert" style="margin-bottom:14px"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"/> <path d="M12 8v4"/> <path d="M12 16h.01"/></svg><span></span></div>
<button class="btn primary" id="btnLogin" type="submit">Sign in</button>
<div class="login-foot"><a href="#" onclick="return false">Forgot password?</a></div>
</form>
<!-- Shown INSTEAD of the form when this deployment is a module of the platform (GET /config says
so). Nobody signs in here then: there is one account, and the hub is where it is used. The
form is not merely disabled - an e-mail and password box that cannot work is an invitation to
go hunting for a second password, which is the exact thing this change removes. -->
<div class="login-card hidden" id="loginHub">
<div class="lhead">
<div class="logo"><svg viewBox="0 0 24 24" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path fill="#f76707" d="M19 2h-14a3 3 0 0 0 -3 3v14a3 3 0 0 0 3 3h14a3 3 0 0 0 3 -3v-14a3 3 0 0 0 -3 -3z"/><g fill="none" stroke="#fff4e6" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" transform="translate(12 12) scale(0.8) translate(-12 -12)"><path d="M16 17a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M6 7a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M6 18l12 -12"/></g></svg></div>
<h1>Counsel Scorecard</h1>
<div class="lsub">One account for the whole platform</div>
</div>
<div class="banner" style="margin-bottom:18px"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"/> <path d="M12 9h.01"/> <path d="M11 12h1v4h1"/></svg><span>Sign in once at the hub and you arrive here already signed in. There is no separate password for Counsel.</span></div>
<a class="btn primary" id="btnHub" style="width:100%;height:44px;justify-content:center" href="#">Sign in at the hub</a>
</div>
<!-- The third state of this screen, and the only one NOT about signing in: the session is good and
the person is refused. Shown when GET /auth/me answers 403, which on the platform means
`moderation.assert_may_use` found no `module_permission` row for counsel. The hub card would
tell someone already signed in to sign in, and its button sends them to the hub they came
from — a loop, since signing in again can never produce a row only an administrator writes.
Only reachable on the platform: standalone, `assert_may_use` refuses nobody. -->
<div class="login-card hidden" id="refusedCard">
<div class="lhead">
<div class="logo"><svg viewBox="0 0 24 24" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path fill="#f76707" d="M19 2h-14a3 3 0 0 0 -3 3v14a3 3 0 0 0 3 3h14a3 3 0 0 0 3 -3v-14a3 3 0 0 0 -3 -3z"/><g fill="none" stroke="#fff4e6" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" transform="translate(12 12) scale(0.8) translate(-12 -12)"><path d="M16 17a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M6 7a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M6 18l12 -12"/></g></svg></div>
<h1>Counsel Scorecard</h1>
<div class="lsub">One account for the whole platform</div>
</div>
<div class="banner" style="margin-bottom:18px"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"/> <path d="M12 9h.01"/> <path d="M11 12h1v4h1"/></svg><span><span>You are signed in, but you do not have access to Counsel.</span> <span>Ask an administrator for access.</span></span></div>
<a class="btn primary" id="btnRefusedHub" style="width:100%;height:44px;justify-content:center" href="#">Go to the platform</a>
<button class="btn ghost" id="btnRefusedOut" type="button" style="width:100%;height:40px;justify-content:center;margin-top:10px">Sign out</button>
</div>
</div>
<!-- ───────── App shell ───────── -->
<div id="app" class="hidden">
<a class="skip" href="#content" onclick="event.preventDefault();document.getElementById('content').focus()">Skip to content</a>
<aside class="sidebar" id="sidebar">
<div class="brand"><div class="logo"><svg viewBox="0 0 24 24" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path fill="#f76707" d="M19 2h-14a3 3 0 0 0 -3 3v14a3 3 0 0 0 3 3h14a3 3 0 0 0 3 -3v-14a3 3 0 0 0 -3 -3z"/><g fill="none" stroke="#fff4e6" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" transform="translate(12 12) scale(0.8) translate(-12 -12)"><path d="M16 17a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M6 7a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M6 18l12 -12"/></g></svg></div><div class="nm">Counsel Scorecard<small>External-counsel scoring</small></div></div>
<div class="navsearch"><input id="navSearch" placeholder="Search…" aria-label="Search navigation" autocomplete="off"></div>
<nav id="nav"></nav>
</aside>
<div id="navScrim" class="nav-scrim" aria-hidden="true"></div>
<div class="main">
<header class="topbar">
<button class="iconbtn" id="navToggle" title="Toggle sidebar" aria-label="Toggle sidebar"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 6a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2l0 -12"/> <path d="M9 4l0 16"/></svg></button>
<div class="crumb" id="crumb"><span>Dashboard</span></div>
<div class="spacer"></div>
<button class="iconbtn" id="btnLog" title="Request log" aria-label="Request log"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 6l11 0"/> <path d="M9 12l11 0"/> <path d="M9 18l11 0"/> <path d="M5 6l0 .01"/> <path d="M5 12l0 .01"/> <path d="M5 18l0 .01"/></svg></button>
<button class="iconbtn" id="btnPalette" title="Search (Ctrl/⌘K)" aria-label="Search (Ctrl/⌘K)"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 10a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"/> <path d="M21 21l-6 -6"/></svg></button>
<button class="iconbtn js-theme" id="btnTheme" title="Theme" aria-label="Theme"></button>
<div class="org"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21l18 0"/> <path d="M9 8l1 0"/> <path d="M9 12l1 0"/> <path d="M9 16l1 0"/> <path d="M14 8l1 0"/> <path d="M14 12l1 0"/> <path d="M14 16l1 0"/> <path d="M5 21v-16a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v16"/></svg> Counsel Scorecard</div>
<div class="usermenu" id="userMenu">
<span class="avatar" id="userAvatar">?</span>
<span class="muted" id="userEmail" style="font-size:13px"></span>
</div>
</header>
<main class="content" id="content" tabindex="-1"></main>
</div>
</div>
<!-- request log slide-over -->
<div id="logPanel" class="slideover hidden">
<div class="sh">Request log <button class="iconbtn" id="logClose" title="Close" aria-label="Close"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6l-12 12"/> <path d="M6 6l12 12"/></svg></button></div>
<div class="sb" id="log"></div>
</div>
<div id="modalRoot"></div>
<div id="toast" role="status" aria-live="polite"></div>
<script>
// ═══════════════ helpers (security-preserving) ═══════════════
const $ = (id) => document.getElementById(id);
const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (ch) =>
({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[ch]));
// A value as a JS argument inside an inline handler (onclick="fn(…)"). esc() alone is NOT enough
// there: the HTML parser turns &#39; back into ' before the handler is compiled, so a value that
// carries a quote ends the string and the rest of it runs as script. JSON.stringify makes the value
// one JS string literal; esc() then only has to protect the attribute around it.
const jsArg = (v) => esc(JSON.stringify(String(v ?? '')));
// The API base (carrying the Bearer token) is persisted in localStorage, so a poisoned
// cs_base2 could point requests — and the token — at an attacker origin. Accept only a
// same-origin path, the same origin, or a local dev backend; anything else falls back.
function sanitizeBase(raw){
// Derive the default from the document rather than hard-coding a root-absolute '/api/v1':
// served at /counsel/ (this app as a module of the platform) the console must call
// /counsel/api/v1, and at the origin root plain /api/v1. Relative resolution drops the last
// path segment and ignores the fragment, so it is right at /counsel/, /counsel/index.html and
// /counsel/#/firms alike — but NOT at a bare /counsel with no trailing slash, which resolves to
// /api/v1 and would hit the platform root. That is why the proxy 308-redirects /counsel to
// /counsel/. A file:// page has no usable base, hence the local-dev fallback.
const fb = location.origin.startsWith('http')
? new URL('api/v1', document.baseURI).pathname
: 'http://localhost:8000/api/v1';
if(!raw) return fb; raw = String(raw).trim();
// One leading slash and no more: '//host' and '/\host' are protocol-relative, i.e. another
// ORIGIN, which is the one thing this function exists to refuse. ('/%5C…' is a literal path
// segment to the URL parser, so it stays same-origin and is fine.)
if(/^\/(?![/\\])/.test(raw)) return raw;
let u; try{ u = new URL(raw); }catch{ return fb; }
if(u.protocol!=='http:' && u.protocol!=='https:') return fb;
if(u.origin===location.origin) return raw;
if(['localhost','127.0.0.1','[::1]'].includes(u.hostname)) return raw;
return fb;
}
// cs_base2, not cs_base: on the platform all four consoles share ONE origin and therefore one
// localStorage, so a value left under the old key — by an earlier deployment of this console at
// the origin root, or by a sibling module's script — is stale at best and points at the wrong
// module at worst. Bumping the key retires every one of them in a single reload.
const state = { base: sanitizeBase(localStorage.getItem('cs_base2')), token:'', user:null, platform:false }; // token in memory only; platform = identity is the hub's (GET /config)
const cache = { enums:{}, practiceAreas:[], jurisdictions:[], firms:[], users:[], matters:[], questionnaires:[], questions:[], cycles:[], evaluations:[] };
let lastResponseId = null;
function log(title,data,isError){
const d=document.createElement('details'); d.className='logentry '+(isError?'err':'ok');
const s=document.createElement('summary'); s.textContent=title;
const pre=document.createElement('pre'); pre.textContent=typeof data==='string'?data:JSON.stringify(data,null,2);
d.appendChild(s); d.appendChild(pre);
const box=$('log'); if(box){ box.insertBefore(d,box.firstChild); while(box.children.length>60) box.removeChild(box.lastChild); }
}
async function api(method,path,body){
const url=state.base.replace(/\/$/,'')+path;
const headers={'Accept':'application/json'};
if(body!==undefined) headers['Content-Type']='application/json';
if(state.token) headers['Authorization']='Bearer '+state.token;
let res,text,data;
try{ res=await fetch(url,{method,headers,credentials:'include',body:body!==undefined?JSON.stringify(body):undefined}); }
catch(e){ log(`${method} ${path} — NETWORK ERROR`,String(e),true); throw e; }
text=await res.text(); try{ data=text?JSON.parse(text):null; }catch{ data=text; }
log(`${method} ${path} → ${res.status}`,data,!res.ok);
if(!res.ok){ const err=new Error((data&&data.detail)||res.statusText); err.data=data; err.status=res.status; throw err; }
return data;
}
function toast(msg){ const t=$('toast'); t.innerHTML=`<div class="toast">${esc(msg)}</div>`; setTimeout(()=>{t.innerHTML='';},2600); }
function initials(s){ s=String(s||'?'); return s.replace(/@.*/,'').split(/[.\s_-]+/).filter(Boolean).slice(0,2).map(x=>x[0].toUpperCase()).join('')||'?'; }
// ═══════════════ component builders (all values esc()'d) ═══════════════
// Icons = Tabler Icons (https://tabler.io/icons, MIT). Outline 24x24 stroke paths drawn by
// svg() with stroke:currentColor. Inner SVG from @tabler/icons (bounding-box rect removed).
const ICN = {
firm:'<path d="M3 21l18 0"/> <path d="M9 8l1 0"/> <path d="M9 12l1 0"/> <path d="M9 16l1 0"/> <path d="M14 8l1 0"/> <path d="M14 12l1 0"/> <path d="M14 16l1 0"/> <path d="M5 21v-16a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v16"/>',
matter:'<path d="M14 3v4a1 1 0 0 0 1 1h4"/> <path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2"/> <path d="M9 9l1 0"/> <path d="M9 13l6 0"/> <path d="M9 17l6 0"/>',
form:'<path d="M12 3a3 3 0 0 0 -3 3v12a3 3 0 0 0 3 3"/> <path d="M6 3a3 3 0 0 1 3 3v12a3 3 0 0 1 -3 3"/> <path d="M13 7h7a1 1 0 0 1 1 1v8a1 1 0 0 1 -1 1h-7"/> <path d="M5 7h-1a1 1 0 0 0 -1 1v8a1 1 0 0 0 1 1h1"/> <path d="M17 12h.01"/> <path d="M13 12h.01"/>',
question:'<path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"/> <path d="M12 16v.01"/> <path d="M12 13a2 2 0 0 0 .914 -3.782a1.98 1.98 0 0 0 -2.414 .483"/>',
resp:'<path d="M8 9h8"/> <path d="M8 13h6"/> <path d="M18 4a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-5l-5 3v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12"/>',
cycle:'<path d="M9 4.55a8 8 0 0 1 6 14.9m0 -4.45v5h5"/> <path d="M5.63 7.16l0 .01"/> <path d="M4.06 11l0 .01"/> <path d="M4.63 15.1l0 .01"/> <path d="M7.16 18.37l0 .01"/> <path d="M11 19.94l0 .01"/>',
user:'<path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0"/> <path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2"/>',
book:'<path d="M3 19a9 9 0 0 1 9 0a9 9 0 0 1 9 0"/> <path d="M3 6a9 9 0 0 1 9 0a9 9 0 0 1 9 0"/> <path d="M3 6l0 13"/> <path d="M12 6l0 13"/> <path d="M21 6l0 13"/>',
home:'<path d="M5 12l-2 0l9 -9l9 9l-2 0"/> <path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-7"/> <path d="M9 21v-6a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v6"/>',
dots:'<path d="M4 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/> <path d="M11 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/> <path d="M18 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/>',
plus:'<path d="M12 5l0 14"/> <path d="M5 12l14 0"/>',
save:'<path d="M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2"/> <path d="M10 14a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"/> <path d="M14 4l0 4l-6 0l0 -4"/>',
filter:'<path d="M4 4h16v2.172a2 2 0 0 1 -.586 1.414l-4.414 4.414v7l-6 2v-8.5l-4.48 -4.928a2 2 0 0 1 -.52 -1.345v-2.227"/>',
info:'<path d="M3 10.5a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"/> <path d="M12 5.5h.01"/> <path d="M11 8.5h1v4h1"/>',
refresh:'<path d="M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4"/> <path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4"/>'};
function svg(p,w){ return `<svg viewBox="0 0 24 24" width="${w||16}" height="${w||16}" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">${p}</svg>`; }
function btn(label,{cls='ghost',icon,onclick,attrs=''}={}){ return `<button class="btn ${cls}" ${onclick?`onclick="${onclick}"`:''} ${attrs}>${icon?svg(icon):''}${label?esc(label):''}</button>`; }
const STATUS = {
active:['success','complete'],inactive:['','neutral'],blacklisted:['danger','danger'],
open:['','open'],in_progress:['warn','progress'],closed:['success','complete'],cancelled:['danger','danger'],
draft:['','neutral'],submitted:['','open'],locked:['','neutral'],archived:['','neutral'],
provisional:['','neutral'],at_risk:['warn','progress'],watch:['warn','progress'],solid:['success','complete'],top_performer:['success','complete'],remove_candidate:['danger','danger'],
};
function badge(val){ if(val==null||val==='') return '<span class="faint">—</span>'; const k=String(val); const m=STATUS[k]||['','neutral'];
return `<span class="badge ${m[0]}"><span class="dot dot-${m[1]}"></span>${esc(k.replace(/_/g,' '))}</span>`; }
// generic data-table card. cols: [{h, f(row)->html, raw?(skip esc), cls}]
function dataTable({title, subtitle, createLabel, createHref, columns, rows, rowMenu, search, onSearch, empty}){
const head = `<div class="card-head"><div><h2>${esc(title)}</h2></div>${createLabel?btn(createLabel,{cls:'primary',icon:ICN.plus,onclick:`go('${createHref}')`}):''}</div>`;
const tb = `<div class="toolbar"><div></div><div class="search">${svg('<path d="M3 10a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"/> <path d="M21 21l-6 -6"/>',15)}<input placeholder="Search…" oninput="filterTable(this)"></div></div>`;
let body;
if(!rows.length){ body = `<div class="empty">${esc(empty||'No records yet.')}</div>`; }
else {
const ths = columns.map(c=>`<th class="${c.cls||''}">${esc(c.h)}</th>`).join('') + (rowMenu?'<th class="actions">Actions</th>':'');
const trs = rows.map((r,i)=>{
const tds = columns.map(c=>`<td class="${c.cls||''}">${c.raw?c.f(r):esc(c.f(r)??'')}</td>`).join('');
const menu = rowMenu?`<td class="actions"><button class="iconbtn" aria-label="Actions" aria-haspopup="true" onclick='rowMenu(event,${i})'>${svg(ICN.dots)}</button></td>`:'';
return `<tr>${tds}${menu}</tr>`;
}).join('');
body = `<div class="dt-scroll"><table class="dt"><thead><tr>${ths}</tr></thead><tbody>${trs}</tbody></table></div>
<div class="pager"><span><span>Showing</span> 1–${rows.length} <span>of</span> ${rows.length}</span>
<span class="pg">${btn('Previous',{cls:'ghost sm',attrs:'disabled'})}<span><span>Page</span> 1 <span>of</span> 1</span>${btn('Next',{cls:'ghost sm',attrs:'disabled'})}</span></div>`;
}
// expose rowMenu handler
window.rowMenu = rowMenu ? (ev,i)=>rowMenu(ev,rows[i]) : null;
return `<div class="card">${head}${tb}${body}</div>`;
}
function pageHead(title,sub,actions){ return `<div class="page-head"><div><h1>${esc(title)}</h1>${sub?`<div class="sub">${esc(sub)}</div>`:''}</div><div class="page-actions">${actions||''}</div></div>`; }
// ═══════════════ auth ═══════════════
// The hub is a sibling PATH, not another host: the platform serves one module per path on one
// origin (/atrium, /galena, /sygna, /counsel), which is why there is no handoff to build and no
// address to configure. Derived from the document like every other URL in this console, so it stays
// correct under any prefix; if the hub ever moves, this one line is where it is said.
function hubUrl(){ try{ return new URL('../atrium/', document.baseURI).href; }catch{ return '../atrium/'; } }
function showLogin(){
const hub=state.platform;
$('loginForm').classList.toggle('hidden',hub);
$('loginHub').classList.toggle('hidden',!hub);
if(hub) $('btnHub').href=hubUrl();
// The refusal card is the one state you can leave without a reload (signing out there lands
// here), and the two cards above are toggled against each other, so put it away explicitly.
$('refusedCard').classList.add('hidden');
$('login').classList.remove('hidden'); $('app').classList.add('hidden');
}
// Signed in, and not admitted to this module: a different problem from showLogin()'s, with a
// different remedy (a person, not a password). The hub address is set as an href property, never
// interpolated markup.
function showRefused(){
$('loginForm').classList.add('hidden'); $('loginHub').classList.add('hidden');
$('refusedCard').classList.remove('hidden');
$('btnRefusedHub').href=hubUrl();
$('login').classList.remove('hidden'); $('app').classList.add('hidden');
}
function showApp(){ $('login').classList.add('hidden'); $('app').classList.remove('hidden'); }
async function doLogin(e){ e&&e.preventDefault(); $('loginErr').classList.add('hidden'); state.token='';
try{ const r=await api('POST','/auth/login',{email:$('email').value.trim(),password:$('password').value});
state.token=r.token; state.user=r.user; renderUser(); showApp(); await loadAll(); router();
}catch(err){ const b=$('loginErr'); b.querySelector('span').textContent=err.message||'Sign in failed'; b.classList.remove('hidden'); }
}
async function doLogout(){ try{ await api('POST','/auth/logout'); }catch{}
state.token=''; state.user=null;
for(const k of Object.keys(cache)) cache[k]=Array.isArray(cache[k])?[]:{};
lastResponseId=null; showLogin();
}
// What kind of deployment this is, before anything else: it decides whether there is a sign-in
// screen at all. A failure here is not fatal - it falls back to the standalone shape, which shows
// the form, and the server refuses that with a sentence if it was the wrong guess.
async function loadConfig(){ try{ const c=await api('GET','/config'); state.platform=!!(c&&c.shares_identity); }catch{} }
async function restore(){ await loadConfig();
try{ state.user=await api('GET','/auth/me'); renderUser(); showApp(); await loadAll(); router(); }
// 403 is not 401: 401 means no (or an expired) session, and signing in is the answer; 403 on THIS
// call means the session resolved to a real person whom `assert_may_use` refused, and the sign-in
// card's hub button would only loop back here. A GET reaches no other 403 (scope and the
// cross-site guard only check unsafe methods); a thrown fetch has no `.status`.
catch(e){ state.token=''; if(e&&e.status===403) showRefused(); else showLogin(); } }
function renderUser(){ const u=state.user; $('userEmail').textContent=u?u.email:''; $('userAvatar').textContent=initials(u&&u.email);
renderNav(); }
// "May I administer this module?" - a platform ADMINISTRATOR, or a MODERATOR of counsel. A field of
// its own rather than a role value, because the tier is not a Counsel role any more: the hub grants
// it, this app only reads it, and `role` now says purely what someone DOES here.
function isModerator(){ return !!(state.user && state.user.is_moderator); }
// ═══════════════ data loading ═══════════════
async function loadAll(){
await Promise.all([
api('GET','/enums').then(d=>cache.enums=d).catch(()=>{}),
api('GET','/practice-areas').then(d=>cache.practiceAreas=d).catch(()=>{}),
api('GET','/jurisdictions').then(d=>cache.jurisdictions=d).catch(()=>{}),
api('GET','/firms').then(d=>cache.firms=d).catch(()=>{}),
api('GET','/matters').then(d=>cache.matters=d).catch(()=>{}),
api('GET','/questionnaires').then(d=>cache.questionnaires=d).catch(()=>{}),
api('GET','/questions').then(d=>cache.questions=d).catch(()=>{}),
api('GET','/review-cycles').then(d=>cache.cycles=d).catch(()=>{}),
// limit=500 = the API's max page; past that the avg-score columns need a server aggregate
api('GET','/responses?limit=500').then(d=>cache.evaluations=d).catch(()=>{}),
]);
if(isModerator()) await api('GET','/users').then(d=>cache.users=d).catch(()=>{});
}
const ENUM_FALLBACKS = {
user_role:['legal_ops','matter_owner','viewer'], firm_status:['active','inactive','blacklisted'],
matter_type:['transactional','advisory','litigation','regulatory'], complexity_band:['routine','standard','complex'],
value_band:['lt_50k','50k_250k','250k_1m','1m_10m','gt_10m'],
};
function enumVals(key){ return (cache.enums&&cache.enums[key])||ENUM_FALLBACKS[key]||[]; }
function optionTags(values,sel){ return values.map(v=>`<option value="${esc(v)}" ${v===sel?'selected':''}>${esc(v)}</option>`).join(''); }
// ═══════════════ navigation ═══════════════
const NAV = [
{ group:'OVERVIEW', items:[ {id:'',label:'Dashboard',icon:ICN.home} ] },
{ group:'DIRECTORY', items:[ {id:'firms',label:'Firms',icon:ICN.firm}, {id:'matters',label:'Matters',icon:ICN.matter} ] },
{ group:'QUESTIONNAIRES', items:[ {id:'questionnaires',label:'Questionnaires',icon:ICN.form}, {id:'questions',label:'Questions',icon:ICN.question} ] },
{ group:'EVALUATIONS', items:[ {id:'evaluations',label:'Evaluations',icon:ICN.resp}, {id:'responses',label:'Submit evaluation',icon:ICN.plus} ] },
{ group:'REVIEW', items:[ {id:'cycles',label:'Review cycles',icon:ICN.cycle} ] },
{ group:'ADMIN', items:[ {id:'users',label:'Users',icon:ICN.user,admin:true}, {id:'dictionaries',label:'Dictionaries',icon:ICN.book} ] },
{ group:'HELP', items:[ {id:'about',label:'About',icon:ICN.info} ] },
];
function curRoute(){ return (location.hash||'#/').replace(/^#\/?/,'').split('/'); }
let navFilter='';
function renderNav(){
const cur=curRoute()[0]||''; const q=navFilter.trim().toLowerCase();
$('nav').innerHTML = NAV.map(g=>{
// On the platform the ADMIN group opens from Atrium's Ustawienia (#/settings), not from this menu.
if(g.group==='ADMIN'&&state.platform) return '';
let items=g.items.filter(it=>!it.admin||isModerator());
if(q) items=items.filter(it=>it.label.toLowerCase().includes(q) || _tr(it.label).toLowerCase().includes(q)); // match English OR the displayed (localized) label, so nav search works in PL too
if(!items.length) return '';
// Links and a button, not <div onclick>: a div takes no focus, so the whole menu was mouse-only.
return `<div class="nav-group" data-g="${esc(g.group)}"><button type="button" class="gh" aria-expanded="true" onclick="navFold(this)"><span>${esc(g.group)}</span>${svg('<path d="M6 9l6 6l6 -6"/>',14)}</button>
${items.map(it=>`<a class="nav-item ${it.id===cur?'active':''}" href="#/${esc(it.id)}" title="${esc(it.label)}"${it.id===cur?' aria-current="page"':''} onclick="go('${it.id}')">${svg(it.icon)}<span>${esc(it.label)}</span></a>`).join('')}</div>`;
}).join('');
}
function setCrumb(parts){ $('crumb').innerHTML = parts.map((p,i)=> i? `<span class="sep">/</span>${i===parts.length-1?`<b>${esc(p)}</b>`:esc(p)}` : esc(p)).join(' '); fitOrg(); }
// Hide the topbar workspace chip when the bar is too tight to show it fully, rather than letting
// "Counsel Scorecard" wrap inside the 34px chip. min-width:0 + nowrap make .org clip first; if it's
// clipped (scrollWidth > clientWidth) we hide the whole chip. Re-checked on crumb change + topbar resize.
let _orgFitT;
function fitOrg(){ const o=document.querySelector('.topbar .org'); if(!o) return;
o.classList.remove('org-hide'); // reveal now; measure in a later task so the chip is laid out
clearTimeout(_orgFitT); // (reading a child's box in the same task it leaves display:none
_orgFitT=setTimeout(()=>{ if(o.scrollWidth > o.clientWidth + 1) o.classList.add('org-hide'); }, 80); } // is unreliable). .org clips (min-width:0) rather than wraps, so hide it when its text is clipped.
function go(id){ location.hash = '#/'+id; if(window.innerWidth<=880) $('sidebar').classList.remove('open'); }
window.go = go;
function navFold(b){ const g=b.parentNode; g.classList.toggle('collapsed'); b.setAttribute('aria-expanded',String(!g.classList.contains('collapsed'))); }
window.navFold = navFold;
window.addEventListener('hashchange', router);
// ═══════════════ views ═══════════════
// Bumped on every route render; async views capture it and drop DOM writes when a fetch
// resolves after the user has already navigated away (the ids they'd write to now belong
// to a different page).
let renderEpoch=0;
function router(){
if(!state.user) return;
renderEpoch++;
renderNav();
const r=curRoute(); const v=r[0]||'';
const C=$('content');
const views={ '':viewDashboard, about:viewAbout, firms:viewFirms, matters:viewMatters, questionnaires:viewQuestionnaires,
questions:viewQuestions, responses:viewResponses, evaluations:viewEvaluations, cycles:viewCycles, users:viewUsers, dictionaries:viewDictionaries, settings:viewSettings };
if(v==='firms'&&r[1]==='new') return formFirm(C);
if(v==='matters'&&r[1]==='new') return formMatter(C);
if(v==='users'&&r[1]==='new') return formUser(C);
if(v==='questions'&&r[1]==='new') return formQuestion(C);
if(v==='questionnaires'&&r[1]==='new') return formQuestionnaire(C);
if(v==='questionnaires'&&r[1]) return formQuestionnaire(C,r[1]);
if(v==='cycles'&&r[1]==='new') return formCycle(C);
if(v==='cycles'&&r[1]) return viewCycleDetail(C,r[1]);
if(v==='firms'&&r[1]) return viewFirmDetail(C,r[1]);
if(v==='matters'&&r[1]) return viewMatterDetail(C,r[1]);
(views[v]||viewDashboard)(C);
}
function viewDashboard(C){
setCrumb(['Dashboard']);
const firms=cache.firms||[], matters=cache.matters||[], cycles=cache.cycles||[];
const openCycles=cycles.filter(c=>c.status==='open');
C.innerHTML = `<div class="page">
${pageHead('Dashboard','Overview of firms, matters, and review activity.')}
<div class="widgets">
<div class="widget"><h3>Firms</h3><p class="wd-desc">External counsel on record</p><div class="metric">${firms.length}</div></div>
<div class="widget"><h3>Matters</h3><p class="wd-desc">Engagements being evaluated</p><div class="metric">${matters.length}</div></div>
<div class="widget"><h3>Open review cycles</h3><p class="wd-desc">Accepting evaluations</p><div class="metric">${openCycles.length}</div></div>
<div class="widget"><h3>Recent matters</h3><p class="wd-desc">Latest engagements</p>
${matters.slice(0,5).map(m=>`<div class="kv"><span class="k">${esc(m.reference||'')}</span><span>${esc((m.title||'').slice(0,28))}</span></div>`).join('')||'<div class="kv"><span class="k">No matters</span></div>'}</div>
<div class="widget"><h3>Review cycles</h3><p class="wd-desc">Status by cycle</p>
${cycles.slice(0,5).map(c=>`<div class="kv"><span class="k">${esc(c.name||'')}</span>${badge(c.status)}</div>`).join('')||'<div class="kv"><span class="k">No cycles</span></div>'}</div>
<div class="widget"><h3>Quick actions</h3><p class="wd-desc">Common tasks</p>
<div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:4px">${btn('New firm',{cls:'ghost sm',icon:ICN.plus,onclick:"go('firms/new')"})}${btn('New matter',{cls:'ghost sm',icon:ICN.plus,onclick:"go('matters/new')"})}${btn('Evaluate',{cls:'ghost sm',onclick:"go('responses')"})}</div></div>
</div></div>`;
}
function viewAbout(C){
setCrumb(['Dashboard','About']);
C.innerHTML = `<div class="page"><div class="about">
${pageHead('About','What Counsel Scorecard is and how it helps.')}
<div class="card2">
<h3>What is Counsel Scorecard?</h3>
<p>Counsel Scorecard helps legal teams keep track of how well their outside law firms perform — and turn scattered opinions into a clear, fair score for every firm.</p>
</div>
<div class="card2">
<h3>How it works</h3>
<ol>
<li>Decide what matters — choose the questions you want to ask, such as responsiveness, quality of work, and value for money.</li>
<li>Group those questions into a scorecard and give each one a weight.</li>
<li>After every piece of work, the person who ran it fills in a short evaluation.</li>
<li>At the end of a review period, the answers are combined into a single score and a ranking for each firm.</li>
</ol>
</div>
<div class="card2">
<h3>Why teams use it</h3>
<ul>
<li>Fair and consistent — every firm is judged against the same questions.</li>
<li>Transparent — each score can be traced back to the answers behind it.</li>
<li>Private by design — it runs on your own systems, and your data never leaves them.</li>
</ul>
</div>
<div class="card2">
<h3>License</h3>
<p>Counsel Scorecard is free and open-source software, released under the Apache License 2.0.</p>
<p>You are free to use, change, and share it — including for commercial use — at no cost. In short: keep the original copyright and license notice, and state any significant changes you make. The software is provided as-is, without warranty.</p>
<p><a href="https://www.apache.org/licenses/LICENSE-2.0" target="_blank" rel="noopener">Read the full license</a></p>
</div>
</div></div>`;
}
// ── evaluation display helpers (counsel review 2026-07-02: scores must be visible) ──
const firmName=(id)=>((cache.firms||[]).find(f=>f.id===id)||{}).name||shortId(id);
const matterRef=(id)=>{ const m=(cache.matters||[]).find(x=>x.id===id); return m?m.reference:shortId(id); };
const cycleName=(id)=>((cache.cycles||[]).find(c=>c.id===id)||{}).name||(id?shortId(id):'—');
function fmtScore(v){ if(v==null||v==='') return '—'; const n=Number(v); return Number.isFinite(n)?String(Math.round(n*10)/10):'—'; }
function submittedEvals(list){ return (list||[]).filter(r=>r.status==='submitted'||r.status==='locked'); }
function avgScore(list){ const s=submittedEvals(list).map(r=>Number(r.score)).filter(Number.isFinite); if(!s.length) return null; return s.reduce((a,b)=>a+b,0)/s.length; }
function fmtBilling(m){ if(!m.billing_method) return '—';
const method=String(m.billing_method).replace(/_/g,' ');
const amt=m.budget_estimate!=null?` · ${esc(m.budget_estimate)}${m.budget_currency?' '+esc(m.budget_currency):''}`:'';
const notes=m.billing_method==='other'&&m.billing_notes?` · ${esc(m.billing_notes)}`:'';
return `<span class="chip">${esc(method)}</span><span class="sub">${amt}${notes}</span>`; }
function fmtWhen(r){ const d=r.submitted_at||r.created_at; return d?new Date(d).toLocaleDateString():'—'; }
function viewFirms(C){
setCrumb(['Dashboard','Firms']);
const evalsByFirm={}; (cache.evaluations||[]).forEach(r=>{ if(r.firm_id) (evalsByFirm[r.firm_id]=evalsByFirm[r.firm_id]||[]).push(r); });
C.innerHTML = `<div class="page">${pageHead('Firms','Law firms evaluated in review cycles. Click a firm to see its evaluation history.')}
${dataTable({ title:'Firms', createLabel:'New firm', createHref:'firms/new',
columns:[ {h:'Name',f:f=>`<a class="primary-cell" href="#/firms/${esc(f.id)}">${esc(f.name)}</a>${f.legal_name?`<span class="sub">${esc(f.legal_name)}</span>`:''}`,raw:true},
{h:'Status',f:f=>badge(f.status),raw:true},
{h:'Avg score',f:f=>{ const a=avgScore(evalsByFirm[f.id]); return a==null?'<span class="faint">—</span>':`<b>${esc(fmtScore(a))}</b><span class="faint">/100</span>`; },raw:true},
{h:'Evaluations',f:f=>submittedEvals(evalsByFirm[f.id]).length||'—'},
{h:'Website',f:f=>f.website||'—'} ],
rows:cache.firms||[], empty:'No firms yet — create one to start.',
rowMenu:(ev,row)=>openMenu(ev,[ {label:'Open',fn:()=>go('firms/'+row.id)}, {label:'Edit',fn:()=>editFirm(row)} ]) })}</div>`;
}
function viewMatters(C){
setCrumb(['Dashboard','Matters']);
const evalsByMatter={}; (cache.evaluations||[]).forEach(r=>{ if(r.matter_id) (evalsByMatter[r.matter_id]=evalsByMatter[r.matter_id]||[]).push(r); });
C.innerHTML = `<div class="page">${pageHead('Matters','Engagements scored by their owners. Click a matter to see how it was evaluated.')}
${dataTable({ title:'Matters', createLabel:'New matter', createHref:'matters/new',
columns:[ {h:'Matter',f:m=>`<a class="primary-cell" href="#/matters/${esc(m.id)}">${esc(m.reference)}</a><span class="sub">${esc(m.title)}</span>`,raw:true},
{h:'Firm',f:m=>`<span class="chip">${esc(firmName(m.firm_id))}</span>`,raw:true},
{h:'Billing',f:m=>fmtBilling(m),raw:true},
{h:'Score',f:m=>{ const a=avgScore(evalsByMatter[m.id]); return a==null?'<span class="faint">—</span>':`<b>${esc(fmtScore(a))}</b><span class="faint">/100</span>`; },raw:true},
{h:'Type',f:m=>m.matter_type}, {h:'Status',f:m=>badge(m.status),raw:true} ],
rows:cache.matters||[], empty:'No matters yet.',
rowMenu:(ev,row)=>openMenu(ev,[ {label:'Open',fn:()=>go('matters/'+row.id)}, {label:'Edit',fn:()=>editMatter(row)} ]) })}</div>`;
}
// ── shared evaluations table (firm detail / matter detail / evaluations list) ──
function evalTable(rows,{showFirm=true,showMatter=true}={}){
if(!rows||!rows.length) return `<div class="empty">No evaluations yet.</div>`;
rows=[...rows].sort((a,b)=>new Date(b.submitted_at||b.created_at||0)-new Date(a.submitted_at||a.created_at||0));
const dash='<span class="faint">—</span>';
return `<div class="dt-scroll"><table class="dt"><thead><tr><th>When</th>${showFirm?'<th>Firm</th>':''}${showMatter?'<th>Matter</th>':''}<th>Review cycle</th><th>Status</th><th>Recommend?</th><th>Score</th></tr></thead><tbody>
${rows.map(r=>`<tr><td>${esc(fmtWhen(r))}</td>
${showFirm?`<td>${r.firm_id?`<a href="#/firms/${esc(r.firm_id)}">${esc(firmName(r.firm_id))}</a>`:dash}</td>`:''}
${showMatter?`<td>${r.matter_id?`<a href="#/matters/${esc(r.matter_id)}">${esc(matterRef(r.matter_id))}</a>`:dash}</td>`:''}
<td>${r.review_cycle_id?esc(cycleName(r.review_cycle_id)):dash}</td><td>${badge(r.status)}</td>
<td>${r.recommend==null?dash:(r.recommend?'yes':'no')}</td>
<td>${r.score==null?dash:`<b>${esc(fmtScore(r.score))}</b><span class="faint">/100</span>`}</td></tr>`).join('')}</tbody></table></div>`;
}
function safeUrl(u){ return /^https?:\/\//i.test(u||'')?u:null; }
function viewEvaluations(C){
setCrumb(['Dashboard','Evaluations']);
C.innerHTML=`<div class="page">${pageHead('Evaluations','Every submitted evaluation, with its score.',btn('Submit evaluation',{cls:'primary',icon:ICN.plus,onclick:"go('responses')"}))}
<div class="card"><div id="evalList"><div class="empty">Loading evaluations…</div></div></div></div>`;
const ep=renderEpoch;
api('GET','/responses?limit=500').then(evals=>{ if(ep!==renderEpoch) return; cache.evaluations=evals||[]; const box=$('evalList'); if(box) box.innerHTML=evalTable(cache.evaluations); })
.catch(e=>{ if(ep!==renderEpoch) return; const box=$('evalList'); if(box) box.innerHTML=`<div class="empty">${esc(e.message||'Failed to load evaluations')}</div>`; });
}
async function viewFirmDetail(C,id){
const ep=renderEpoch; // guards every post-await DOM write against a route change mid-fetch
let f=(cache.firms||[]).find(x=>x.id===id);
if(!f){ try{ f=await api('GET','/firms/'+encodeURIComponent(id)); }catch{ if(ep===renderEpoch) C.innerHTML='<div class="page"><div class="empty">Firm not found.</div></div>'; return; } }
if(ep!==renderEpoch) return;
setCrumb(['Dashboard','Firms',f.name]);
const card=(l,v)=>`<div class="fieldcard"><div class="lbl">${esc(l)}</div><div class="val">${v}</div></div>`;
const site=safeUrl(f.website);
C.innerHTML=`<div class="page">
<div class="kicker">Firm</div>
<div class="page-head"><div><h1>${esc(f.name)}</h1>${f.legal_name?`<div class="sub">${esc(f.legal_name)}</div>`:''}</div>
<div class="page-actions">${badge(f.status)} ${btn('Edit',{cls:'ghost',onclick:`editFirmById(${jsArg(f.id)})`})}</div></div>
<div class="fieldcards">
${card('Website',site?`<a href="${esc(site)}" target="_blank" rel="noopener">${esc(f.website)}</a>`:esc(f.website||'—'))}
${card('Email',esc(f.email||'—'))}
${card('Contact person',esc(f.contact_person||'—'))}
${card('Notes',esc(f.notes||'—'))}
</div>
<div class="card"><div class="card-head"><h2>Evaluation history</h2><div id="firmStats" class="muted" style="font-size:13px"></div></div><div id="firmEvals"><div class="empty">Loading evaluations…</div></div></div></div>`;
try{ const evals=await api('GET','/responses?firm_id='+encodeURIComponent(id)+'&limit=500');
if(ep!==renderEpoch) return;
const a=avgScore(evals), n=submittedEvals(evals).length;
const st=$('firmStats'); if(st&&n) st.innerHTML=`<span>Average score</span> <b>${esc(fmtScore(a))}</b><span class="faint">/100</span> · ${n} <span>submitted evaluations</span>`;
const box=$('firmEvals'); if(box) box.innerHTML=evalTable(evals,{showFirm:false});
}catch(e){ if(ep!==renderEpoch) return; const box=$('firmEvals'); if(box) box.innerHTML=`<div class="empty">${esc(e.message||'Failed to load evaluations')}</div>`; }
}
function editFirmById(id){ const f=(cache.firms||[]).find(x=>x.id===id); if(f) editFirm(f); }
async function viewMatterDetail(C,id){
const ep=renderEpoch;
let m=(cache.matters||[]).find(x=>x.id===id);
if(!m){ try{ m=await api('GET','/matters/'+encodeURIComponent(id)); }catch{ if(ep===renderEpoch) C.innerHTML='<div class="page"><div class="empty">Matter not found.</div></div>'; return; } }
if(ep!==renderEpoch) return;
setCrumb(['Dashboard','Matters',m.reference]);
const card=(l,v)=>`<div class="fieldcard"><div class="lbl">${esc(l)}</div><div class="val">${v}</div></div>`;
C.innerHTML=`<div class="page">
<div class="kicker">Matter</div>
<div class="page-head"><div><h1>${esc(m.reference)}</h1><div class="sub">${esc(m.title)}</div></div>
<div class="page-actions">${badge(m.status)} ${btn('Edit',{cls:'ghost',onclick:`editMatterById(${jsArg(m.id)})`})}</div></div>
<div class="fieldcards">
${card('Firm',`<a href="#/firms/${esc(m.firm_id)}">${esc(firmName(m.firm_id))}</a>`)}
${card('Type',esc(m.matter_type||'—'))}
${card('Complexity',esc(m.complexity_band||'—'))}
${card('Jurisdiction',esc(m.jurisdiction||'—'))}
${card('Billing',fmtBilling(m))}
</div>
<div class="card"><div class="card-head"><h2>Evaluations for this matter</h2></div><div id="matterEvals"><div class="empty">Loading evaluations…</div></div></div></div>`;
try{ const evals=await api('GET','/responses?matter_id='+encodeURIComponent(id)+'&limit=500');
if(ep!==renderEpoch) return;
const box=$('matterEvals'); if(box) box.innerHTML=evalTable(evals,{showMatter:false});
}catch(e){ if(ep!==renderEpoch) return; const box=$('matterEvals'); if(box) box.innerHTML=`<div class="empty">${esc(e.message||'Failed to load evaluations')}</div>`; }
}
function editMatterById(id){ const m=(cache.matters||[]).find(x=>x.id===id); if(m) editMatter(m); }
window.editFirmById=editFirmById; window.editMatterById=editMatterById;
function viewQuestionnaires(C){
setCrumb(['Dashboard','Questionnaires']);
C.innerHTML = `<div class="page">${pageHead('Questionnaires','Weighted evaluation forms.')}
${dataTable({ title:'Questionnaires', createLabel:'New questionnaire', createHref:'questionnaires/new',
columns:[ {h:'Title',f:q=>`<a class="primary-cell" href="#/questionnaires/${esc(q.id)}">${esc(q.title)}</a><span class="sub">${esc(q.key)} · v${esc(q.version)}</span>`,raw:true},
{h:'Questions',f:q=>(q.items||[]).length}, {h:'Status',f:q=>badge(q.status),raw:true} ],
rows:cache.questionnaires||[], empty:'No questionnaires yet.',
rowMenu:(ev,row)=>openMenu(ev,[ {label:'Edit',fn:()=>go('questionnaires/'+row.id)} ]) })}</div>`;
}
function viewQuestions(C){
setCrumb(['Dashboard','Questions']);
C.innerHTML = `<div class="page">${pageHead('Questions','Criteria that make up evaluation forms.')}
${dataTable({ title:'Questions', createLabel:'New question', createHref:'questions/new',
columns:[ {h:'Question',f:q=>`<span class="primary-cell">${esc(q.label)}</span><span class="sub">${esc(q.key)}</span>`,raw:true},
{h:'Category',f:q=>`<span class="chip">${esc(q.category)}</span>`,raw:true}, {h:'Answer type',f:q=>`<span class="chip">${esc(q.answer_type)}</span>`,raw:true},
{h:'Scale',f:q=>`${esc(q.scale_min)}–${esc(q.scale_max)}`} ],
rows:cache.questions||[], empty:'No questions yet.' })}</div>`;
}
function viewUsers(C){
setCrumb(['Dashboard','Users']);
// On the platform this screen is a roster plus ONE editable thing: the Counsel role. Creating a
// person, renaming them and deactivating them belong to the hub, because they are true of every
// module at once - and those buttons are absent rather than disabled, because the server refuses
// the writes and a control that can only ever produce an error is worse than no control.
const hub=state.platform;
const menu=(ev,row)=>openMenu(ev, hub
? [ {label:'Edit role',fn:()=>editUser(row)} ]
: [ {label:'Edit role',fn:()=>editUser(row)}, {label:'Deactivate',danger:true,fn:()=>deactivateUser(row)} ]);
C.innerHTML = `<div class="page">${pageHead('Users', hub?'Accounts come from the hub; the role is Counsel\'s own.':'Accounts and roles.')}
${dataTable({ title:'Users', createLabel:hub?null:'Create user', createHref:'users/new',
columns:[ {h:'Email',f:u=>`<span class="primary-cell">${esc(u.email)}</span>`,raw:true}, {h:'Name',f:u=>u.full_name},
{h:'Role',f:u=>`<span class="chip">${esc(u.role)}</span>`,raw:true}, {h:'Active',f:u=>u.is_active?badge('active'):badge('inactive'),raw:true} ],
rows:cache.users||[], empty:'No users.',
rowMenu:menu })}</div>`;
}
function viewCycles(C){
setCrumb(['Dashboard','Review cycles']);
C.innerHTML = `<div class="page">${pageHead('Review cycles','Score firms by cycle and publish rankings.')}
${dataTable({ title:'Review cycles', createLabel:'New cycle', createHref:'cycles/new',
columns:[ {h:'Name',f:c=>`<span class="primary-cell">${esc(c.name)}</span>`,raw:true}, {h:'Dates',f:c=>`${esc(c.start_date)} → ${esc(c.end_date)}`},
{h:'Status',f:c=>badge(c.status),raw:true} ],
rows:cache.cycles||[], empty:'No review cycles yet.',
rowMenu:(ev,row)=>openMenu(ev,[ {label:'Open',fn:()=>go('cycles/'+row.id)} ]) })}</div>`;
}
// The module's settings in one screen, the one Atrium shows under Ustawienia: roles, then dictionaries.
function viewSettings(C){
const roles=document.createElement('div'), dicts=document.createElement('div');
if(isModerator()) viewUsers(roles);
viewDictionaries(dicts);
C.replaceChildren(roles,dicts);
setCrumb(['Dashboard','Settings']);
}
function viewDictionaries(C){
setCrumb(['Dashboard','Dictionaries']);
const sect=(title,rows)=>`<div class="card" style="margin-bottom:16px"><div class="card-head"><h2>${esc(title)}</h2></div><div class="card-body" style="display:flex;flex-wrap:wrap;gap:8px">${rows.length?rows.map(r=>`<span class="chip">${esc(r)}</span>`).join(''):'<span class="muted">none</span>'}</div></div>`;
const enumChips = Object.keys(cache.enums||{}).map(k=>`<div style="margin-bottom:12px"><div class="kicker">${esc(k)}</div><div style="display:flex;flex-wrap:wrap;gap:6px">${enumVals(k).map(v=>`<span class="chip">${esc(v)}</span>`).join('')}</div></div>`).join('');
C.innerHTML = `<div class="page">${pageHead('Dictionaries','Reference data (read-only).')}
${sect('Practice areas',(cache.practiceAreas||[]).map(p=>p.label||p.code))}
${sect('Jurisdictions',(cache.jurisdictions||[]).map(j=>`${j.code} · ${j.label}`))}
<div class="card"><div class="card-head"><h2>Enums</h2></div><div class="card-body">${enumChips||'<span class="muted">none</span>'}</div></div></div>`;
}
// ── cycle detail + snapshots ──
async function viewCycleDetail(C,id){
const ep=renderEpoch;
// `id` is the address bar's, i.e. whatever a link put there. Nothing below is built from it: the
// cycle is looked up (once more from the server if this tab's list is stale), an unknown one is
// "not found" like a firm or a matter, and the page uses the server's own c.id from then on. The
// old fallback drew a made-up open cycle with a Close button carrying the raw id.
let c=(cache.cycles||[]).find(x=>x.id===id);
if(!c){ try{ cache.cycles=await api('GET','/review-cycles'); }catch{ /* keep the list we have */ }
if(ep!==renderEpoch) return;
c=(cache.cycles||[]).find(x=>x.id===id); }
if(!c){ C.innerHTML='<div class="page"><div class="empty">Review cycle not found.</div></div>'; return; }
setCrumb(['Dashboard','Review cycles',c.name||'Cycle']);
C.innerHTML=`<div class="page">
<div class="kicker">Review cycle</div>
<div class="page-head"><div><h1>${esc(c.name||'Cycle')}</h1><div class="sub">${esc(c.start_date||'')} → ${esc(c.end_date||'')}</div>
<div class="sub" style="margin-top:2px"><span>Firms with fewer than</span> <b>${esc(c.min_evaluations||0)}</b> <span>submitted evaluations stay provisional.</span></div></div>
<div class="page-actions">${badge(c.status)} ${c.status==='open'?btn('Close cycle',{cls:'primary',onclick:`closeCycle(${jsArg(c.id)})`}):''}</div></div>
<div class="card"><div class="card-head"><h2>Firm rankings</h2></div><div id="snaps" class="card-body"><div class="empty">Loading snapshots…</div></div></div></div>`;
try{ const snaps=await api('GET',`/review-cycles/${encodeURIComponent(c.id)}/snapshots`); if(ep!==renderEpoch) return; renderSnaps(snaps); }
catch{ if(ep!==renderEpoch) return; $('snaps').innerHTML='<div class="empty">No snapshots — close the cycle to generate rankings.</div>'; }
}
function renderSnaps(snaps){
const el=$('snaps'); if(!el) return;
if(!snaps||!snaps.length){ el.innerHTML='<div class="empty">No snapshots yet.</div>'; return; }
const firmName=(id)=>(cache.firms.find(f=>f.id===id)||{}).name||shortId(id);
el.style.padding='0';
el.innerHTML=`<table class="dt"><thead><tr><th>Firm</th><th>Composite</th><th>Completeness</th><th># evals</th><th>Ranking</th></tr></thead><tbody>
${snaps.map(s=>`<tr><td class="primary-cell">${esc(firmName(s.firm_id))}</td><td><b>${esc(s.composite_score)}</b></td>
<td>${esc(s.data_completeness??'—')}</td><td>${esc(s.evaluation_count)}</td><td>${badge(s.ranking_status)}</td></tr>`).join('')}</tbody></table>`;
}
async function closeCycle(id){ try{ const snaps=await api('POST',`/review-cycles/${id}/close`); toast('Cycle closed — rankings published'); cache.cycles=await api('GET','/review-cycles').catch(()=>cache.cycles); router(); }
catch(e){ toast(e.message||'Close failed'); } }
window.closeCycle=closeCycle;
// ═══════════════ forms ═══════════════
function formShell(C,{kicker,title,sections,onSubmit,submitLabel,backTo}){
C.innerHTML=`<div class="page" style="max-width:820px"><div class="kicker">${esc(kicker)}</div>${pageHead(title,'')}
<form id="theForm" class="card form-card">${sections}
<div class="form-foot">${btn('Cancel',{cls:'ghost',onclick:`go('${backTo}')`})}${btn(submitLabel,{cls:'primary',icon:ICN.save,attrs:'type="submit"'})}</div></form></div>`;
$('theForm').addEventListener('submit',(e)=>{e.preventDefault();onSubmit();});
}
function fieldsGrid(html){ return `<div class="form-section"><div class="grid2">${html}</div></div>`; }
function field(label,inner,{req,full}={}){ return `<label class="field ${full?'full':''}"><span class="lbl">${esc(label)}${req?' <span class="req">*</span>':''}</span>${inner}</label>`; }
// slug: derive a stable key from a name/label so users never type a "key"
function slug(s){ return ((s||'').toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'_').replace(/^_+|_+$/g,''))||('item_'+Date.now()); }
// matter billing: amount field for fixed-fee/hourly, a notes field for "other"
function onBillChange(){ var v=($('m_bill')||{}).value, box=$('m_bill_extra'); if(!box) return;
if(v==='fixed_fee'||v==='hourly_rate') box.innerHTML=field(v==='hourly_rate'?'Hourly rate':'Fixed fee amount','<input id="m_bill_amount" type="number" step="0.01" min="0" placeholder="amount">');
else if(v==='other') box.innerHTML=field('Billing notes','<input id="m_bill_notes" placeholder="how this matter is billed">');
else box.innerHTML=''; }
// client-side table filter, wired to the toolbar search box (fixes the dead Filters/search)
function filterTable(input){ var card=input.closest('.card'); if(!card) return; var q=input.value.trim().toLowerCase();
card.querySelectorAll('tbody tr').forEach(function(tr){ tr.style.display=(!q||tr.textContent.toLowerCase().indexOf(q)>=0)?'':'none'; }); }
function formFirm(C){ setCrumb(['Dashboard','Firms','New firm']);
formShell(C,{kicker:'Firm',title:'Create firm',backTo:'firms',submitLabel:'Create firm',
sections:`<div class="form-section"><h3>Firm details</h3><div class="grid2">
${field('Name','<input id="f_name" required>',{req:true})}
${field('Status',`<select id="f_status">${optionTags(enumVals('firm_status'),'active')}</select>`)}
${field('Email','<input id="f_email" type="email" placeholder="contact@firm.example">')}
${field('Contact person','<input id="f_contact" placeholder="full name">')}
${field('Notes','<textarea id="f_notes"></textarea>',{full:true})}</div></div>`,
onSubmit:async()=>{ try{ await api('POST','/firms',{name:$('f_name').value.trim(),email:$('f_email').value.trim()||null,contact_person:$('f_contact').value.trim()||null,status:$('f_status').value,notes:$('f_notes').value.trim()||null});
cache.firms=await api('GET','/firms'); toast('Firm created'); go('firms'); }catch(e){ toast(e.message||'Failed'); } } });
}
function formMatter(C){ setCrumb(['Dashboard','Matters','New matter']);
const opt=(arr,vk,lf)=>arr.map(x=>`<option value="${esc(x[vk])}">${esc(lf(x))}</option>`).join('');
formShell(C,{kicker:'Matter',title:'Create matter',backTo:'matters',submitLabel:'Create matter',
sections:`<div class="form-section"><h3>Matter details</h3><div class="grid2">
${field('Title','<input id="m_title" required>',{req:true})}
${field('Firm',`<select id="m_firm" required>${opt(cache.firms,'id',f=>f.name)}</select>`,{req:true})}
${field('Type',`<select id="m_type">${optionTags(enumVals('matter_type'),'advisory')}</select>`)}
${field('Jurisdiction','<input id="m_jur" placeholder="optional, e.g. New York">')}
${field('Billing method',`<select id="m_bill" onchange="onBillChange()"><option value="">—</option><option value="fixed_fee">fixed fee</option><option value="hourly_rate">hourly rate</option><option value="other">other</option></select>`)}
<div id="m_bill_extra"></div>
${field('Complexity',`<select id="m_cplx">${optionTags(enumVals('complexity_band'),'standard')}</select>`)}
${isModerator()?field('Responsible person',`<select id="m_owner"><option value="">responsible = me</option>${opt(cache.users,'id',u=>u.full_name+' ('+u.role+')')}</select>`):''}
</div></div>`,
onSubmit:async()=>{ try{ const body={reference:'M-'+Date.now(),title:$('m_title').value.trim()||'Untitled matter',
firm_id:$('m_firm').value,matter_type:$('m_type').value,complexity_band:$('m_cplx').value};
const jur=$('m_jur').value.trim(); if(jur) body.jurisdiction=jur;
const bm=$('m_bill').value; if(bm){ body.billing_method=bm; const amt=$('m_bill_amount'); const nts=$('m_bill_notes'); if(amt&&amt.value!=='') body.budget_estimate=Number(amt.value); if(nts&&nts.value.trim()) body.billing_notes=nts.value.trim(); }
const owner=$('m_owner')&&$('m_owner').value; if(owner) body.matter_owner_id=owner;
await api('POST','/matters',body); cache.matters=await api('GET','/matters'); toast('Matter created'); go('matters'); }catch(e){ toast(e.message||'Failed'); } } });
}
function formUser(C){ setCrumb(['Dashboard','Users','Create user']);
formShell(C,{kicker:'User',title:'Create user',backTo:'users',submitLabel:'Create user',
sections:`<div class="form-section"><h3>Account</h3><div class="grid2">
${field('Email','<input id="u_email" type="email" required>',{req:true})}
${field('Full name','<input id="u_name" required>',{req:true})}
${field('Password','<input id="u_pass" type="password" required>',{req:true})}
${field('Role',`<select id="u_role">${optionTags(enumVals('user_role'),'matter_owner')}</select>`)}</div></div>`,
onSubmit:async()=>{ try{ await api('POST','/users',{email:$('u_email').value.trim(),full_name:$('u_name').value.trim(),password:$('u_pass').value,role:$('u_role').value});
cache.users=await api('GET','/users'); toast('User created'); go('users'); }catch(e){ toast(e.message||'Failed'); } } });
}
function formCycle(C){ setCrumb(['Dashboard','Review cycles','New cycle']);
formShell(C,{kicker:'Review cycle',title:'Create review cycle',backTo:'cycles',submitLabel:'Create cycle',
sections:`<div class="form-section"><h3>Cycle</h3><div class="grid2">
${field('Name','<input id="c_name" required>',{req:true})}
${field('Min evaluations','<input id="c_min" type="number" value="3" min="0"><span class="muted" style="font:400 12px/1.4 var(--font-sans)">How many submitted evaluations a firm needs to be ranked in this cycle.</span>')}
${field('Start date','<input id="c_start" type="date" required>',{req:true})}
${field('End date','<input id="c_end" type="date" required>',{req:true})}</div></div>`,
onSubmit:async()=>{ try{ await api('POST','/review-cycles',{name:$('c_name').value.trim(),start_date:$('c_start').value,end_date:$('c_end').value,min_evaluations:Number($('c_min').value)||3});
cache.cycles=await api('GET','/review-cycles'); toast('Cycle created'); go('cycles'); }catch(e){ toast(e.message||'Failed'); } } });
}
function formQuestion(C){ setCrumb(['Dashboard','Questions','New question']);
formShell(C,{kicker:'Question',title:'Create question',backTo:'questions',submitLabel:'Create question',
sections:`<div class="form-section"><h3>Criterion</h3><div class="grid2">
${field('Question text','<input id="q_label" required>',{req:true,full:true})}
${field('Category',`<select id="q_cat">${optionTags(['qualitative','quantitative'],'qualitative')}</select>`)}
${field('Answer type',`<select id="q_at">${optionTags(['scale','single_choice','boolean','numeric','text'],'scale')}</select>`)}
${field('Scale min','<input id="q_min" type="number" value="1">')}
${field('Scale max','<input id="q_max" type="number" value="5">')}
${field('Help text','<textarea id="q_help"></textarea>',{full:true})}</div></div>`,
onSubmit:async()=>{ try{ await api('POST','/questions',{key:slug($('q_label').value.trim()),label:$('q_label').value.trim(),category:$('q_cat').value,answer_type:$('q_at').value,scale_min:Number($('q_min').value),scale_max:Number($('q_max').value),help_text:$('q_help').value.trim()||null,options:[]});
cache.questions=await api('GET','/questions'); toast('Question created'); go('questions'); }catch(e){ toast(e.message||'Failed'); } } });
}
// ── questionnaire builder (counsel review 2026-07-02: create was name+description only — no
// way to attach questions, assign a new question to a form, or edit per-question weights) ──
function qbSum(){ let t=0;
document.querySelectorAll('.qb-inc').forEach(cb=>{ const w=document.querySelector(`.qb-w[data-q="${cb.dataset.q}"]`); if(w){ w.disabled=!cb.checked; if(cb.checked) t+=Number(w.value||0); } });
const el=$('qbTotal'); if(el){ el.textContent=t.toFixed(2); el.style.color=Math.abs(t-1)<=0.001?'var(--success)':'var(--danger)'; } }
window.qbSum=qbSum;
function formQuestionnaire(C,editId){
const editing=editId?(cache.questionnaires||[]).find(q=>q.id===editId):null;
if(editId&&!editing){ C.innerHTML='<div class="page"><div class="empty">Questionnaire not found.</div></div>'; return; }
setCrumb(['Dashboard','Questionnaires',editing?editing.title:'New questionnaire']);
const byId={}; (editing?(editing.items||[]):[]).forEach(it=>{ byId[it.question_id]=it; });
// in edit mode show the form's own question order first, then the remaining questions
const qsAll=[...(cache.questions||[])].sort((a,b)=>{ const ia=byId[a.id],ib=byId[b.id];
if(ia&&ib) return ia.display_order-ib.display_order; if(ia) return -1; if(ib) return 1; return 0; });
const qRows=qsAll.map(q=>{ const it=byId[q.id];
return `<div style="display:flex;align-items:center;gap:12px;padding:8px 0;border-bottom:1px solid var(--border)">
<label class="checkbox" style="flex:1;min-width:0"><input type="checkbox" class="qb-inc" data-q="${esc(q.id)}" ${it?'checked':''} onchange="qbSum()"> <span style="font-weight:500">${esc(q.label)}</span> <span class="chip">${esc(q.category)}</span></label>
<label style="display:flex;align-items:center;gap:6px;font:400 13px/1 var(--font-sans);color:var(--text-muted)"><span>Weight</span>
<input type="number" class="qb-w" data-q="${esc(q.id)}" step="0.05" min="0" max="1" value="${it?esc(Number(it.weight)):''}" style="width:90px" oninput="qbSum()" ${it?'':'disabled'}></label></div>`;
}).join('');
formShell(C,{kicker:'Questionnaire',title:editing?'Edit questionnaire':'Create questionnaire',backTo:'questionnaires',
submitLabel:editing?'Save changes':'Create questionnaire',
sections:`<div class="form-section"><h3>Form</h3><div class="grid2">
${field('Name',`<input id="qn_title" required value="${editing?esc(editing.title):''}">`,{req:true,full:true})}
${field('Description',`<textarea id="qn_desc">${editing?esc(editing.description||''):''}</textarea>`,{full:true})}</div></div>
<div class="form-section" style="border-top:1px solid var(--border)"><h3>Questions &amp; weights</h3>
<p class="muted" style="margin:0 0 10px">Tick the questions to include and give each a weight — weights must sum to exactly 1.0.</p>
${qRows||'<span class="muted">No questions yet — create questions first.</span>'}
<div style="margin-top:12px;font-weight:600"><span>Weights sum:</span> <span id="qbTotal">0.00</span> <span class="faint">/ 1.00</span></div></div>`,
onSubmit:async()=>{
const items=[]; let nextOrder=editing?Math.max(-1,...((editing.items||[]).map(i=>i.display_order)))+1:0;
document.querySelectorAll('.qb-inc').forEach(cb=>{ if(!cb.checked) return;
const qid=cb.dataset.q, w=document.querySelector(`.qb-w[data-q="${qid}"]`);
const q=(cache.questions||[]).find(x=>x.id===qid)||{};
const prev=byId[qid]; // kept questions keep their order + required flag; new ones append
items.push({question_id:qid,display_order:prev?prev.display_order:nextOrder++,
weight:Number((w&&w.value)||0),is_required:prev?prev.is_required:q.category==='qualitative'}); });
if(items.length){ const total=items.reduce((s,i)=>s+i.weight,0);
if(Math.abs(total-1)>0.001){ toast('Question weights must sum to 1.0'); return; } }
try{
const title=$('qn_title').value.trim(), desc=$('qn_desc').value.trim()||null;
if(editing){
// Send items ONLY when they actually changed: the backend freezes questions/weights
// (409) once the form has responses, but metadata must stay editable from the UI.
const canon=a=>a.map(i=>i.question_id+':'+Number(i.weight)).sort().join('|');
const body={title:title,description:desc};
if(canon(items)!==canon(editing.items||[])) body.items=items;
await api('PATCH','/questionnaires/'+editing.id,body); toast('Questionnaire saved');
}
else{ await api('POST','/questionnaires',{key:slug(title),title:title,version:1,description:desc,items:items}); toast('Questionnaire created'); }
cache.questionnaires=await api('GET','/questionnaires'); go('questionnaires');
}catch(e){ toast(e.message||'Failed'); } } });
qbSum();
}
// ── response submit (preserves the original scoring console flow) ──
function viewResponses(C){
setCrumb(['Dashboard','Submit evaluation']);
const opt=(arr,vk,lf,ph)=>`<option value="">${esc(ph)}</option>`+arr.map(x=>`<option value="${esc(x[vk])}">${esc(lf(x))}</option>`).join('');
C.innerHTML=`<div class="page" style="max-width:820px">${pageHead('Submit evaluation','Sign in as the matter owner. Scale answers feed the composite score.')}
<form class="card form-card" id="respForm"><div class="form-section"><h3>Evaluation</h3><div class="grid2">
${field('Questionnaire',`<select id="r_qnn">${opt(cache.questionnaires,'id',q=>q.title+' v'+q.version,'questionnaire…')}</select>`)}
${field('Matter',`<select id="r_matter">${opt(cache.matters,'id',m=>m.reference+' — '+m.title,'matter…')}</select>`)}
${field('Review cycle',`<select id="r_cycle">${opt(cache.cycles,'id',c=>c.name+' ('+c.status+')','cycle…')}</select>`)}
${field('Recommend?',`<select id="r_rec"><option value="">—</option><option value="true">yes</option><option value="false">no</option></select>`)}
</div></div>
<div class="form-section" style="border-top:1px solid var(--border)"><h3>Answers</h3><div id="r_questions" class="muted">Pick a questionnaire…</div>
<label class="field full" style="margin-top:16px">Overall comment (≤280)<textarea id="r_comment" maxlength="280"></textarea></label></div>
<div class="form-foot">${btn('Save draft',{cls:'ghost',onclick:'submitResponse(false)'})}${btn('Submit evaluation',{cls:'primary',icon:ICN.save,onclick:'submitResponse(true)'})}</div></form>
<div id="respResult" style="margin-top:14px"></div><div id="respHistory"></div></div>`;
$('r_qnn').addEventListener('change',renderQuestionsForQnn);
$('respForm').addEventListener('submit',e=>e.preventDefault());
}
function renderQuestionsForQnn(){
const qnn=(cache.questionnaires||[]).find(q=>q.id===$('r_qnn').value);
const box=$('r_questions'); if(!qnn){ box.innerHTML='<span class="muted">Pick a questionnaire…</span>'; return; }
const byId=Object.fromEntries((cache.questions||[]).map(q=>[q.id,q]));
const items=[...(qnn.items||[])].sort((a,b)=>a.display_order-b.display_order);
let h='';
for(const it of items){ const q=byId[it.question_id]; if(!q) continue;
const tag=`<span class="chip">${esc(q.category)}</span> <span class="faint">w=${esc(it.weight)}</span>`;
let fieldEl;
if((q.answer_type==='scale'||q.answer_type==='single_choice')&&q.options&&q.options.length){
// Number() strips pydantic's Decimal serialization ("5.00" → 5) so the composed text
// matches the I18N.pl '5 — Exemplary' keys and reads clean.
const opts=[...q.options].sort((a,b)=>a.display_order-b.display_order).map(o=>`<option value="${esc(o.id)}">${o.value!=null?esc(Number(o.value))+' — ':''}${esc(o.label)}</option>`).join('');
fieldEl=`<select data-q="${esc(q.id)}" data-kind="option"><option value="">—</option>${opts}</select>`;
} else if(q.answer_type==='boolean'){ fieldEl=`<select data-q="${esc(q.id)}" data-kind="bool"><option value="">—</option><option value="true">yes</option><option value="false">no</option></select>`; }
else if(q.answer_type==='numeric'){
if(Number(q.scale_min)===0&&Number(q.scale_max)===100){
// percent question (counsel review 2026-07-02): a picker capped at 100%, not a free number
let opts=''; for(let p=100;p>=0;p-=5) opts+=`<option value="${p}">${p}%</option>`;
fieldEl=`<select data-q="${esc(q.id)}" data-kind="num"><option value="">—</option>${opts}</select>`;
} else fieldEl=`<input type="number" step="0.01" min="${esc(q.scale_min)}" max="${esc(q.scale_max)}" data-q="${esc(q.id)}" data-kind="num">`;
}
else { fieldEl=`<input type="text" data-q="${esc(q.id)}" data-kind="text">`; }
h+=`<div style="display:flex;gap:12px;align-items:center;margin:8px 0"><label style="flex:1;font-weight:500">${esc(q.label)} ${tag}</label><div style="width:240px">${fieldEl}</div></div>`;
}
box.innerHTML=h||'<span class="muted">No questions in this set.</span>';
}
function collectItems(){ const items=[]; for(const el of $('r_questions').querySelectorAll('[data-q]')){ const qid=el.dataset.q,kind=el.dataset.kind,v=el.value; if(v===''||v==null) continue;
if(kind==='option') items.push({question_id:qid,answer_option_id:v}); else if(kind==='bool') items.push({question_id:qid,bool_value:v==='true'});
else if(kind==='num') items.push({question_id:qid,numeric_value:Number(v)}); else items.push({question_id:qid,text_value:v}); } return items; }
async function submitResponse(submit){
const rec=$('r_rec').value;
const body={questionnaire_id:$('r_qnn').value,matter_id:$('r_matter').value||null,review_cycle_id:$('r_cycle').value||null,
recommend:rec===''?null:rec==='true',overall_comment:$('r_comment').value||null,submit:!!submit,items:collectItems()};
if(!body.questionnaire_id){ toast('Pick a questionnaire'); return; }
try{ const r=await api('POST','/responses',body); lastResponseId=r.id;
$('respResult').innerHTML=`<div class="banner"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12l5 5l10 -10"/></svg><span>Score <b>${esc(fmtScore(r.score))}</b>/100 · ${esc(r.status)} · ${esc(shortId(r.id))} ${btn('View history',{cls:'ghost sm',onclick:'showHistory()'})}</span></div>`;
const hb=$('respHistory'); if(hb) hb.innerHTML=''; // a fresh save invalidates the shown history
api('GET','/responses?limit=500').then(d=>cache.evaluations=d).catch(()=>{}); // keep list views fresh
toast('Evaluation '+(submit?'submitted':'saved')); }catch(e){ toast(e.message||'Failed'); }
}
async function showHistory(){ if(!lastResponseId) return; const box=$('respHistory'); if(!box) return;
try{ const revs=await api('GET',`/responses/${lastResponseId}/history`);
if(!revs||!revs.length){ box.innerHTML=`<div class="card" style="margin-top:12px"><div class="empty">No history yet.</div></div>`; return; }
// replace, never append — repeated clicks must not stack empty "History" cards
box.innerHTML=`<div class="card" style="margin-top:12px"><div class="card-head"><h2>History</h2></div><div class="dt-scroll"><table class="dt"><thead><tr><th>Rev</th><th>Reason</th><th>Score</th><th>When</th></tr></thead><tbody>
${revs.map(r=>`<tr><td>${esc(r.revision_no)}</td><td>${esc(r.change_reason||'')}</td><td>${esc(fmtScore(r.snapshot&&r.snapshot.score))}</td><td>${esc(new Date(r.created_at).toLocaleString())}</td></tr>`).join('')}</tbody></table></div></div>`;
}catch(e){ toast(e.message||'Failed'); } }
window.submitResponse=submitResponse; window.showHistory=showHistory;
// ═══════════════ edit dialogs ═══════════════
// A dialog keeps keyboard focus inside itself (the page behind is inert while it is open — aria-modal
// alone does not stop Tab) and hands focus back to whatever opened it. The opener is taken BEFORE the
// page goes inert, which takes focus away from it; a dialog opened from another keeps the first opener.
let _modalOpener=null;
function rememberOpener(){ const a=document.activeElement; if(!_modalOpener&&a&&a!==document.body&&!$('modalRoot').contains(a)) _modalOpener=a; }
function modal(title,inner,onSave,saveLabel){
rememberOpener();
$('modalRoot').innerHTML=`<div class="overlay" onclick="if(event.target===this)closeModal()"><div class="card" role="dialog" aria-modal="true" aria-labelledby="modalTitle" style="width:440px;max-width:92vw"><div class="card-head"><h2 id="modalTitle">${esc(title)}</h2></div>
<div class="card-body">${inner}</div><div class="form-foot">${btn('Cancel',{cls:'ghost',onclick:'closeModal()'})}${btn(saveLabel||'Save',{cls:'primary',attrs:'id="modalSave"'})}</div></div></div>`;
$('modalSave').onclick=onSave;
$('app').inert=true;
const first=$('modalRoot').querySelector('input:not([type=hidden]),select,textarea')||$('modalRoot').querySelector('.card button');
if(first) first.focus();
}
function closeModal(){ const was=!!$('modalRoot').innerHTML; $('modalRoot').innerHTML=''; $('app').inert=false;
if(was&&_modalOpener&&document.contains(_modalOpener)) _modalOpener.focus(); _modalOpener=null; } window.closeModal=closeModal;
function editFirm(f){ modal('Edit firm',`${field('Name',`<input id="ef_name" value="${esc(f.name)}">`)}${field('Status',`<select id="ef_status">${optionTags(enumVals('firm_status'),f.status)}</select>`,{})}`,
async()=>{ try{ await api('PATCH','/firms/'+f.id,{name:$('ef_name').value.trim(),status:$('ef_status').value}); cache.firms=await api('GET','/firms'); closeModal(); toast('Saved'); router(); }catch(e){ toast(e.message||'Failed'); } }); }
function editMatter(m){ modal('Edit matter',`${field('Status',`<select id="em_status">${optionTags(enumVals('matter_status')||['open','in_progress','closed','cancelled'],m.status)}</select>`)}`,
async()=>{ try{ await api('PATCH','/matters/'+m.id,{status:$('em_status').value}); cache.matters=await api('GET','/matters'); closeModal(); toast('Saved'); router(); }catch(e){ toast(e.message||'Failed'); } }); }
function editUser(u){ modal('Edit role',`${field('Role',`<select id="eu_role">${optionTags(enumVals('user_role'),u.role)}</select>`)}`,
async()=>{ try{ await api('PATCH','/users/'+u.id,{role:$('eu_role').value}); cache.users=await api('GET','/users'); closeModal(); toast('Saved'); router(); }catch(e){ toast(e.message||'Failed'); } }); }
async function deactivateUser(u){ try{ await api('POST','/users/'+u.id+'/deactivate'); cache.users=await api('GET','/users'); toast('Deactivated'); router(); }catch(e){ toast(e.message||'Failed'); } }
// ═══════════════ overflow menu ═══════════════
function openMenu(ev,items){ ev.stopPropagation(); document.querySelectorAll('.menu').forEach(m=>m.remove());
const trigger=ev.currentTarget;
const m=document.createElement('div'); m.className='menu';
m.innerHTML=items.map((it,i)=>`<button class="${it.danger?'danger':''}" data-i="${i}">${esc(it.label)}</button>`).join('');
document.body.appendChild(m); const r=trigger.getBoundingClientRect();
m.style.top=(r.bottom+4)+'px'; m.style.left=(r.right-m.offsetWidth)+'px';
// The keyboard's half: focus moves into the menu, Escape or Tab-ing out closes it, and focus goes
// back to the ⋯ button — so a dialog an item opens hands focus back there too.
let closed=false;
const close=(back)=>{ if(closed) return; closed=true; m.remove(); if(back&&document.contains(trigger)) trigger.focus(); };
m.querySelectorAll('button').forEach(b=>b.onclick=()=>{ close(true); items[+b.dataset.i].fn(); });
m.addEventListener('keydown',(e)=>{ if(e.key==='Escape'){ e.stopPropagation(); close(true); } });
// Deferred: Chrome fires focusout from inside remove() itself, and removing the menu there makes
// the outer remove() throw NotFoundError before focus is handed back.
m.addEventListener('focusout',(e)=>{ if(!m.contains(e.relatedTarget)) setTimeout(()=>close(false),0); });
const firstItem=m.querySelector('button'); if(firstItem) firstItem.focus();
setTimeout(()=>document.addEventListener('click',function h(){ m.remove(); document.removeEventListener('click',h); }),0);
}
window.openMenu=openMenu; window.editFirm=editFirm; window.editMatter=editMatter; window.editUser=editUser; window.deactivateUser=deactivateUser;
const shortId=(id)=>id?String(id).slice(0,8):''; window.shortId=shortId;
// ═══════════════ command palette (global search) ═══════════════
function openPalette(){ rememberOpener(); $('modalRoot').innerHTML=`<div class="overlay" onclick="if(event.target===this)closeModal()"><div class="palette" role="dialog" aria-modal="true" aria-label="Search">
<div class="pinp">${svg('<path d="M3 10a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"/> <path d="M21 21l-6 -6"/>',18)}<input id="pq" placeholder="Search firms, matters, questions, responses…" aria-label="Search" autocomplete="off"></div>
<div class="presults" id="presults"><div class="empty">Type to search.</div></div></div></div>`;
$('app').inert=true;
const inp=$('pq'); inp.focus(); let t;
inp.oninput=()=>{ clearTimeout(t); t=setTimeout(()=>paletteSearch(inp.value),220); };
}
async function paletteSearch(q){ q=q.trim(); const box=$('presults'); if(!box) return; if(!q){ box.innerHTML='<div class="empty">Type to search.</div>'; return; }
try{ const r=await api('GET',`/search?q=${encodeURIComponent(q)}`); const hits=(r.hits||[]);
if(!hits.length){ box.innerHTML='<div class="empty">No results.</div>'; return; }
const groups={}; hits.forEach(h=>{ (groups[h.type]=groups[h.type]||[]).push(h); });
box.innerHTML=Object.keys(groups).map(g=>`<div class="pgroup">${esc(g)}</div>`+groups[g].map(h=>`<div class="presult" data-type="${esc(h.type)}" data-id="${esc(h.id)}"><span class="pt">${esc(h.title||shortId(h.id))}</span><span class="pr">${esc(g)} · ${esc((h.rank||0).toFixed?h.rank.toFixed(2):h.rank)}</span></div>`).join('')).join('');
// counsel review 2026-07-02: hits were dead text — clicking one must open the record
box.querySelectorAll('.presult').forEach(el=>{ el.onclick=()=>openSearchHit(el.dataset.type,el.dataset.id); });
}catch(e){ box.innerHTML=`<div class="empty">${esc(e.message||'Search failed')}</div>`; }
}
function openSearchHit(type,id){ closeModal();
if(type==='firm') go('firms/'+id);
else if(type==='matter') go('matters/'+id);
else if(type==='response') go('evaluations');
else if(type==='question') go('questions');
else go('');
}
window.openPalette=openPalette; window.openSearchHit=openSearchHit;
// ═══════════════ theme (light / dark / system) ═══════════════
const TH_ICN={ system:'<path d="M3 5a1 1 0 0 1 1 -1h16a1 1 0 0 1 1 1v10a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1v-10"/> <path d="M7 20h10"/> <path d="M9 16v4"/> <path d="M15 16v4"/>',
light:'<path d="M8 12a4 4 0 1 0 8 0a4 4 0 1 0 -8 0"/> <path d="M3 12h1m8 -9v1m8 8h1m-9 8v1m-6.4 -15.4l.7 .7m12.1 -.7l-.7 .7m0 11.4l.7 .7m-12.1 -.7l-.7 .7"/>',
dark:'<path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454l0 .008"/>' };
function resolveTheme(m){ return (m==='dark'||(m==='system'&&window.matchMedia&&matchMedia('(prefers-color-scheme:dark)').matches))?'dark':'light'; }
function themeMode(){ return localStorage.getItem('cs_theme')||'system'; }
function applyTheme(m){ document.documentElement.dataset.theme=resolveTheme(m);
document.querySelectorAll('.js-theme').forEach(b=>{ b.innerHTML=svg(TH_ICN[m]||TH_ICN.system); b.title='Theme: '+m+' — click to change'; }); }
// Default is "system" (no stored value → follows the OS) for a flash-free first paint. The toggle
// then flips light⇄dark off the *currently shown* theme, so every click visibly changes it — the old
// system→light→dark cycle had a "dead" click that left the colors unchanged (e.g. system→light when
// the OS is already light), which read as a broken toggle.
function cycleTheme(){ const m=(document.documentElement.dataset.theme==='dark')?'light':'dark'; try{ localStorage.setItem('cs_theme',m); }catch(e){} applyTheme(m); }
if(window.matchMedia){ matchMedia('(prefers-color-scheme:dark)').addEventListener('change',()=>{ if(themeMode()==='system') document.documentElement.dataset.theme=resolveTheme('system'); }); }
// ═══════════════ wiring ═══════════════
$('loginForm').addEventListener('submit',doLogin);
// The refusal card's clean exit: POST /auth/logout resolves the token itself rather than going through
// the guard that just refused this person, so the session really is revoked.
$('btnRefusedOut').onclick=doLogout;
$('userMenu').onclick=(e)=>openMenu({stopPropagation(){},currentTarget:$('userMenu')},[ {label:'Sign out',danger:true,fn:doLogout} ]);
$('navToggle').onclick=()=>{
if(window.innerWidth<=880){ $('sidebar').classList.toggle('open'); return; }
const a=$('app'); a.classList.toggle('nav-collapsed');
try{ localStorage.setItem('om:navCollapsed', a.classList.contains('nav-collapsed')?'1':'0'); }catch{}
};
$('navScrim').onclick=()=>$('sidebar').classList.remove('open');
window.addEventListener('resize',()=>{ if(window.innerWidth>880) $('sidebar').classList.remove('open'); fitOrg(); });
// Re-fit the workspace chip whenever the topbar changes width (viewport resize, sidebar collapse/expand).
try{ if(window.ResizeObserver) new ResizeObserver(fitOrg).observe(document.querySelector('.topbar')); }catch(e){}
$('navSearch').addEventListener('input',(e)=>{ navFilter=e.target.value; renderNav(); });
try{ if(localStorage.getItem('om:navCollapsed')==='1') $('app').classList.add('nav-collapsed'); }catch{}
$('btnLog').onclick=()=>$('logPanel').classList.toggle('hidden');
$('logClose').onclick=()=>$('logPanel').classList.add('hidden');
$('btnPalette').onclick=openPalette;
document.querySelectorAll('.js-theme').forEach(b=>b.onclick=cycleTheme); applyTheme(themeMode());
document.addEventListener('keydown',(e)=>{ if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='k'){ e.preventDefault(); if(state.user) openPalette(); } if(e.key==='Escape') closeModal(); });
// ═══════════════ i18n — Option 1: native + a Polish dictionary ═══════════════
// Translations are applied to the rendered DOM by localize(); each node's pristine English is
// remembered (WeakMap) so switching back to EN is lossless. A MutationObserver re-localizes every
// dynamic render, so the existing English-string templates need no changes. Data (firm/matter
// names, etc.) is never a dictionary key, so it stays untouched.
const I18N = { pl: {
// nav groups
'OVERVIEW':'PRZEGLĄD','DIRECTORY':'KATALOG','QUESTIONNAIRES':'KWESTIONARIUSZE','EVALUATIONS':'OCENY','REVIEW':'CYKLE PRZEGLĄDU','ADMIN':'ADMINISTRACJA',
// nav items / row menu / user menu
'Dashboard':'Pulpit','Firms':'Kancelarie','Matters':'Sprawy','Questionnaires':'Kwestionariusze','Questions':'Pytania','Submit evaluation':'Wyślij ocenę','Review cycles':'Cykle przeglądu','Users':'Użytkownicy','Dictionaries':'Słowniki','Sign out':'Wyloguj','Edit':'Edytuj','Edit role':'Edytuj rolę','Deactivate':'Dezaktywuj','Open':'Otwórz',
// login
'Sign in':'Zaloguj się','You are signed in, but you do not have access to Counsel.':'Masz zalogowane konto, ale nie masz dostępu do Counsel.','Ask an administrator for access.':'Poproś administratora o dostęp.','Go to the platform':'Przejdź do platformy','Sign in with your workspace credentials':'Zaloguj się danymi logowania do przestrzeni roboczej','Sign in at the hub':'Zaloguj się w centrum','One account for the whole platform':'Jedno konto dla całej platformy','Sign in once at the hub and you arrive here already signed in. There is no separate password for Counsel.':'Zaloguj się raz w centrum, a tutaj trafisz już zalogowany. Counsel nie ma osobnego hasła.',"Accounts come from the hub; the role is Counsel's own.":'Konta pochodzą z centrum; rola jest własna dla Counsel.','Access your workspace':'Wejdź do swojej przestrzeni roboczej','External-counsel scoring':'Ocena kancelarii zewnętrznych','Email':'E-mail','Password':'Hasło','bootstrap password':'hasło robocze','Remember me':'Zapamiętaj mnie','Forgot password?':'Nie pamiętasz hasła?',
// topbar / search
'Skip to content':'Przejdź do treści','Close':'Zamknij','Search':'Szukaj',
'Toggle sidebar':'Przełącz panel boczny','Request log':'Dziennik żądań','Search (Ctrl/⌘K)':'Szukaj (Ctrl/⌘K)','Theme':'Motyw','Search…':'Szukaj…','Search navigation':'Przeszukaj nawigację','Search firms, matters, questions, responses…':'Szukaj kancelarii, spraw, pytań, odpowiedzi…',
// dashboard
'Overview of firms, matters, and review activity.':'Przegląd kancelarii, spraw i aktywności przeglądów.','External counsel on record':'Zarejestrowane kancelarie zewnętrzne','Engagements being evaluated':'Oceniane sprawy','Open review cycles':'Otwarte cykle przeglądu','Accepting evaluations':'Przyjmują oceny','Recent matters':'Ostatnie sprawy','Latest engagements':'Najnowsze sprawy','Status by cycle':'Status według cyklu','Quick actions':'Szybkie akcje','Common tasks':'Częste zadania','New firm':'Nowa kancelaria','New matter':'Nowa sprawa','Evaluate':'Oceń','No matters':'Brak spraw','No cycles':'Brak cykli',
// page-head subtitles
'Law firms evaluated in review cycles. Click a firm to see its evaluation history.':'Kancelarie prawne oceniane w cyklach przeglądu. Kliknij kancelarię, aby zobaczyć historię jej ocen.','Engagements scored by their owners. Click a matter to see how it was evaluated.':'Sprawy oceniane przez ich właścicieli. Kliknij sprawę, aby zobaczyć jej oceny.','Weighted evaluation forms.':'Ważone formularze oceny.','Criteria that make up evaluation forms.':'Kryteria tworzące formularze oceny.','Score firms by cycle and publish rankings.':'Oceniaj kancelarie w cyklach i publikuj rankingi.','Sign in as the matter owner. Scale answers feed the composite score.':'Zaloguj się jako właściciel sprawy. Odpowiedzi w skali zasilają wynik łączny.','Accounts and roles.':'Konta i role.','Reference data (read-only).':'Dane referencyjne (tylko do odczytu).','Every submitted evaluation, with its score.':'Wszystkie wysłane oceny wraz z wynikiem.',
// tables / pager
'Filters':'Filtry','Actions':'Akcje','Name':'Nazwa','Status':'Status','Website':'Strona WWW','ID':'ID','Matter':'Sprawa','Firm':'Kancelaria','Type':'Typ','Complexity':'Złożoność','Title':'Tytuł','Category':'Kategoria','Answer type':'Typ odpowiedzi','Scale':'Skala','Role':'Rola','Active':'Aktywny','Dates':'Daty','Min evals':'Min. ocen','Question':'Pytanie','Showing':'Wyświetlanie','of':'z','Previous':'Wstecz','Next':'Dalej',
'No firms yet — create one to start.':'Brak kancelarii — utwórz pierwszą, aby zacząć.','No matters yet.':'Brak spraw.','No questionnaires yet.':'Brak kwestionariuszy.','No questions yet.':'Brak pytań.','No review cycles yet.':'Brak cykli przeglądu.','No users.':'Brak użytkowników.','No records yet.':'Brak rekordów.',
// create labels / form titles / kickers / submit
'Create user':'Utwórz użytkownika','New cycle':'Nowy cykl','New question':'Nowe pytanie','New questionnaire':'Nowy kwestionariusz','Create firm':'Utwórz kancelarię','Create matter':'Utwórz sprawę','Create question':'Utwórz pytanie','Create questionnaire':'Utwórz kwestionariusz','Create review cycle':'Utwórz cykl przeglądu','Create cycle':'Utwórz cykl','User':'Użytkownik','Questionnaire':'Kwestionariusz','Review cycle':'Cykl przeglądu',
// form section headers
'Firm details':'Dane kancelarii','Matter details':'Dane sprawy','Account':'Konto','Cycle':'Cykl','Criterion':'Kryterium','Form':'Formularz','Evaluation':'Ocena','Answers':'Odpowiedzi','History':'Historia','Firm rankings':'Rankingi kancelarii',
// field labels
'Description':'Opis','End date':'Data zakończenia','Full name':'Imię i nazwisko','Help text':'Tekst pomocy','Jurisdiction':'Jurysdykcja','Key':'Klucz','Label':'Etykieta','Legal name':'Nazwa prawna','Min evaluations':'Min. liczba ocen','Notes':'Notatki','Owner':'Właściciel','Practice area':'Obszar praktyki','Recommend?':'Polecasz?','Reference':'Sygnatura','Scale max':'Maks. skali','Scale min':'Min. skali','Start date':'Data rozpoczęcia','Version':'Wersja','owner = me':'właściciel = ja',
// modals / actions
'Edit firm':'Edytuj kancelarię','Edit matter':'Edytuj sprawę','Cancel':'Anuluj','Save':'Zapisz','Save draft':'Zapisz wersję roboczą','Close cycle':'Zamknij cykl','View history':'Pokaż historię',
// response form
'questionnaire…':'kwestionariusz…','matter…':'sprawa…','cycle…':'cykl…','Pick a questionnaire…':'Wybierz kwestionariusz…','No questions in this set.':'Brak pytań w tym zestawie.','Overall comment (≤280)':'Komentarz ogólny (≤280)','Score':'Wynik','yes':'tak','no':'nie',
// questionnaire builder (counsel review 2026-07-02)
'Edit questionnaire':'Edytuj kwestionariusz','Save changes':'Zapisz zmiany','Questions & weights':'Pytania i wagi','Tick the questions to include and give each a weight — weights must sum to exactly 1.0.':'Zaznacz pytania do uwzględnienia i nadaj każdemu wagę — suma wag musi wynosić dokładnie 1,0.','Weights sum:':'Suma wag:','Weight':'Waga','No questions yet — create questions first.':'Brak pytań — najpierw utwórz pytania.','Question weights must sum to 1.0':'Wagi pytań muszą sumować się do 1,0','Questionnaire saved':'Kwestionariusz zapisany','Questionnaire not found.':'Nie znaleziono kwestionariusza.',
// evaluations list + detail views (counsel review 2026-07-02)
'Evaluations':'Oceny','Loading evaluations…':'Wczytywanie ocen…','No evaluations yet.':'Brak ocen.','Failed to load evaluations':'Nie udało się wczytać ocen','Evaluation history':'Historia ocen','Evaluations for this matter':'Oceny tej sprawy','Average score':'Średni wynik','submitted evaluations':'wysłanych ocen','Avg score':'Średni wynik','Billing':'Rozliczenie','Firm not found.':'Nie znaleziono kancelarii.','Matter not found.':'Nie znaleziono sprawy.','Review cycle not found.':'Nie znaleziono cyklu przeglądu.','No history yet.':'Brak historii.','fixed fee':'ryczałt','firm':'kancelaria','matter':'sprawa','question':'pytanie','response':'odpowiedź',
// review-cycle wording (counsel review 2026-07-02: a bare "min evals 3" meant nothing)
'Firms with fewer than':'Kancelarie z mniej niż','submitted evaluations stay provisional.':'wysłanymi ocenami mają status wstępny.','How many submitted evaluations a firm needs to be ranked in this cycle.':'Ile wysłanych ocen potrzebuje kancelaria, aby znaleźć się w rankingu tego cyklu.',
// seeded data labels (EN in the DB, localized for display like any other exact-match string)
'Quality of advice':'Jakość porady','Responsiveness':'Responsywność','Scope compliance':'Zgodność z zakresem zlecenia','Business awareness':'Świadomość biznesowa','Budget adherence':'Trzymanie budżetu','Billing accuracy':'Prawidłowość rozliczeń',
'Exemplary':'Wzorowo','Good':'Dobrze','Average':'Przeciętnie','Below expectations':'Poniżej oczekiwań','Poor':'Źle',
// the answer <option> renders "value — label" as ONE text node, so the composed forms need keys too
'5 — Exemplary':'5 — Wzorowo','4 — Good':'4 — Dobrze','3 — Average':'3 — Przeciętnie','2 — Below expectations':'2 — Poniżej oczekiwań','1 — Poor':'1 — Źle',
'Counsel Evaluation':'Ocena kancelarii','Standard evaluation form completed after a matter closes.':'Standardowy formularz oceny kancelarii po zamknięciu sprawy.',
// cycle detail / snapshots / history
'Loading snapshots…':'Wczytywanie migawek…','No snapshots — close the cycle to generate rankings.':'Brak migawek — zamknij cykl, aby wygenerować rankingi.','No snapshots yet.':'Brak migawek.','Composite':'Wynik łączny','Completeness':'Kompletność','# evals':'Liczba ocen','Ranking':'Ranking','Rev':'Wer.','Reason':'Powód','When':'Kiedy',
// dictionaries
'Practice areas':'Obszary praktyki','Jurisdictions':'Jurysdykcje','Enums':'Typy wyliczeniowe','none':'brak',
// toasts / messages
'Cycle closed — rankings published':'Cykl zamknięty — rankingi opublikowane','Cycle created':'Cykl utworzony','Deactivated':'Dezaktywowano','Firm created':'Kancelaria utworzona','Matter created':'Sprawa utworzona','Pick a questionnaire':'Wybierz kwestionariusz','Question created':'Pytanie utworzone','Questionnaire created':'Kwestionariusz utworzony','Saved':'Zapisano','User created':'Użytkownik utworzony','Evaluation submitted':'Ocena wysłana','Evaluation saved':'Ocena zapisana','Failed':'Niepowodzenie','Sign in failed':'Logowanie nie powiodło się','Close failed':'Zamknięcie nie powiodło się','Search failed':'Wyszukiwanie nie powiodło się','No results.':'Brak wyników.','Type to search.':'Zacznij pisać, aby wyszukać.',
// status badges (de-underscored enum values)
'active':'aktywny','inactive':'nieaktywny','blacklisted':'na czarnej liście','open':'otwarty','in progress':'w toku','closed':'zamknięty','cancelled':'anulowany','draft':'wersja robocza','submitted':'przesłany','locked':'zablokowany','archived':'zarchiwizowany','provisional':'wstępny','at risk':'zagrożony','watch':'obserwacja','solid':'stabilny','top performer':'najlepszy','remove candidate':'kandydat do usunięcia',
// domain enum option/chip values (display only — the <option value> stays English)
'qualitative':'jakościowe','quantitative':'ilościowe','single_choice':'jednokrotny wybór','numeric':'liczbowy','text':'tekst','transactional':'transakcyjna','advisory':'doradcza','litigation':'sporna','regulatory':'regulacyjna','dispute':'spór','routine':'rutynowa','standard':'standardowa','complex':'złożona','bet_the_company':'kluczowa dla firmy','legal_ops':'legal ops','matter_owner':'właściciel sprawy','viewer':'obserwator',
// remaining answer types + value bands + underscored status values (Dictionaries chips)
'scale':'skala','boolean':'tak/nie','lt_50k':'< 50 tys.','50k_250k':'50–250 tys.','250k_1m':'250 tys. – 1 mln','1m_10m':'1 – 10 mln','gt_10m':'> 10 mln','in_progress':'w toku','at_risk':'zagrożony','top_performer':'najlepszy','remove_candidate':'kandydat do usunięcia',
// dictionaries enum group names + pager
'firm_status':'status kancelarii','matter_status':'status sprawy','matter_type':'typ sprawy','complexity_band':'poziom złożoności','value_band':'przedział wartości','user_role':'rola użytkownika','ranking_status':'status rankingu','questionnaire_status':'status kwestionariusza','response_status':'status odpowiedzi','answer_type':'typ odpowiedzi','question_category':'kategoria pytania','Page':'Strona',
// about page (nav group + item + prose)
'HELP':'POMOC','About':'O programie','What Counsel Scorecard is and how it helps.':'Czym jest Counsel Scorecard i jak pomaga.',
'What is Counsel Scorecard?':'Czym jest Counsel Scorecard?',
'Counsel Scorecard helps legal teams keep track of how well their outside law firms perform — and turn scattered opinions into a clear, fair score for every firm.':'Counsel Scorecard pomaga zespołom prawnym śledzić, jak dobrze radzą sobie współpracujące z nimi kancelarie zewnętrzne — i zamienia rozproszone opinie w przejrzysty, sprawiedliwy wynik dla każdej kancelarii.',
'How it works':'Jak to działa',
'Decide what matters — choose the questions you want to ask, such as responsiveness, quality of work, and value for money.':'Zdecyduj, co się liczy — wybierz pytania, które chcesz zadać, takie jak szybkość reakcji, jakość pracy i stosunek jakości do ceny.',
'Group those questions into a scorecard and give each one a weight.':'Pogrupuj te pytania w kartę oceny i nadaj każdemu z nich wagę.',
'After every piece of work, the person who ran it fills in a short evaluation.':'Po każdym zleceniu osoba, która je prowadziła, wypełnia krótką ocenę.',
'At the end of a review period, the answers are combined into a single score and a ranking for each firm.':'Na koniec okresu przeglądu odpowiedzi są łączone w jeden wynik i ranking dla każdej kancelarii.',
'Why teams use it':'Dlaczego zespoły z tego korzystają',
'Fair and consistent — every firm is judged against the same questions.':'Sprawiedliwie i spójnie — każda kancelaria jest oceniana według tych samych pytań.',
'Transparent — each score can be traced back to the answers behind it.':'Przejrzyście — każdy wynik można prześledzić aż do odpowiedzi, które go tworzą.',
'Private by design — it runs on your own systems, and your data never leaves them.':'Prywatnie z założenia — działa na Twoich własnych systemach, a Twoje dane nigdy ich nie opuszczają.',
'License':'Licencja',
'Counsel Scorecard is free and open-source software, released under the Apache License 2.0.':'Counsel Scorecard to bezpłatne oprogramowanie open source, udostępnione na licencji Apache License 2.0.',
'You are free to use, change, and share it — including for commercial use — at no cost. In short: keep the original copyright and license notice, and state any significant changes you make. The software is provided as-is, without warranty.':'Możesz go bezpłatnie używać, zmieniać i udostępniać — również komercyjnie. W skrócie: zachowaj oryginalną informację o prawach autorskich i licencji oraz zaznacz istotne zmiany, które wprowadzisz. Oprogramowanie jest dostarczane „tak jak jest”, bez gwarancji.',
'Read the full license':'Przeczytaj pełną treść licencji',
// form / UX revisions (2026-06-15)
'Contact person':'Osoba kontaktowa','Billing method':'Sposób rozliczenia','Responsible person':'Osoba odpowiedzialna','Question text':'Treść pytania',
'responsible = me':'odpowiedzialny = ja','hourly rate':'stawka godzinowa','other':'inny','Fixed fee amount':'Kwota','Hourly rate':'Stawka godzinowa','Billing notes':'Uwagi do rozliczenia',
}};
let LANG = (function(){ try{ const s=localStorage.getItem('cs_lang'); if(s==='en'||s==='pl') return s; }catch{}
const ls=(navigator.languages&&navigator.languages.length)?navigator.languages:[navigator.language||'en'];
for(const l of ls){ if(String(l).toLowerCase().indexOf('pl')===0) return 'pl'; } return 'en'; })();
const _txtEN=new WeakMap(), _attrEN=new WeakMap(), I18N_ATTRS=['placeholder','title','aria-label'];
function _tr(orig){ if(LANG==='en'||orig==null) return orig; const k=orig.trim(); if(!k) return orig; const v=I18N[LANG][k]; return v?orig.replace(k,v):orig; }
function _locText(n){ const p=n.parentElement; if(!p||p.closest('[data-no-i18n]')) return; let e=_txtEN.get(n); if(!e||e.shown!==n.nodeValue){ e={src:n.nodeValue}; _txtEN.set(n,e); } const out=_tr(e.src); e.shown=out; if(n.nodeValue!==out) n.nodeValue=out; }
function _locAttrs(el){ if(el.closest('[data-no-i18n]')) return; let st=_attrEN.get(el); for(const a of I18N_ATTRS){ if(!el.hasAttribute(a)) continue; if(!st){ st={}; _attrEN.set(el,st);} const cur=el.getAttribute(a); if(!(a in st)||cur!==st['='+a]) st[a]=cur; const out=_tr(st[a]); st['='+a]=out; if(cur!==out) el.setAttribute(a,out); } }
function localize(root){ if(!root) return; if(root.nodeType===3){ _locText(root); return; } if(root.nodeType!==1) return;
const w=document.createTreeWalker(root,NodeFilter.SHOW_TEXT,null); const ns=[]; let n; while(n=w.nextNode()) ns.push(n); for(const t of ns) _locText(t);
_locAttrs(root); root.querySelectorAll('['+I18N_ATTRS.join('],[')+']').forEach(_locAttrs); }
function updateLangButtons(){ const tip=LANG==='pl'?'Język: polski — kliknij, aby zmienić':'Language: English — click to switch'; ['btnLang','btnLangLogin'].forEach(id=>{ const el=$(id); if(el){ el.textContent=LANG.toUpperCase(); el.title=tip; el.setAttribute('aria-label',tip); } }); }
function setLang(l){ LANG=(l==='pl')?'pl':'en'; try{localStorage.setItem('cs_lang',LANG);}catch{} document.documentElement.lang=LANG; localize(document.body); updateLangButtons(); }
/* True when a field in `root` holds something the user typed or picked, which a re-render would lose. */
function _hasEditedField(root){ return !!root && [...root.querySelectorAll('input,textarea,select')].some(el=>{
if(el.type==='checkbox'||el.type==='radio') return el.checked!==el.defaultChecked;
if(el.tagName==='SELECT') return [...el.options].some(o=>o.selected!==o.defaultSelected);
return el.value!==el.defaultValue; }); }
/* The platform's hook: Atrium calls applyLang(lang) on this frame when its language changes. In place,
never a reload: the chrome, an open modal and the view are re-localized from their English source
(localize keeps it, and a node rewritten since becomes the new source), and the view is re-rendered
through router() only when it holds no typed or picked value. Same value = no-op, so our own button
writing cs_lang and Atrium's storage listener cannot loop. */
function applyLang(lang){ if((lang!=='en'&&lang!=='pl')||lang===LANG) return false; setLang(lang);
if(state.user&&!_hasEditedField($('content'))) router(); return true; }
window.applyLang=applyLang;
function _mkLangBtn(id,extra){ const b=document.createElement('button'); b.id=id; b.className='iconbtn'; b.setAttribute('data-no-i18n',''); b.style.cssText='width:auto;padding:0 10px;font-weight:600;font-size:12px;letter-spacing:.03em;'+(extra||''); b.onclick=()=>applyLang(LANG==='pl'?'en':'pl'); return b; }
(function initI18n(){
document.documentElement.lang=LANG;
const t=$('btnTheme'); if(t&&!$('btnLang')) t.parentNode.insertBefore(_mkLangBtn('btnLang'),t);
const tl=$('btnThemeLogin'); if(tl&&!$('btnLangLogin')) tl.parentNode.insertBefore(_mkLangBtn('btnLangLogin','position:fixed;top:16px;right:60px;background:var(--surface);border:1px solid var(--border-input);box-shadow:var(--shadow-card);color:var(--text-secondary);'),tl);
updateLangButtons();
localize(document.body);
new MutationObserver(ms=>{ for(const m of ms) for(const nd of m.addedNodes) localize(nd); }).observe(document.body,{childList:true,subtree:true});
})();
restore();
</script>
</body>
</html>