1353 lines
116 KiB
HTML
1353 lines
116 KiB
HTML
<!doctype html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||
<title>Kilometer Log</title>
|
||
<script>
|
||
// Dark mode by default; a choice made with the header toggle is remembered in this browser.
|
||
(function(){ var t="dark"; try{ t=localStorage.getItem("kmlog-theme")||"dark"; }catch(e){} document.documentElement.setAttribute("data-theme",t); })();
|
||
</script>
|
||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Barlow:wght@400;500;600&family=Barlow+Condensed:wght@600;700&display=swap">
|
||
<style>
|
||
html{color-scheme:light}body{margin:0}[hidden]{display:none!important}:root{padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)}
|
||
/* Layout: a driver's logbook — sticky header with two tabs (log / statistics), one working column, data set in tabular figures, plates drawn as Dutch number plates. */
|
||
:root{
|
||
--bg:#f3f5f8; --surface:#ffffff; --surface-2:#eef1f5; --fg:#17202d; --muted:#5a6577; --line:#dbe1e8;
|
||
--accent:#1c4ea6; --accent-fg:#ffffff; --danger:#b3261e; --danger-bg:#fbeceb;
|
||
--c-pnod:#1c4ea6; --c-hire:#c27410; --c-personal:#2c876a;
|
||
--plate:#f2c200; --plate-fg:#111111; --plate-eu:#1f3c96;
|
||
--shadow:0 1px 2px rgba(20,30,50,.06),0 8px 24px rgba(20,30,50,.08);
|
||
--f-display:"Barlow Condensed","Arial Narrow",Arial,sans-serif;
|
||
--f-body:"Barlow",system-ui,-apple-system,"Segoe UI",sans-serif;
|
||
}
|
||
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
|
||
--bg:#0f141b; --surface:#171e28; --surface-2:#1e2733; --fg:#e5eaf1; --muted:#97a3b5; --line:#2b3544;
|
||
--accent:#7aa2ff; --accent-fg:#0d1420; --danger:#ff8a80; --danger-bg:#3a1d1c;
|
||
--c-pnod:#7aa2ff; --c-hire:#eaa640; --c-personal:#55c39b;
|
||
--shadow:0 1px 2px rgba(0,0,0,.3),0 8px 24px rgba(0,0,0,.35); color-scheme:dark}}
|
||
:root[data-theme="dark"]{
|
||
--bg:#0f141b; --surface:#171e28; --surface-2:#1e2733; --fg:#e5eaf1; --muted:#97a3b5; --line:#2b3544;
|
||
--accent:#7aa2ff; --accent-fg:#0d1420; --danger:#ff8a80; --danger-bg:#3a1d1c;
|
||
--c-pnod:#7aa2ff; --c-hire:#eaa640; --c-personal:#55c39b;
|
||
--shadow:0 1px 2px rgba(0,0,0,.3),0 8px 24px rgba(0,0,0,.35); color-scheme:dark}
|
||
|
||
*{box-sizing:border-box}
|
||
body{background:var(--bg);color:var(--fg);font-family:var(--f-body);font-size:15px;line-height:1.45}
|
||
body::before{content:"";position:fixed;inset:0 0 auto;height:env(safe-area-inset-top,0px);z-index:10;background:var(--surface)}
|
||
.wrap{max-width:1080px;margin:0 auto;padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px))}
|
||
.num{font-variant-numeric:tabular-nums}
|
||
button,input,select,textarea{font:inherit;color:inherit}
|
||
:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
||
|
||
header{position:sticky;top:env(safe-area-inset-top,0px);z-index:5;background:var(--surface);border-bottom:1px solid var(--line)}
|
||
.bar{display:flex;align-items:center;gap:16px;flex-wrap:wrap;padding-block:12px}
|
||
.brand{display:flex;align-items:center;gap:10px;margin-right:auto}
|
||
.brand h1{font-family:var(--f-display);font-weight:700;font-size:1.6rem;letter-spacing:.01em;margin:0;line-height:1}
|
||
.odo{display:flex;gap:2px}
|
||
.odo span{font-family:var(--f-display);font-weight:600;font-size:1rem;background:var(--fg);color:var(--surface);width:1.05em;text-align:center;border-radius:2px;line-height:1.35}
|
||
.odo span:last-child{background:var(--danger);color:#fff}
|
||
.ccell{display:inline-flex;align-items:center;gap:8px}
|
||
.plate.cmark{min-height:22px}
|
||
.plate.us.cmark{padding:2px 6px;justify-content:center}
|
||
.platecell{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
|
||
.srctag{font-size:.68rem;font-weight:700;letter-spacing:.06em;color:var(--accent);border:1px solid currentColor;border-radius:4px;padding:0 4px;line-height:1.4}
|
||
.model{font-size:.85rem;color:var(--muted);white-space:nowrap}
|
||
.subtabs{display:flex;gap:4px;flex-wrap:wrap;border-bottom:1px solid var(--line)}
|
||
.subtabs button{border:0;background:none;padding:9px 14px;margin-bottom:-1px;border-bottom:2px solid transparent;color:var(--muted);font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
|
||
.subtabs button:hover{color:var(--fg)}
|
||
.subtabs button[aria-selected="true"]{color:var(--fg);border-bottom-color:var(--accent)}
|
||
.tabcount{font-size:.72rem;font-weight:600;background:var(--surface-2);color:var(--muted);border-radius:999px;padding:1px 7px}
|
||
.tabwarn{font-size:.72rem;font-weight:700;background:var(--c-hire);color:var(--surface);border-radius:999px;padding:1px 7px}
|
||
.apane{display:grid;gap:12px;min-width:0}
|
||
.apane>p.small{margin:0}
|
||
.sectionh{font-family:var(--f-display);font-weight:700;font-size:1.45rem;margin:0 0 2px}
|
||
.similar{display:inline-block;margin-left:8px;font-size:.78rem;font-weight:600;color:var(--c-hire);border:1px solid currentColor;border-radius:4px;padding:0 5px}
|
||
tr.editing td{background:var(--surface-2)!important}
|
||
select.lcsel{padding:4px 6px;font-size:.88rem;max-width:190px}
|
||
/* a location without a country: same orange as the badge on the Locations tab */
|
||
select.lcsel.unset{border-color:var(--c-hire);color:var(--c-hire);font-weight:600;background-color:color-mix(in srgb, var(--c-hire) 12%, var(--surface))}
|
||
select.lcsel.unset option{color:var(--fg);font-weight:400;background:var(--surface)}
|
||
.hapad{padding:14px 16px;display:grid;gap:12px;grid-template-columns:minmax(0,1fr)}
|
||
.hapad>*,.hasetup,.codewrap{min-width:0}
|
||
#adminHaCard{min-width:0;overflow:hidden}
|
||
.hafrom{display:grid;gap:4px;font-size:.82rem;font-weight:600;color:var(--muted);max-width:420px}
|
||
.hafrom .small{font-weight:400}
|
||
.hasetup summary{cursor:pointer;font-weight:600}
|
||
.hasetup[open] summary{margin-bottom:10px}
|
||
.hafields{margin-bottom:10px}
|
||
.codewrap{position:relative;margin-top:6px}
|
||
.hasteps{margin:0;padding-left:20px;display:grid;gap:14px}
|
||
.hasteps li{min-width:0}
|
||
.codewrap .btn{position:absolute;top:8px;right:8px}
|
||
pre.code{margin:0;padding:12px 14px;background:var(--surface-2);border:1px solid var(--line);border-radius:8px;overflow-x:auto;font:12.5px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:var(--fg);white-space:pre}
|
||
code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.9em;background:var(--surface-2);padding:0 4px;border-radius:4px}
|
||
.catform{padding:14px 16px;display:grid;gap:12px}
|
||
.catrows{display:grid;gap:8px}
|
||
.catrow{display:grid;grid-template-columns:auto minmax(0,320px) auto;justify-content:start;align-items:center;gap:10px}
|
||
.catrow .dot{width:10px;height:10px}
|
||
.renamebox{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
|
||
.renamebox input{flex:1 1 220px;min-width:0}
|
||
.renamehint{font-size:.85rem;color:var(--muted);margin-top:6px}
|
||
/* search field with its own clear button (the browser's built-in one is hidden so it looks the same everywhere) */
|
||
.searchbox{position:relative;flex:1 1 180px;min-width:0}
|
||
.searchbox .field{width:100%;padding-right:36px}
|
||
.searchbox input[type=search]::-webkit-search-cancel-button{-webkit-appearance:none;appearance:none;display:none}
|
||
.clearbtn{position:absolute;right:6px;top:50%;transform:translateY(-50%);width:26px;height:26px;border:0;border-radius:50%;background:var(--surface-2);color:var(--muted);display:flex;align-items:center;justify-content:center;cursor:pointer;padding:0}
|
||
.clearbtn:hover{color:var(--fg);background:var(--line)}
|
||
.clearbtn[hidden]{display:none!important}
|
||
.themebtn{border:1px solid var(--line);background:var(--surface);color:var(--muted);width:36px;height:36px;border-radius:8px;display:inline-flex;align-items:center;justify-content:center;cursor:pointer}
|
||
.themebtn:hover{color:var(--fg);border-color:var(--muted)}
|
||
.themebtn svg{width:18px;height:18px}
|
||
.tabs{display:flex;gap:4px;background:var(--surface-2);padding:3px;border-radius:8px}
|
||
.tabs button{border:0;background:transparent;padding:6px 14px;border-radius:6px;cursor:pointer;font-weight:600;color:var(--muted)}
|
||
.tabs button[aria-selected="true"]{background:var(--surface);color:var(--fg);box-shadow:0 1px 2px rgba(0,0,0,.12)}
|
||
|
||
main{padding-block:20px 48px;display:grid;gap:16px;grid-template-columns:minmax(0,1fr)}
|
||
main section>div{grid-template-columns:minmax(0,1fr)}
|
||
.card{min-width:0}
|
||
td.num{white-space:nowrap}
|
||
.btn{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--surface);padding:7px 12px;border-radius:7px;cursor:pointer;font-weight:500;white-space:nowrap}
|
||
.btn:hover{border-color:var(--muted)}
|
||
.btn.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-fg);font-weight:600}
|
||
.btn.danger{background:var(--danger);border-color:var(--danger);color:var(--surface)}
|
||
.btn.ghost{border-color:transparent;background:transparent;padding:5px 8px;color:var(--muted)}
|
||
.btn.ghost:hover{color:var(--fg);background:var(--surface-2)}
|
||
.btn:disabled{opacity:.5;cursor:default}
|
||
|
||
.toolbar{display:flex;gap:10px;flex-wrap:wrap;align-items:center}
|
||
.toolbar .grow{flex:1 1 180px;min-width:0}
|
||
.field{border:1px solid var(--line);background:var(--surface);border-radius:7px;padding:7px 10px;width:100%}
|
||
select.field{width:auto}
|
||
.chips{display:flex;gap:4px;flex-wrap:wrap}
|
||
.chip{border:1px solid var(--line);background:var(--surface);border-radius:999px;padding:4px 11px;cursor:pointer;font-size:.88rem;font-weight:500;display:inline-flex;align-items:center;gap:6px}
|
||
.chip[aria-pressed="true"]{border-color:var(--fg);background:var(--fg);color:var(--surface)}
|
||
.dot{width:8px;height:8px;border-radius:50%;display:inline-block}
|
||
|
||
.notice{display:flex;gap:12px;align-items:center;flex-wrap:wrap;background:var(--surface-2);border:1px dashed var(--line);border-radius:8px;padding:10px 14px;font-size:.92rem}
|
||
.notice p{margin:0;flex:1 1 240px}
|
||
|
||
.card{background:var(--surface);border:1px solid var(--line);border-radius:10px}
|
||
.sumline{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;padding:12px 16px;border-bottom:1px solid var(--line);font-size:.9rem;color:var(--muted)}
|
||
.sumline b{color:var(--fg);font-weight:600}
|
||
.tablewrap{overflow-x:auto}
|
||
table{border-collapse:collapse;width:100%;min-width:720px}
|
||
th,td{text-align:left;padding:9px 12px;border-bottom:1px solid var(--line);vertical-align:middle}
|
||
th{font-size:.74rem;text-transform:uppercase;letter-spacing:.07em;color:var(--muted);font-weight:600;background:var(--surface)}
|
||
th.sortable{cursor:pointer;user-select:none}
|
||
th.sortable:hover{color:var(--fg)}
|
||
tbody tr:last-child td{border-bottom:0}
|
||
tbody tr:hover td{background:var(--surface-2)}
|
||
td.r,th.r{text-align:right}
|
||
td.km{font-weight:600}
|
||
td.actions{text-align:right;white-space:nowrap;width:1%}
|
||
tr.confirm td{background:var(--danger-bg)!important}
|
||
.ex{font-size:.7rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);border:1px solid var(--line);border-radius:4px;padding:0 4px;margin-left:6px}
|
||
|
||
.plate{display:inline-flex;align-items:stretch;border-radius:3px;overflow:hidden;border:1px solid rgba(0,0,0,.55);background:#fff;color:#111;font-family:var(--f-display);font-weight:700;font-size:.95rem;letter-spacing:.05em;line-height:1;white-space:nowrap}
|
||
.plate i{flex:none;width:19px;background:var(--plate-eu);color:#fff;font-style:normal;display:flex;flex-direction:column;align-items:center;justify-content:space-between;padding:2px 0 2px;letter-spacing:0}
|
||
.plate i svg{display:block;width:11px;height:11px}
|
||
.plate i svg.flag{width:13px;height:9px;margin-top:1px;outline:.5px solid rgba(255,255,255,.55)}
|
||
.plate i small{font-family:var(--f-body);font-weight:700;font-size:.5rem;line-height:1}
|
||
.plate i small.l3{font-size:.4rem;letter-spacing:-.02em}
|
||
.plate i.ukside{background:#f2c200;color:#111;border-right:1px solid rgba(0,0,0,.18)}
|
||
.plate i.chside{background:#fff;justify-content:center;padding:0}
|
||
.plate i.chside svg.shield{width:11px;height:13px}
|
||
.plate i.ukside svg.flag{width:14px;height:7px;outline:.5px solid rgba(0,0,0,.25)}
|
||
.plate i.unk{background:#8a93a0;justify-content:flex-end}
|
||
.plate span{padding:4px 7px 3px}
|
||
.plate.us{flex-direction:column;align-items:center;justify-content:center;border-radius:5px;padding:2px 9px 3px;gap:1px}
|
||
.plate.us em{font-style:normal;font-family:var(--f-body);font-size:.5rem;font-weight:700;letter-spacing:.09em;text-transform:uppercase;line-height:1.05}
|
||
.plate.us span{padding:0;line-height:1}
|
||
.plate b{font-family:var(--f-body);font-size:.55rem;font-weight:600;letter-spacing:.04em;background:#e3e6eb;color:#333;display:flex;align-items:center;padding:0 4px;border-left:1px solid rgba(0,0,0,.25)}
|
||
.filters{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
|
||
.filters select.field{max-width:100%}
|
||
.form .pair{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:8px}
|
||
.unitrow{display:flex;gap:6px;align-items:stretch}
|
||
.unitrow input{flex:1 1 auto;min-width:0}
|
||
.unit{display:flex;border:1px solid var(--line);border-radius:7px;overflow:hidden;flex:none}
|
||
.unit button{border:0;background:var(--surface);color:var(--muted);padding:0 10px;cursor:pointer;font-weight:600}
|
||
.unit button[aria-pressed="true"]{background:var(--fg);color:var(--surface)}
|
||
.conv{font-weight:400;color:var(--muted);font-size:.82rem;min-height:1.2em}
|
||
.check[hidden]{display:none!important}
|
||
.check{display:flex!important;flex-direction:row!important;align-items:center;gap:8px;font-weight:500!important;color:var(--fg)!important}
|
||
.pill{display:inline-flex;align-items:center;gap:6px;font-size:.85rem;font-weight:500}
|
||
|
||
.empty{padding:40px 20px;text-align:center;color:var(--muted)}
|
||
.empty h2{font-family:var(--f-display);color:var(--fg);font-size:1.4rem;margin:0 0 6px}
|
||
.empty .toolbar{justify-content:center;margin-top:14px}
|
||
|
||
/* stats */
|
||
.tiles{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
|
||
.tile{background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:14px 16px}
|
||
.tile .lab{font-size:.74rem;text-transform:uppercase;letter-spacing:.07em;color:var(--muted);font-weight:600}
|
||
.tile .val{font-family:var(--f-display);font-weight:700;font-size:2.1rem;line-height:1.1;margin-top:4px}
|
||
.tile .val small{font-size:1rem;color:var(--muted);font-weight:600;margin-left:3px}
|
||
.tile .sub{font-size:.85rem;color:var(--muted)}
|
||
@media (max-width:760px){.tiles{grid-template-columns:repeat(2,minmax(0,1fr))}}
|
||
.panel{padding:16px}
|
||
.panel h2{font-family:var(--f-display);font-weight:700;font-size:1.25rem;margin:0 0 2px;text-wrap:balance}
|
||
.panel .hint{color:var(--muted);font-size:.88rem;margin:0 0 12px}
|
||
.grid2{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:16px}
|
||
@media (max-width:760px){.grid2{grid-template-columns:minmax(0,1fr)}}
|
||
.split{display:flex;height:14px;border-radius:4px;overflow:hidden;background:var(--surface-2);margin:8px 0 12px}
|
||
.legend{display:flex;gap:16px;flex-wrap:wrap;font-size:.9rem}
|
||
.legend div{display:flex;gap:6px;align-items:baseline}
|
||
.legend b{font-weight:600}
|
||
.chartrow{display:flex;align-items:flex-start;min-width:0}
|
||
.chartrow .yaxis{flex:none;width:52px;height:260px}
|
||
.chartrow #monthScroll{flex:1 1 auto;min-width:0}
|
||
.chartrow #monthScroll svg{width:auto;height:260px}
|
||
.rank thead th{font-size:.7rem;text-transform:uppercase;letter-spacing:.07em;color:var(--muted);font-weight:600;text-align:left;padding:0 4px 6px;border-bottom:1px solid var(--line);background:none}
|
||
.rank thead th.r{text-align:right}
|
||
.rank thead th.sortable:hover{color:var(--fg)}
|
||
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
|
||
.rankmore{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-top:8px;padding-top:8px;border-top:1px solid var(--line);font-size:.86rem;color:var(--muted)}
|
||
.rank{width:100%;min-width:0;border-collapse:collapse}
|
||
.rank td{padding:7px 4px;border-bottom:1px solid var(--line)}
|
||
.rank tr:last-child td{border-bottom:0}
|
||
.rank .barcell{width:38%}
|
||
.rank .track{height:8px;background:var(--surface-2);border-radius:4px;overflow:hidden;display:flex}
|
||
.chart svg{width:100%;height:auto;display:block}
|
||
.chart .axis{fill:var(--muted);font-size:11px;font-family:var(--f-body)}
|
||
.chart .grid{stroke:var(--line);stroke-width:1}
|
||
.chart .tot{fill:var(--fg);font-size:10.5px;font-weight:600;font-family:var(--f-body)}
|
||
|
||
/* modal */
|
||
.overlay{position:fixed;inset:0;z-index:20;background:rgba(10,15,25,.45);display:flex;align-items:flex-start;justify-content:center;overflow-y:auto;padding:max(24px,env(safe-area-inset-top,0px)) max(16px,env(safe-area-inset-right,0px)) 24px max(16px,env(safe-area-inset-left,0px))}
|
||
.modal{background:var(--surface);border-radius:12px;box-shadow:var(--shadow);width:100%;max-width:560px;padding:20px;display:grid;gap:14px;margin-top:4vh}
|
||
.modal h2{font-family:var(--f-display);font-size:1.45rem;margin:0}
|
||
.form{display:grid;grid-template-columns:1fr 1fr;gap:12px;align-items:start}
|
||
.form label{display:grid;gap:4px;font-size:.82rem;font-weight:600;color:var(--muted)}
|
||
.form .full{grid-column:1/-1}
|
||
@media (max-width:480px){.form{grid-template-columns:1fr}}
|
||
.seg{display:flex;gap:6px;flex-wrap:wrap}
|
||
.seg label{display:flex;flex-direction:row;align-items:center;gap:6px;border:1px solid var(--line);border-radius:7px;padding:7px 12px;cursor:pointer;color:var(--fg);font-weight:500;font-size:.92rem}
|
||
.seg input{accent-color:var(--accent)}
|
||
.err{color:var(--danger);font-size:.88rem;min-height:1.2em;margin:0}
|
||
.actionsrow{display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap}
|
||
textarea.field{min-height:150px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.82rem;resize:vertical}
|
||
.small{font-size:.86rem;color:var(--muted);margin:0}
|
||
.preview{font-size:.88rem;background:var(--surface-2);border-radius:8px;padding:10px 12px;display:grid;gap:4px}
|
||
.dupebox{display:grid;gap:4px;padding-top:6px;border-top:1px solid var(--line)}
|
||
.dupebox .check{font-weight:500;color:var(--fg);margin-top:2px}
|
||
.preview ul{margin:4px 0 0;padding-left:18px;color:var(--muted)}
|
||
.toast{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(20px + env(safe-area-inset-bottom,0px));background:var(--fg);color:var(--surface);padding:9px 16px;border-radius:8px;font-weight:500;z-index:30;box-shadow:var(--shadow)}
|
||
@media (prefers-reduced-motion:no-preference){.toast{animation:up .2s ease-out}@keyframes up{from{opacity:0;transform:translate(-50%,8px)}}}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<header>
|
||
<div class="wrap bar">
|
||
<div class="brand">
|
||
<div class="odo" aria-hidden="true"><span>0</span><span>4</span><span>2</span><span>7</span><span>1</span></div>
|
||
<h1>Kilometer Log</h1>
|
||
</div>
|
||
<div class="tabs" role="tablist">
|
||
<button role="tab" id="tab-trips" aria-selected="true" data-view="trips">Trips</button>
|
||
<button role="tab" id="tab-stats" aria-selected="false" data-view="stats">Statistics</button>
|
||
<button role="tab" id="tab-admin" aria-selected="false" data-view="admin">Admin</button>
|
||
</div>
|
||
<button class="themebtn" id="themeBtn" type="button"></button>
|
||
</div>
|
||
</header>
|
||
|
||
<main class="wrap">
|
||
<div id="banner" hidden></div>
|
||
|
||
<section id="view-trips" aria-labelledby="tab-trips">
|
||
<div style="display:grid;gap:14px">
|
||
<div class="toolbar">
|
||
<div class="searchbox grow"><input id="q" class="field" type="search" placeholder="Search plate, make/model, country or location" aria-label="Search trips"><button type="button" class="clearbtn" data-clear="q" aria-label="Clear search" title="Clear search" hidden><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button></div>
|
||
</div>
|
||
<div class="filters" id="tripFilters"></div>
|
||
<div class="toolbar" id="writeTools">
|
||
<button class="btn primary" id="addBtn">+ Add trip</button>
|
||
<button class="btn" id="importBtn">Import from Excel</button>
|
||
<button class="btn" id="exportBtn">Export CSV</button>
|
||
</div>
|
||
<div class="card" id="tripsCard"></div>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="view-stats" aria-labelledby="tab-stats" hidden>
|
||
<div style="display:grid;gap:16px">
|
||
<div class="filters" id="statsFilters"></div>
|
||
<div id="statsBody" style="display:grid;gap:16px"></div>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="view-admin" aria-labelledby="tab-admin" hidden>
|
||
<div style="display:grid;gap:14px">
|
||
<div class="subtabs" role="tablist" aria-label="Admin sections">
|
||
<button role="tab" type="button" data-atab="locations" id="atab-locations">Locations</button>
|
||
<button role="tab" type="button" data-atab="vehicles" id="atab-vehicles">Vehicles</button>
|
||
<button role="tab" type="button" data-atab="categories" id="atab-categories">Categories</button>
|
||
<button role="tab" type="button" data-atab="ha" id="atab-ha">Home Assistant</button>
|
||
</div>
|
||
|
||
<div class="apane" id="apane-locations" role="tabpanel" aria-labelledby="atab-locations">
|
||
<p class="small">Rename a location to change it on every trip that uses it. Renaming to a name that already exists merges the two.</p>
|
||
<div class="toolbar"><div class="searchbox grow"><input id="adminQ" class="field" type="search" placeholder="Find a location" aria-label="Find a location"><button type="button" class="clearbtn" data-clear="adminQ" aria-label="Clear search" title="Clear search" hidden><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button></div></div>
|
||
<div class="card" id="adminCard"></div>
|
||
</div>
|
||
|
||
<div class="apane" id="apane-vehicles" role="tabpanel" aria-labelledby="atab-vehicles" hidden>
|
||
<p class="small">Set the make and model once per license plate; it is applied to all trips with that plate.</p>
|
||
<div class="toolbar"><div class="searchbox grow"><input id="vehQ" class="field" type="search" placeholder="Find a plate or make/model" aria-label="Find a vehicle"><button type="button" class="clearbtn" data-clear="vehQ" aria-label="Clear search" title="Clear search" hidden><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button></div></div>
|
||
<div class="card" id="adminVehCard"></div>
|
||
</div>
|
||
|
||
<div class="apane" id="apane-categories" role="tabpanel" aria-labelledby="atab-categories" hidden>
|
||
<p class="small">The names shown for the three categories. Renaming only changes the label; trips keep their category.</p>
|
||
<form class="card catform" id="catForm" novalidate></form>
|
||
</div>
|
||
|
||
<div class="apane" id="apane-ha" role="tabpanel" aria-labelledby="atab-ha" hidden>
|
||
<p class="small">Each time your car's odometer changes, Home Assistant sends the new reading here. The distance since the previous reading is added as a trip, at the place where the car is.</p>
|
||
<div class="card" id="adminHaCard"></div>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
</main>
|
||
|
||
<div id="modalRoot"></div>
|
||
<div id="toastRoot"></div>
|
||
|
||
<script>
|
||
(function(){
|
||
/* Categories. The key is what is stored on each trip and never changes;
|
||
the label is free text, set on the Admin page (shared through the server). */
|
||
const CATS = [
|
||
{key:"PNOD", def:"Business", label:"Business", color:"var(--c-pnod)"},
|
||
{key:"hire", def:"Rental", label:"Rental", color:"var(--c-hire)"},
|
||
{key:"personal", def:"Personal", label:"Personal", color:"var(--c-personal)"}
|
||
];
|
||
function applyCatLabels(labels){ CATS.forEach(c=>{ const v=String((labels||{})[c.key]??"").trim(); c.label=v||c.def; }); }
|
||
const CAT = Object.fromEntries(CATS.map(c=>[c.key,c]));
|
||
const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
|
||
|
||
let trips = [];
|
||
let loaded = false;
|
||
let canWrite = true;
|
||
let store = null;
|
||
let locCountry = new Map(); // location name -> country code (set once per location)
|
||
const lcOf=name=>locCountry.get(name||"")||"";
|
||
const ui = {view:"trips", q:"", admin:{q:"",sort:"name",dir:"asc",editing:null}, adminTab:(()=>{ try{ return localStorage.getItem("kmlog-admintab")||"locations"; }catch(e){ return "locations"; } })(), adminV:{editing:null,deleting:null,q:"",all:false}, haOpen:null, expanded:new Set(), rankSort:{}, tsort:{}, sort:"start", dir:"desc", confirmId:null,
|
||
t:{year:"all", cat:"all", veh:"all", loc:"all", car:"all"},
|
||
s:{year:null, cat:"all", veh:"all", loc:"all", car:"all"}};
|
||
|
||
const $ = s => document.querySelector(s);
|
||
const esc = s => String(s ?? "").replace(/[&<>"']/g, c => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
|
||
const fmtKm = n => (Math.round(n*10)/10).toLocaleString("nl-NL",{maximumFractionDigits:1});
|
||
function fmtDate(iso){ if(!iso) return ""; const [y,m,d]=iso.split("-").map(Number); return `${d} ${MONTHS[m-1]} ${y}`; }
|
||
function days(t){ const a=Date.parse(t.start), b=Date.parse(t.end||t.start); return isNaN(a)||isNaN(b)?1:Math.max(1,Math.round((b-a)/864e5)+1); }
|
||
/* Plate looks per country: background, text colour, the code in the blue EU band, or a side tag for non-EU style plates. */
|
||
const PLATE_STYLE={
|
||
NL:{bg:"#f2c200",fg:"#111"}, L:{bg:"#f2c200",fg:"#111"}, UK:{bg:"#f2c200",fg:"#111"},
|
||
B:{bg:"#fff",fg:"#a3122a"}, CH:{bg:"#fff",fg:"#111"}, N:{bg:"#fff",fg:"#111"}
|
||
};
|
||
const COUNTRIES=[["NL","Netherlands"],["B","Belgium"],["D","Germany"],["F","France"],["L","Luxembourg"],["UK","United Kingdom"],["IRL","Ireland"],["N","Norway"],["S","Sweden"],["DK","Denmark"],["FIN","Finland"],["SLO","Slovenia"],["HR","Croatia"],["A","Austria"],["CH","Switzerland"],["I","Italy"],["E","Spain"],["P","Portugal"],["PL","Poland"],["CZ","Czechia"],["SK","Slovakia"],["H","Hungary"],["RO","Romania"],["BG","Bulgaria"],["GR","Greece"],["MD","Moldova"],["UA","Ukraine"],["IS","Iceland"],["AL","Albania"],["SRB","Serbia"],["BIH","Bosnia and Herzegovina"],["MNE","Montenegro"],["NMK","North Macedonia"],["TR","Turkey"],["USA","United States"],["CDN","Canada"]];
|
||
const COUNTRY_ALIAS={NLD:"NL",NEDERLAND:"NL",NETHERLANDS:"NL",HOLLAND:"NL",BE:"B",BEL:"B",BELGIE:"B","BELGIË":"B",BELGIUM:"B",DE:"D",DEU:"D",GER:"D",GERMANY:"D",DUITSLAND:"D",FR:"F",FRA:"F",FRANCE:"F",FRANKRIJK:"F",LU:"L",LUX:"L",GB:"UK",GBR:"UK","UNITED KINGDOM":"UK",ENGLAND:"UK",ENGELAND:"UK","VERENIGD KONINKRIJK":"UK",IE:"IRL",IRELAND:"IRL",NO:"N",NOR:"N",NORWAY:"N",NOORWEGEN:"N",SE:"S",SWE:"S",SWEDEN:"S",ZWEDEN:"S",DEN:"DK",DENMARK:"DK",DENEMARKEN:"DK",FI:"FIN",SI:"SLO",SVN:"SLO",SLOVENIA:"SLO","SLOVENIË":"SLO",SLOVENIE:"SLO",AT:"A",AUT:"A",AUSTRIA:"A",OOSTENRIJK:"A",IT:"I",ITA:"I",ITALY:"I",ES:"E",ESP:"E",SPAIN:"E",SPANJE:"E",PT:"P",PRT:"P",MDA:"MD",MOLDOVA:"MD",UKR:"UA",UKRAINE:"UA",OEKRAINE:"UA",ISL:"IS",ICELAND:"IS",IJSLAND:"IS",ALB:"AL",ALBANIA:"AL","ALBANIË":"AL",ALBANIE:"AL",RS:"SRB",SERBIA:"SRB","SERVIË":"SRB",SERVIE:"SRB",BA:"BIH",BOSNIA:"BIH","BOSNIË":"BIH",ME:"MNE",MONTENEGRO:"MNE",MK:"NMK","NORTH MACEDONIA":"NMK","NOORD-MACEDONIË":"NMK",TUR:"TR",TURKEY:"TR",TURKIJE:"TR","TÜRKIYE":"TR",GREECE:"GR","GRIEKENLAND":"GR",EL:"GR",HU:"H",HUNGARY:"H",HONGARIJE:"H",RO:"RO",ROMANIA:"RO","ROEMENIË":"RO",BG:"BG",BULGARIA:"BG","BULGARIJE":"BG",SVK:"SK",SLOVAKIA:"SK",US:"USA",AMERICA:"USA",AMERIKA:"USA","UNITED STATES":"USA",CA:"CDN",CAN:"CDN",CANADA:"CDN"};
|
||
function normCountry(s){ s=String(s||"").trim().toUpperCase(); if(!s) return ""; s=COUNTRY_ALIAS[s]||s; return /^[A-Z]{1,3}$/.test(s)?s:null; }
|
||
function countryName(c){ const f=COUNTRIES.find(x=>x[0]===c); return f?f[1]:(c||"Unknown country"); }
|
||
/* US states: name, plate background, number colour, colour of the state name.
|
||
Simplified colour schemes in the spirit of each state's standard plate; no artwork. */
|
||
const US_STATES={AL:["Alabama"],AK:["Alaska","#f4d03f","#1c3f8f","#1c3f8f"],AZ:["Arizona","#fff","#7a2a17","#b35c1e"],AR:["Arkansas","#fff","#7a1424","#7a1424"],
|
||
CA:["California","#fff","#1d2f6b","#c8102e"],CO:["Colorado","#2e6b3c","#fff","#fff"],CT:["Connecticut","#e9f1f8","#1d2f6b","#1d2f6b"],DE:["Delaware","#1d3f7a","#f1c232","#f1c232"],
|
||
DC:["District of Columbia","#fff","#b31b1b","#b31b1b"],FL:["Florida","#fff","#0d6b3b","#e5701f"],GA:["Georgia","#fff","#111","#b5560b"],HI:["Hawaii","#fff","#111","#0f5ea8"],
|
||
ID:["Idaho","#fff","#7a1f1f","#1d3f7a"],IL:["Illinois","#fff","#7a1f2a","#1d3f7a"],IN:["Indiana","#fff","#1d2f6b","#1d2f6b"],IA:["Iowa","#fff","#1d2f6b","#1d2f6b"],
|
||
KS:["Kansas","#fff","#1d2f6b","#1d2f6b"],KY:["Kentucky","#fff","#1d2f6b","#1d2f6b"],LA:["Louisiana","#fff","#1d2f6b","#b31b1b"],ME:["Maine","#fff","#111","#1d3f7a"],
|
||
MD:["Maryland","#fff","#111","#b31b1b"],MA:["Massachusetts","#fff","#8b1a1a","#1d3f7a"],MI:["Michigan","#fff","#1d2f6b","#1d2f6b"],MN:["Minnesota","#fff","#1d2f6b","#1d2f6b"],
|
||
MS:["Mississippi","#fff","#1d2f6b","#1d2f6b"],MO:["Missouri","#fff","#1d2f6b","#1d2f6b"],MT:["Montana","#fff","#111","#1d3f7a"],NE:["Nebraska","#fff","#1d2f6b","#1d2f6b"],
|
||
NV:["Nevada","#d6e6f4","#0d2d5a","#0d2d5a"],NH:["New Hampshire","#fff","#1d4f2a","#1d4f2a"],NJ:["New Jersey","#f2dd8e","#111","#111"],NM:["New Mexico","#f6d34a","#b31b1b","#b31b1b"],
|
||
NY:["New York","#f6c445","#13306b","#13306b"],NC:["North Carolina","#fff","#1d2f6b","#b31b1b"],ND:["North Dakota","#fff","#1d2f6b","#1d2f6b"],OH:["Ohio","#fff","#1d2f6b","#b31b1b"],
|
||
OK:["Oklahoma","#fff","#1d2f6b","#1d2f6b"],OR:["Oregon","#fff","#1d3f7a","#2f6b3a"],PA:["Pennsylvania","#fff","#13306b","#e0a400"],RI:["Rhode Island","#fff","#1d2f6b","#1d2f6b"],
|
||
SC:["South Carolina","#fff","#1d2f6b","#1d2f6b"],SD:["South Dakota","#fff","#1d2f6b","#1d2f6b"],TN:["Tennessee","#fff","#1d2f6b","#2f6b3a"],TX:["Texas","#fff","#111","#111"],
|
||
UT:["Utah","#fff","#1d2f6b","#b5560b"],VT:["Vermont","#2f6b3a","#fff","#fff"],VA:["Virginia","#fff","#1d2f6b","#1d2f6b"],WA:["Washington","#fff","#1d3f7a","#1d3f7a"],
|
||
WV:["West Virginia","#fff","#1d2f6b","#e0a400"],WI:["Wisconsin","#fff","#1d2f6b","#1d2f6b"],WY:["Wyoming","#fff","#111","#8b1a1a"]};
|
||
const STATE_BY_NAME=Object.fromEntries(Object.entries(US_STATES).map(([k,v])=>[v[0].toUpperCase(),k]));
|
||
function normState(s){ s=String(s||"").trim().toUpperCase().replace(/\.$/,""); if(!s) return ""; if(US_STATES[s]) return s; return STATE_BY_NAME[s]||null; }
|
||
const EU_STARS='<svg viewBox="0 0 24 24" aria-hidden="true"><g fill="#ffcc00"><polygon points="12.00,1.90 12.50,3.31 14.00,3.35 12.81,4.26 13.23,5.70 12.00,4.85 10.77,5.70 11.19,4.26 10.00,3.35 11.50,3.31"/><polygon points="16.00,2.97 16.50,4.38 18.00,4.42 16.81,5.33 17.23,6.77 16.00,5.92 14.77,6.77 15.19,5.33 14.00,4.42 15.50,4.38"/><polygon points="18.93,5.90 19.43,7.31 20.93,7.35 19.74,8.26 20.16,9.70 18.93,8.85 17.69,9.70 18.12,8.26 16.93,7.35 18.43,7.31"/><polygon points="20.00,9.90 20.50,11.31 22.00,11.35 20.81,12.26 21.23,13.70 20.00,12.85 18.77,13.70 19.19,12.26 18.00,11.35 19.50,11.31"/><polygon points="18.93,13.90 19.43,15.31 20.93,15.35 19.74,16.26 20.16,17.70 18.93,16.85 17.69,17.70 18.12,16.26 16.93,15.35 18.43,15.31"/><polygon points="16.00,16.83 16.50,18.24 18.00,18.28 16.81,19.19 17.23,20.63 16.00,19.78 14.77,20.63 15.19,19.19 14.00,18.28 15.50,18.24"/><polygon points="12.00,17.90 12.50,19.31 14.00,19.35 12.81,20.26 13.23,21.70 12.00,20.85 10.77,21.70 11.19,20.26 10.00,19.35 11.50,19.31"/><polygon points="8.00,16.83 8.50,18.24 10.00,18.28 8.81,19.19 9.23,20.63 8.00,19.78 6.77,20.63 7.19,19.19 6.00,18.28 7.50,18.24"/><polygon points="5.07,13.90 5.57,15.31 7.07,15.35 5.88,16.26 6.31,17.70 5.07,16.85 3.84,17.70 4.26,16.26 3.07,15.35 4.57,15.31"/><polygon points="4.00,9.90 4.50,11.31 6.00,11.35 4.81,12.26 5.23,13.70 4.00,12.85 2.77,13.70 3.19,12.26 2.00,11.35 3.50,11.31"/><polygon points="5.07,5.90 5.57,7.31 7.07,7.35 5.88,8.26 6.31,9.70 5.07,8.85 3.84,9.70 4.26,8.26 3.07,7.35 4.57,7.31"/><polygon points="8.00,2.97 8.50,4.38 10.00,4.42 8.81,5.33 9.23,6.77 8.00,5.92 6.77,6.77 7.19,5.33 6.00,4.42 7.50,4.38"/></g></svg>';
|
||
const NO_FLAG='<svg class="flag" viewBox="0 0 22 16" aria-hidden="true"><rect width="22" height="16" fill="#BA0C2F"/><path d="M8 0V16M0 8H22" stroke="#fff" stroke-width="4"/><path d="M8 0V16M0 8H22" stroke="#00205B" stroke-width="2"/></svg>';
|
||
/* National flags for non-EU plates that carry one in the band (tiny, simplified) */
|
||
const FLAG_SVG={
|
||
N: NO_FLAG,
|
||
MD:'<svg class="flag" viewBox="0 0 24 16" aria-hidden="true"><rect width="8" height="16" fill="#0046AE"/><rect x="8" width="8" height="16" fill="#FFD200"/><rect x="16" width="8" height="16" fill="#CC092F"/><rect x="10.5" y="5" width="3" height="6" rx="1" fill="#9a6a2f"/></svg>',
|
||
UA:'<svg class="flag" viewBox="0 0 24 16" aria-hidden="true"><rect width="24" height="8" fill="#0057B7"/><rect y="8" width="24" height="8" fill="#FFD700"/></svg>',
|
||
IS:'<svg class="flag" viewBox="0 0 25 18" aria-hidden="true"><rect width="25" height="18" fill="#02529C"/><path d="M9 0V18M0 9H25" stroke="#fff" stroke-width="4"/><path d="M9 0V18M0 9H25" stroke="#DC1E35" stroke-width="2"/></svg>',
|
||
AL:'<svg class="flag" viewBox="0 0 24 17" aria-hidden="true"><rect width="24" height="17" fill="#E41E20"/><path fill="#000" d="M12 3.2l1.1 1.6 2.3-1.1-.7 2 2.2-.4-1.2 1.8 1.8.6-2 .9.9 1.6-2-.2-.5 2.3L12 11l-1.9 1.3-.5-2.3-2 .2.9-1.6-2-.9 1.8-.6-1.2-1.8 2.2.4-.7-2 2.3 1.1z"/><rect x="11.3" y="11" width="1.4" height="3" fill="#000"/></svg>'
|
||
};
|
||
const CH_SHIELD='<svg class="shield" viewBox="0 0 20 24" aria-hidden="true"><path d="M1.5 1.5H18.5V11C18.5 17 14 21 10 22.5C6 21 1.5 17 1.5 11Z" fill="#DA291C" stroke="#fff" stroke-width="1"/><path d="M8.3 6H11.7V9.3H15V12.7H11.7V16H8.3V12.7H5V9.3H8.3Z" fill="#fff"/></svg>';
|
||
const UNION_FLAG='<svg class="flag" viewBox="0 0 60 30" aria-hidden="true"><rect width="60" height="30" fill="#012169"/><path d="M0 0L60 30M60 0L0 30" stroke="#fff" stroke-width="6"/><path d="M0 0L60 30M60 0L0 30" stroke="#C8102E" stroke-width="2.4"/><path d="M30 0V30M0 15H60" stroke="#fff" stroke-width="10"/><path d="M30 0V30M0 15H60" stroke="#C8102E" stroke-width="6"/></svg>';
|
||
/* EU member states (international plate codes): their plates carry the ring of stars */
|
||
const EU_CODES=new Set(["NL","B","D","F","L","IRL","S","DK","FIN","SLO","HR","A","I","E","P","PL","CZ","SK","H","RO","BG","GR","CY","M","EST","LV","LT"]);
|
||
function plateHtml(p,c,r){
|
||
const num=`<span>${esc(p||"—")}</span>`;
|
||
if(c==="USA"){
|
||
const st=US_STATES[r]; const [name,bg,fg,ac]=st?[st[0],st[1]||"#fff",st[2]||"#1d2f6b",st[3]||st[2]||"#1d2f6b"]:["USA","#fff","#1d2f6b","#1d2f6b"];
|
||
return `<span class="plate us" style="background:${bg};color:${fg}" title="${esc(p)} · ${esc(st?name+", USA":"United States")}"><em style="color:${ac}">${esc(name)}</em>${num}</span>`;
|
||
}
|
||
const st=PLATE_STYLE[c]||{bg:"#fff",fg:"#111"};
|
||
const code=`<small class="${c&&c.length>2?"l3":""}">${esc(c)}</small>`;
|
||
const band = !c ? `<i class="unk"><small>?</small></i>`
|
||
: c==="UK" ? `<i class="ukside">${UNION_FLAG}<small>UK</small></i>` // UK: yellow box with Union flag
|
||
: c==="CH" ? `<i class="chside">${CH_SHIELD}</i>` // Switzerland: shield on the white plate
|
||
: st.tag ? ""
|
||
: FLAG_SVG[c] ? `<i>${FLAG_SVG[c]}${code}</i>` // Norway, Moldova, Ukraine, Iceland, Albania: own flag/emblem
|
||
: EU_CODES.has(c) ? `<i>${EU_STARS}${code}</i>` // EU: ring of stars
|
||
: `<i style="justify-content:flex-end">${code}</i>`; // other countries: code only
|
||
return `<span class="plate" style="background:${st.bg};color:${st.fg}" title="${esc(p)} · ${esc(countryName(c))}">${band}${num}${c&&st.tag?`<b>${esc(c)}</b>`:""}</span>`;
|
||
}
|
||
/* Small country marker for the statistics: the plate's band (stars, flag, shield) without the number */
|
||
function countryLabel(c){
|
||
let mark;
|
||
if(c==="USA") mark=`<span class="plate us cmark" style="background:#fff;color:#1d2f6b"><em style="color:#1d2f6b">USA</em></span>`;
|
||
else { const h=plateHtml("",c,""); mark=h.replace('<span>—</span>','').replace('class="plate"','class="plate cmark"'); }
|
||
return `<span class="ccell">${mark}<span>${esc(c?countryName(c):"Unknown")}</span></span>`;
|
||
}
|
||
function countryOptions(sel,emptyLabel="Not set"){
|
||
return `<option value="">${emptyLabel}</option>`+COUNTRIES.slice().sort((a,b)=>a[1].localeCompare(b[1])).map(([c,n])=>`<option value="${c}" ${sel===c?"selected":""}>${esc(n)} (${c})</option>`).join("")
|
||
+(sel&&!COUNTRIES.some(x=>x[0]===sel)?`<option value="${esc(sel)}" selected>${esc(sel)}</option>`:"");
|
||
}
|
||
const regionLabel=(c,r)=>c==="USA"&&r?`USA·${r}`:(c||"?");
|
||
/* Make/model helpers. "Kia Ceed" -> make "Kia". Multi-word makes are kept together. */
|
||
const TWO_WORD_MAKES=["land rover","alfa romeo","aston martin","rolls royce","mercedes benz","great wall","lynk &"];
|
||
function makeOf(model){
|
||
const m=String(model||"").trim().replace(/\s+/g," "); if(!m) return "";
|
||
const low=m.toLowerCase(); const two=TWO_WORD_MAKES.find(x=>low.startsWith(x+" ")||low===x);
|
||
const words=m.split(" "); const w = two ? words.slice(0,two.split(" ").length).join(" ") : words[0];
|
||
return w;
|
||
}
|
||
/* Tidy a make/model: all-lowercase words get a capital ("kia picanto" -> "Kia Picanto"); BMW, iX3, e-Golf stay as typed. */
|
||
const normModel=s=>String(s||"").trim().replace(/\s+/g," ").slice(0,60).split(" ").map(w=>BRAND_CAPS[w.toLowerCase()]||(/^[a-z]+$/.test(w)?w[0].toUpperCase()+w.slice(1):w)).join(" ");
|
||
const BRAND_CAPS={vw:"VW",bmw:"BMW",byd:"BYD",mg:"MG",ds:"DS",gmc:"GMC",seat:"SEAT",cupra:"Cupra",mini:"MINI"};
|
||
const ci=s=>String(s||"").toLowerCase();
|
||
/* Display name for a make or model: the most used spelling wins ("KIA ceed" and "Kia Ceed" count as one). */
|
||
function canonicalNames(list,fn){ const c=new Map(); list.forEach(t=>{ const v=fn(t); if(!v) return; const k=ci(v); const m=c.get(k)||new Map(); m.set(v,(m.get(v)||0)+1); c.set(k,m); }); const out=new Map(); c.forEach((m,k)=>out.set(k,normModel([...m.entries()].sort((a,b)=>b[1]-a[1])[0][0]))); return out; }
|
||
const vkey=t=>(t.country||"")+"|"+(t.region||"")+"|"+(t.plate||"");
|
||
const vparts=k=>{ const [c,r,...p]=k.split("|"); return [p.join("|"),c,r]; };
|
||
const looksDutch=p=>{ const x=p.replace(/\s/g,""); return /^[A-Z0-9]{1,3}-[A-Z0-9]{1,3}-[A-Z0-9]{1,3}$/.test(x) && x.replace(/-/g,"").length===6; };
|
||
function catHtml(k){ const c=CAT[k]; return c?`<span class="pill"><span class="dot" style="background:${c.color}"></span>${esc(c.label)}</span>`:esc(k); }
|
||
function toast(msg){ const r=$("#toastRoot"); r.innerHTML=`<div class="toast" role="status">${esc(msg)}</div>`; clearTimeout(toast.t); toast.t=setTimeout(()=>r.innerHTML="",2600); }
|
||
|
||
/* ---------- API ---------- */
|
||
async function api(method, path, body){
|
||
const r=await fetch("api/"+path,{method,headers:body?{"Content-Type":"application/json"}:{},body:body?JSON.stringify(body):undefined});
|
||
if(!r.ok){ let m="Request failed"; try{ m=(await r.json()).error||m; }catch(_){} const e=new Error(m); e.status=r.status; throw e; }
|
||
return r.status===204?null:r.json();
|
||
}
|
||
async function reload(){
|
||
try{
|
||
const [rows,locs,settings]=await Promise.all([api("GET","trips"),api("GET","locations"),api("GET","settings")]);
|
||
applyCatLabels(settings.categoryLabels);
|
||
trips=rows.map(t=>({...t,id:String(t.id),km:+t.km}));
|
||
locCountry=new Map(locs.filter(l=>l.country).map(l=>[l.name,l.country]));
|
||
loaded=true; showBanner(""); render();
|
||
}catch(e){
|
||
loaded=true; render();
|
||
showBanner(`<div class="notice"><p>Couldn't load trips from the server: ${esc(e.message)}. Check that the database is reachable, then reload.</p><button class="btn" id="retry">Try again</button></div>`);
|
||
const b=$("#retry"); if(b) b.onclick=reload;
|
||
}
|
||
}
|
||
store={
|
||
add:async d=>{ await api("POST","trips",d); await reload(); },
|
||
addMany:async list=>{ const r=await api("POST","trips/bulk",{trips:list}); await reload(); return r.inserted; },
|
||
update:async (i,d)=>{ await api("PUT","trips/"+encodeURIComponent(i),d); await reload(); },
|
||
renamePlates:async changes=>{ const r=await api("POST","plates/rename",{changes}); await reload(); return r.updated; },
|
||
setCatLabels:async labels=>{ await api("PUT","settings/categories",{labels}); await reload(); },
|
||
setLocCountry:async (name,country)=>{ await api("PUT","locations",{name,country}); },
|
||
renameLocation:async (from,to)=>{ const r=await api("POST","locations/rename",{from,to}); await reload(); return r.updated; },
|
||
deleteVehicle:async (plate,country,region)=>{ const r=await api("POST","vehicles/delete",{plate,country,region}); await reload(); return r.deleted; },
|
||
setVehicle:async (plate,from,v)=>{ const r=await api("POST","vehicles/update",{plate,from,...v}); return r.updated; },
|
||
remove:async i=>{ await api("DELETE","trips/"+encodeURIComponent(i)); await reload(); }
|
||
};
|
||
function boot(){ render(); reload(); }
|
||
function showBanner(html){ const b=$("#banner"); b.innerHTML=html; b.hidden=!html; }
|
||
|
||
async function safe(fn, okMsg){
|
||
try{ await fn(); if(okMsg) toast(okMsg); return true; }
|
||
catch(e){ toast(e.status===400?e.message:"Couldn't save. Check the connection to the server and try again."); return false; }
|
||
}
|
||
|
||
/* ---------- derived data ---------- */
|
||
function yearsOf(list){ return [...new Set(list.map(t=>(t.start||"").slice(0,4)).filter(Boolean))].sort().reverse(); }
|
||
/* The make/model most recently entered for each vehicle */
|
||
function latestModels(){ const m=new Map(); [...trips].sort((a,b)=>String(a.start).localeCompare(String(b.start))||(+a.id-+b.id)).forEach(t=>{ if(t.model) m.set(vkey(t),t.model); }); return m; }
|
||
function applyFilters(list,f){
|
||
return list.filter(t=>(f.cat==="all"||t.category===f.cat)&&(f.year==="all"||(t.start||"").startsWith(f.year))&&(f.veh==="all"||vkey(t)===f.veh)&&locMatch(t,f.loc)&&carMatch(t,f.car));
|
||
}
|
||
function locMatch(t,loc){
|
||
if(!loc||loc==="all") return true;
|
||
if(loc.startsWith("lc:")) return lcOf(t.location)===loc.slice(3) && !!t.location;
|
||
return (t.location||"")===loc.slice(4); // "loc:<name>"
|
||
}
|
||
function carMatch(t,car){
|
||
if(!car||car==="all") return true;
|
||
if(car==="none") return !t.model;
|
||
const [kind,val]=[car.slice(0,car.indexOf(":")),car.slice(car.indexOf(":")+1)];
|
||
return kind==="make" ? ci(makeOf(t.model))===val : ci(normModel(t.model))===val;
|
||
}
|
||
function filtered(){
|
||
const q=ui.q.trim().toLowerCase().replace(/[-\s]/g,"");
|
||
let list=applyFilters(trips,ui.t).filter(t=>!q || (t.plate||"").toLowerCase().replace(/[-\s]/g,"").includes(q) || (t.location||"").toLowerCase().replace(/\s/g,"").includes(q) || countryName(t.country).toLowerCase().includes(q) || (t.region&&US_STATES[t.region]?US_STATES[t.region][0].toLowerCase().replace(/\s/g,"").includes(q):false) || (t.country||"").toLowerCase()===q || ci(t.model).replace(/\s/g,"").includes(q));
|
||
const k=ui.sort, s=ui.dir==="asc"?1:-1;
|
||
list.sort((a,b)=>{
|
||
let x=a[k], y=b[k];
|
||
if(k==="km"){ x=+x||0; y=+y||0; return (x-y)*s; }
|
||
x=String(x??"").toLowerCase(); y=String(y??"").toLowerCase();
|
||
return (x<y?-1:x>y?1:0)*s || String(b.start).localeCompare(String(a.start));
|
||
});
|
||
return list;
|
||
}
|
||
|
||
/* ---------- render ---------- */
|
||
function syncClearButtons(){ document.querySelectorAll("[data-clear]").forEach(b=>{ const i=document.getElementById(b.dataset.clear); b.hidden=!(i&&i.value); }); }
|
||
function clearSearch(id){ const i=document.getElementById(id); if(!i) return; i.value=""; i.dispatchEvent(new Event("input",{bubbles:true})); i.focus(); }
|
||
function render(){
|
||
syncClearButtons();
|
||
document.querySelectorAll(".tabs button").forEach(b=>b.setAttribute("aria-selected", b.dataset.view===ui.view));
|
||
$("#view-trips").hidden = ui.view!=="trips";
|
||
$("#view-stats").hidden = ui.view!=="stats";
|
||
$("#view-admin").hidden = ui.view!=="admin";
|
||
$("#writeTools").hidden = !canWrite;
|
||
if(ui.view==="trips") renderTrips(); else if(ui.view==="stats") renderStats(); else renderAdmin();
|
||
}
|
||
|
||
function renderFilters(el, scope, allYearsLabel){
|
||
const f=ui[scope];
|
||
const ys=yearsOf(trips);
|
||
if(f.year===null){ const cur=String(new Date().getFullYear()); f.year=ys.includes(cur)?cur:(ys[0]||"all"); }
|
||
if(f.year!=="all"&&!ys.includes(f.year)) f.year="all";
|
||
const vmap=new Map(); trips.forEach(t=>vmap.set(vkey(t),(vmap.get(vkey(t))||0)+1));
|
||
const vehModel=latestModels();
|
||
const vehs=[...vmap.keys()].sort((a,b)=>vparts(a)[0].localeCompare(vparts(b)[0]));
|
||
if(f.veh!=="all"&&!vmap.has(f.veh)) f.veh="all";
|
||
const locs=[...new Set(trips.map(t=>t.location).filter(Boolean))].sort((a,b)=>a.localeCompare(b));
|
||
const lcs=[...new Set(locs.map(lcOf))];
|
||
const locVals=new Set(["all",...locs.map(l=>"loc:"+l),...lcs.map(c=>"lc:"+c)]);
|
||
if(!locVals.has(f.loc)) f.loc="all";
|
||
const opt=(v,l,cur)=>`<option value="${esc(v)}" ${v===cur?"selected":""}>${esc(l)}</option>`;
|
||
// make/model options grouped per make: "Kia (all)", "Kia Ceed", "Kia Picanto"
|
||
const modelNames=canonicalNames(trips,t=>normModel(t.model)), makeNames=canonicalNames(trips,t=>makeOf(t.model));
|
||
const makes=[...makeNames.keys()].sort();
|
||
const carVals=new Set(["all","none",...makes.map(k=>"make:"+k),...[...modelNames.keys()].map(k=>"model:"+k)]);
|
||
if(!carVals.has(f.car)) f.car="all";
|
||
const carOpts = makes.length ? opt("all","All makes & models",f.car)+makes.map(mk=>{
|
||
const models=[...modelNames.keys()].filter(k=>ci(makeOf(modelNames.get(k)))===mk).sort();
|
||
if(models.length===1) return opt("model:"+models[0],modelNames.get(models[0]),f.car); // one model: no "(all)" line needed
|
||
return `<optgroup label="${esc(makeNames.get(mk))}">${opt("make:"+mk,makeNames.get(mk)+" (all)",f.car)}${models.map(k=>opt("model:"+k,modelNames.get(k),f.car)).join("")}</optgroup>`;
|
||
}).join("")+(trips.some(t=>!t.model)?opt("none","No make/model set",f.car):"") : "";
|
||
const active=f.cat!=="all"||f.veh!=="all"||f.loc!=="all"||f.car!=="all"||(scope==="t"&&(f.year!=="all"||ui.q));
|
||
const id=k=>`${scope}-${k}`;
|
||
el.innerHTML=`
|
||
<select class="field" id="${id("year")}" data-scope="${scope}" data-f="year" aria-label="Period">${opt("all",allYearsLabel,f.year)}${ys.map(y=>opt(y,y,f.year)).join("")}</select>
|
||
<select class="field" id="${id("veh")}" data-scope="${scope}" data-f="veh" aria-label="Vehicle">${opt("all","All vehicles",f.veh)}${vehs.map(k=>{const [p,c,r]=vparts(k);const md=vehModel.get(k);return opt(k,`${p} (${regionLabel(c,r)})${md?" · "+md:""}`,f.veh);}).join("")}</select>
|
||
${carOpts?`<select class="field" id="${id("car")}" data-scope="${scope}" data-f="car" aria-label="Make and model">${carOpts}</select>`:""}
|
||
<select class="field" id="${id("loc")}" data-scope="${scope}" data-f="loc" aria-label="Location">${opt("all","All locations",f.loc)}${
|
||
lcs.sort((a,b)=>(a===""?1:0)-(b===""?1:0)||countryName(a).localeCompare(countryName(b))).map(c=>{
|
||
const inC=locs.filter(l=>lcOf(l)===c), name=c?countryName(c):"Country not set";
|
||
if(inC.length===1&&c) return `<optgroup label="${esc(name)}">${opt("loc:"+inC[0],inC[0],f.loc)}</optgroup>`;
|
||
return `<optgroup label="${esc(name)}">${opt("lc:"+c,name+" (all)",f.loc)}${inC.map(l=>opt("loc:"+l,l,f.loc)).join("")}</optgroup>`;
|
||
}).join("")}</select>
|
||
<div class="chips">${[{key:"all",label:"All categories"},...CATS].map(c=>`<button class="chip" data-scope="${scope}" data-fcat="${c.key}" aria-pressed="${f.cat===c.key}">${c.color?`<span class="dot" style="background:${c.color}"></span>`:""}${esc(c.label)}</button>`).join("")}</div>
|
||
${active?`<button class="btn ghost" data-act="reset" data-scope="${scope}">Clear filters</button>`:""}`;
|
||
}
|
||
|
||
function renderTrips(){
|
||
renderFilters($("#tripFilters"),"t","All years");
|
||
|
||
const card=$("#tripsCard");
|
||
if(!loaded){ card.innerHTML=`<div class="empty">Loading trips…</div>`; return; }
|
||
if(!trips.length){
|
||
card.innerHTML=`<div class="empty"><h2>No trips yet</h2><p>Add your first trip, or paste the rows from your Excel sheet to bring everything over at once.</p>
|
||
${canWrite?`<div class="toolbar"><button class="btn primary" data-act="add">+ Add trip</button><button class="btn" data-act="import">Import from Excel</button></div>`:""}</div>`;
|
||
return;
|
||
}
|
||
const list=filtered();
|
||
const totKm=list.reduce((s,t)=>s+(+t.km||0),0);
|
||
const arrow=k=>ui.sort===k?(ui.dir==="asc"?" ↑":" ↓"):"";
|
||
const th=(k,l,cls="")=>`<th class="sortable ${cls}" data-sort="${k}" scope="col">${l}${arrow(k)}</th>`;
|
||
const rows=list.map(t=>{
|
||
if(ui.confirmId===t.id) return `<tr class="confirm"><td colspan="7"><div class="toolbar" style="justify-content:space-between">
|
||
<span>Delete the trip of ${fmtDate(t.start)} with ${esc(t.plate)}${t.country?" ("+esc(t.country)+")":""}, ${fmtKm(+t.km||0)} km?</span>
|
||
<span class="toolbar"><button class="btn" data-act="cancelDel">Keep it</button><button class="btn danger" data-act="doDel" data-id="${t.id}">Delete trip</button></span></div></td></tr>`;
|
||
return `<tr>
|
||
<td class="num">${fmtDate(t.start)}</td>
|
||
<td class="num">${t.end&&t.end!==t.start?fmtDate(t.end):`<span style="color:var(--muted)">same day</span>`}</td>
|
||
<td><span class="platecell">${plateHtml(t.plate,t.country,t.region)}${t.model?`<span class="model">${esc(t.model)}</span>`:""}${t.source==="ha"?`<span class="srctag" title="Added automatically from Home Assistant">HA</span>`:""}</span></td>
|
||
<td>${esc(t.location)}</td>
|
||
<td>${catHtml(t.category)}</td>
|
||
<td class="r num km">${fmtKm(+t.km||0)}</td>
|
||
<td class="actions">${canWrite?`<button class="btn ghost" data-act="edit" data-id="${t.id}">Edit</button><button class="btn ghost" data-act="del" data-id="${t.id}">Delete</button>`:""}</td>
|
||
</tr>`;}).join("");
|
||
card.innerHTML=`<div class="sumline"><span><b class="num">${list.length}</b> of ${trips.length} trips shown</span><span><b class="num">${fmtKm(totKm)} km</b> in this selection</span></div>
|
||
<div class="tablewrap"><table><thead><tr>${th("start","Start")}${th("end","End")}${th("plate","Plate")}${th("location","Location")}${th("category","Category")}${th("km","Km","r")}<th></th></tr></thead>
|
||
<tbody>${rows||`<tr><td colspan="7" class="empty">No trips match these filters.</td></tr>`}</tbody></table></div>`;
|
||
}
|
||
|
||
/* ---------- statistics ---------- */
|
||
function renderStats(){
|
||
renderFilters($("#statsFilters"),"s","All time");
|
||
ui.statsYear=ui.s.year;
|
||
const body=$("#statsBody");
|
||
if(!loaded){ body.innerHTML=`<div class="card empty">Loading trips…</div>`; return; }
|
||
const list=applyFilters(trips,ui.s);
|
||
if(!list.length){ body.innerHTML=trips.length?`<div class="card empty"><h2>No trips match these filters</h2><p>Pick another period, vehicle, location or category.</p></div>`:`<div class="card empty"><h2>Nothing to count yet</h2><p>Statistics appear here as soon as there are trips in the log.</p></div>`; return; }
|
||
|
||
const km=list.reduce((s,t)=>s+(+t.km||0),0);
|
||
const byCat=CATS.map(c=>({...c, km:list.filter(t=>t.category===c.key).reduce((s,t)=>s+(+t.km||0),0), n:list.filter(t=>t.category===c.key).length}));
|
||
const longest=list.reduce((a,t)=>(+t.km||0)>(+a.km||0)?t:a,list[0]);
|
||
const dayTotal=list.reduce((s,t)=>s+days(t),0);
|
||
const businessKm=byCat.filter(c=>c.key!=="personal").reduce((s,c)=>s+c.km,0);
|
||
|
||
const tiles=`<div class="tiles">
|
||
<div class="tile"><div class="lab">Total distance</div><div class="val num">${fmtKm(km)}<small>km</small></div><div class="sub">${ui.statsYear==="all"?"all time":ui.statsYear}</div></div>
|
||
<div class="tile"><div class="lab">Trips</div><div class="val num">${list.length}</div><div class="sub num">${dayTotal} day${dayTotal===1?"":"s"} on the road</div></div>
|
||
<div class="tile"><div class="lab">Average trip</div><div class="val num">${fmtKm(km/list.length)}<small>km</small></div><div class="sub num">${fmtKm(km/dayTotal)} km per day</div></div>
|
||
<div class="tile"><div class="lab">Longest trip</div><div class="val num">${fmtKm(+longest.km||0)}<small>km</small></div><div class="sub">${esc(longest.location)} · ${fmtDate(longest.start)}</div></div>
|
||
</div>`;
|
||
|
||
const split=`<div class="card panel"><h2>Distance by category</h2><p class="hint num">${esc(CATS[0].label)} and ${esc(CATS[1].label)} together: ${fmtKm(businessKm)} km (${km?Math.round(businessKm/km*100):0}%) · ${esc(CATS[2].label)}: ${fmtKm(byCat[2].km)} km</p>
|
||
<div class="split">${byCat.filter(c=>c.km>0).map(c=>`<div style="width:${c.km/km*100}%;background:${c.color}" title="${esc(c.label)}: ${fmtKm(c.km)} km"></div>`).join("")}</div>
|
||
<div class="legend">${byCat.map(c=>`<div><span class="dot" style="background:${c.color}"></span><b>${esc(c.label)}</b><span class="num">${fmtKm(c.km)} km · ${km?Math.round(c.km/km*100):0}% · ${c.n} trip${c.n===1?"":"s"}</span></div>`).join("")}</div></div>`;
|
||
|
||
body.innerHTML = tiles + split + monthlyChart(list) +
|
||
`<div class="grid2">${rankPanel("By vehicle", "Kilometres per license plate", list, vkey, k=>{const [p,c,r]=vparts(k);return plateHtml(p,c,r);}, {col:"Plate", sortName:k=>vparts(k)[0]})}${rankPanel("By location", "Kilometres per location", list, t=>t.location||"—", l=>esc(l), {col:"Location"})}</div>`+
|
||
(()=>{ const us=list.filter(t=>t.country==="USA");
|
||
// One country per trip: the location's country, or the plate's country when the location has none yet
|
||
const cp=rankPanel("By country", "Kilometres per country of the location (the plate's country where the location has none)", list, t=>(t.location&&lcOf(t.location))||t.country||"", c=>countryLabel(c), {col:"Country", sortName:c=>c?countryName(c):""});
|
||
if(!us.length) return cp;
|
||
return `<div class="grid2">${cp}${rankPanel("By US state", "Kilometres per state, for US plates", us, t=>t.region||"", r=>r&&US_STATES[r]?esc(US_STATES[r][0]):`<span style="color:var(--muted)">State not set</span>`, {col:"State", sortName:r=>r&&US_STATES[r]?US_STATES[r][0]:""})}</div>`; })() +
|
||
(list.some(t=>t.model) ? (()=>{ const mk=canonicalNames(trips,t=>makeOf(t.model)), md=canonicalNames(trips,t=>normModel(t.model));
|
||
return `<div class="grid2">${rankPanel("By make", "Kilometres per car brand", list, t=>t.model?ci(makeOf(t.model)):"—", k=>k==="—"?`<span style="color:var(--muted)">Not set</span>`:esc(mk.get(k)||k), {col:"Make", sortName:k=>k==="—"?"":(mk.get(k)||k)})}${rankPanel("By make/model", "Kilometres per model", list, t=>t.model?ci(normModel(t.model)):"—", k=>k==="—"?`<span style="color:var(--muted)">Not set</span>`:esc(md.get(k)||k), {col:"Make/model", sortName:k=>k==="—"?"":(md.get(k)||k)})}</div>`; })() : "");
|
||
const ms=$("#monthScroll"); if(ms&&ms.scrollWidth>ms.clientWidth) ms.scrollLeft=ms.scrollWidth; // open on the latest months
|
||
}
|
||
|
||
function monthBuckets(list){
|
||
let months=[];
|
||
if(ui.statsYear!=="all"){ for(let m=1;m<=12;m++) months.push(`${ui.statsYear}-${String(m).padStart(2,"0")}`); }
|
||
else{
|
||
// All time: every month from the first to the last trip (at least 12 months)
|
||
const last = list.reduce((a,t)=>t.start>a?t.start:a,"").slice(0,7) || new Date().toISOString().slice(0,7);
|
||
const first = list.reduce((a,t)=>t.start&&t.start<a?t.start:a,last+"-99").slice(0,7);
|
||
let [y,m]=last.split("-").map(Number);
|
||
while(true){ const k=`${y}-${String(m).padStart(2,"0")}`; months.unshift(k); if(k<=first&&months.length>=12) break; m--; if(!m){m=12;y--;} }
|
||
}
|
||
return months.map(k=>{ const ts=list.filter(t=>(t.start||"").startsWith(k)); return {k, cats:CATS.map(c=>ts.filter(t=>t.category===c.key).reduce((s,t)=>s+(+t.km||0),0))}; });
|
||
}
|
||
function niceMax(v){ if(v<=0) return 100; const p=Math.pow(10,Math.floor(Math.log10(v))); const n=v/p; return (n<=1?1:n<=2?2:n<=2.5?2.5:n<=5?5:10)*p; }
|
||
function monthlyChart(list){
|
||
const b=monthBuckets(list);
|
||
const W=Math.max(760, 62+b.length*34), H=260,L=52,R=10,T=22,B=28, iw=W-L-R, ih=H-T-B; // wider (scrolls) when there are many months
|
||
const max=niceMax(Math.max(...b.map(x=>x.cats.reduce((s,v)=>s+v,0))));
|
||
const y=v=>T+ih-(v/max)*ih;
|
||
const bw=iw/b.length, gap=Math.min(14,bw*.28);
|
||
let g="";
|
||
const wide=W>760; // many months: the bars scroll, the km scale stays pinned on the left
|
||
let axis="";
|
||
for(let i=0;i<=4;i++){ const v=max*i/4, yy=y(v); g+=`<line class="grid" x1="${wide?0:L}" x2="${W-R}" y1="${yy}" y2="${yy}"/>`; const lbl=`<text class="axis" x="${L-8}" y="${yy+4}" text-anchor="end">${fmtKm(v)}</text>`; if(wide) axis+=lbl; else g+=lbl; }
|
||
b.forEach((m,i)=>{
|
||
const x=L+i*bw+gap/2, w=bw-gap; let acc=0;
|
||
m.cats.forEach((v,ci)=>{ if(!v) return; const y0=y(acc), y1=y(acc+v); g+=`<rect x="${x}" y="${y1}" width="${w}" height="${Math.max(0,y0-y1)}" style="fill:${CATS[ci].color}"><title>${MONTHS[+m.k.slice(5)-1]} ${m.k.slice(0,4)} · ${esc(CATS[ci].label)}: ${fmtKm(v)} km</title></rect>`; acc+=v; });
|
||
if(acc) g+=`<text class="tot" x="${x+w/2}" y="${y(acc)-5}" text-anchor="middle">${fmtKm(Math.round(acc))}</text>`;
|
||
const lab=MONTHS[+m.k.slice(5)-1]+(ui.statsYear==="all"&&m.k.slice(5)==="01"?" ’"+m.k.slice(2,4):"");
|
||
g+=`<text class="axis" x="${x+w/2}" y="${H-8}" text-anchor="middle">${lab}</text>`;
|
||
});
|
||
g+=`<line x1="${wide?0:L}" x2="${W-R}" y1="${T+ih}" y2="${T+ih}" stroke="var(--muted)" stroke-width="1"/>`;
|
||
return `<div class="card panel chart"><h2>Kilometres per month</h2><p class="hint">${ui.statsYear==="all"?`All ${b.length} months, from ${MONTHS[+b[0].k.slice(5)-1]} ${b[0].k.slice(0,4)}`:ui.statsYear}, by start date of the trip${W>760?" · scroll sideways for more":""}</p>
|
||
${wide
|
||
? `<div class="chartrow"><svg class="yaxis" viewBox="0 0 ${L} ${H}" width="${L}" height="${H}" aria-hidden="true">${axis}</svg>
|
||
<div class="tablewrap" id="monthScroll"><svg viewBox="${L} 0 ${W-L} ${H}" width="${W-L}" height="${H}" role="img" aria-label="Kilometres per month, stacked by category" style="max-width:none">${g}</svg></div></div>`
|
||
: `<div class="tablewrap" id="monthScroll"><svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Kilometres per month, stacked by category" style="min-width:520px">${g}</svg></div>`}
|
||
<div class="legend" style="margin-top:8px">${CATS.map(c=>`<div><span class="dot" style="background:${c.color}"></span>${esc(c.label)}</div>`).join("")}</div></div>`;
|
||
}
|
||
/* Ranking panel: sortable columns (name, trips, km); shows 10 rows with a button to show all.
|
||
Sorting and "show all" are remembered per panel. */
|
||
function rankPanel(title, hint, list, keyFn, fmt, opts={}){
|
||
const limit=opts.limit||10, col=opts.col||"Name", sortName=opts.sortName||(k=>String(k));
|
||
const m=new Map();
|
||
list.forEach(t=>{ const k=keyFn(t); const e=m.get(k)||{k,km:0,n:0,cats:[0,0,0]}; e.km+=+t.km||0; e.n++; const ci=CATS.findIndex(c=>c.key===t.category); if(ci>=0) e.cats[ci]+=+t.km||0; m.set(k,e); });
|
||
const srt=ui.rankSort[title]||{key:"km",dir:"desc"}, d=srt.dir==="asc"?1:-1;
|
||
const nameKey=r=>{ const v=sortName(r.k); return v===""||v==="—"?"\uffff":String(v).toLowerCase(); }; // "not set" rows last
|
||
const all=[...m.values()].sort((a,b)=>
|
||
srt.key==="name" ? nameKey(a).localeCompare(nameKey(b))*d || b.km-a.km :
|
||
srt.key==="n" ? (a.n-b.n)*d || b.km-a.km :
|
||
(a.km-b.km)*d);
|
||
const open=ui.expanded.has(title), rows=open?all:all.slice(0,limit);
|
||
const top=Math.max(...all.map(r=>r.km),1);
|
||
const lead = srt.key==="km"&&srt.dir==="desc" ? "Top" : "First";
|
||
const more = all.length>limit ? `<div class="rankmore"><span class="num">${open?`All ${all.length}`:`${lead} ${limit} of ${all.length}`}</span><button class="btn ghost" data-act="expand" data-panel="${esc(title)}">${open?"Show fewer":`Show all ${all.length}`}</button></div>` : "";
|
||
const arrow=k=>srt.key===k?(srt.dir==="asc"?" ↑":" ↓"):"";
|
||
const th=(k,label,cls="")=>`<th class="sortable ${cls}" data-rsort="${k}" data-panel="${esc(title)}" scope="col" aria-sort="${srt.key===k?(srt.dir==="asc"?"ascending":"descending"):"none"}">${label}${arrow(k)}</th>`;
|
||
return `<div class="card panel"><h2>${title}</h2><p class="hint">${hint}${all.length>1?` · ${all.length} in total`:""}</p>
|
||
<table class="rank"><thead><tr>${th("name",col)}${th("n","Trips")}<th scope="col"><span class="sr">Share by category</span></th>${th("km","Km","r")}</tr></thead><tbody>${rows.map(r=>`<tr>
|
||
<td>${fmt(r.k)}</td><td class="num" style="color:var(--muted);white-space:nowrap">${r.n} trip${r.n===1?"":"s"}</td>
|
||
<td class="barcell"><div class="track" style="width:${r.km/top*100}%">${r.cats.map((v,i)=>v?`<div style="flex:${v};background:${CATS[i].color}"></div>`:"").join("")}</div></td>
|
||
<td class="r num" style="text-align:right;font-weight:600;white-space:nowrap">${fmtKm(r.km)} km</td></tr>`).join("")}</tbody></table>${more}</div>`;
|
||
}
|
||
|
||
/* ---------- admin: locations ---------- */
|
||
const locKey=l=>String(l||"").trim().replace(/\s+/g," ").toLowerCase();
|
||
let adminRows=[];
|
||
/* Sortable column titles for the Admin tables. State per table in ui.tsort[table] = {key, dir}. */
|
||
function sortTh(table,key,label,cls=""){
|
||
const st=ui.tsort[table]||{}, on=st.key===key;
|
||
return `<th class="sortable ${cls}" data-tsort="${table}:${key}" scope="col" aria-sort="${on?(st.dir==="asc"?"ascending":"descending"):"none"}">${label}${on?(st.dir==="asc"?" ↑":" ↓"):""}</th>`;
|
||
}
|
||
/* Sort rows by the chosen column. Empty values always go last, whatever the direction. */
|
||
function sortRows(rows,table,getters){
|
||
const st=ui.tsort[table]; if(!st||!getters[st.key]) return rows;
|
||
const g=getters[st.key], d=st.dir==="asc"?1:-1;
|
||
const empty=v=>v===""||v===null||v===undefined;
|
||
return rows.slice().sort((a,b)=>{ const x=g(a), y=g(b);
|
||
if(empty(x)||empty(y)) return empty(x)-empty(y);
|
||
return (typeof x==="number"&&typeof y==="number" ? x-y : String(x).localeCompare(String(y),"nl",{numeric:true}))*d; });
|
||
}
|
||
const ADMIN_TABS=["locations","vehicles","categories","ha"];
|
||
function renderAdmin(){
|
||
const t=ADMIN_TABS.includes(ui.adminTab)?ui.adminTab:"locations";
|
||
ADMIN_TABS.forEach(k=>{ $("#apane-"+k).hidden=k!==t; $("#atab-"+k).setAttribute("aria-selected",k===t); });
|
||
// counts on the tabs, so you can see what needs attention without opening each one
|
||
const vehs=new Set(trips.map(vkey)).size, noLc=new Set(trips.map(x=>x.location).filter(l=>l&&!lcOf(l))).size;
|
||
$("#atab-vehicles").innerHTML=`Vehicles <span class="tabcount">${vehs}</span>`;
|
||
$("#atab-locations").innerHTML=`Locations <span class="tabcount">${new Set(trips.map(x=>x.location).filter(Boolean)).size}</span>${noLc?`<span class="tabwarn" title="${noLc} without a country">${noLc}</span>`:""}`;
|
||
if(t==="locations") renderAdminLocations();
|
||
else if(t==="vehicles") renderAdminVehicles();
|
||
else if(t==="categories") renderAdminCategories();
|
||
else renderAdminHa();
|
||
}
|
||
/* ---------- admin: Home Assistant ---------- */
|
||
let haStatus=null, haLoading=false;
|
||
const haPref=(k,d)=>{ try{ return localStorage.getItem("kmlog-ha-"+k)||d; }catch(e){ return d; } };
|
||
const haSave=(k,v)=>{ try{ localStorage.setItem("kmlog-ha-"+k,v); }catch(e){} };
|
||
async function loadHa(){ if(haLoading) return; haLoading=true; try{ haStatus=await api("GET","ha/status"); }catch(e){ haStatus={error:e.message}; } haLoading=false; renderAdminHa(); }
|
||
/* The Home Assistant setup, as three separate pieces to paste in three places. */
|
||
/* How Home Assistant reaches the app. Internal routes skip Traefik (no redirects, no public domain). */
|
||
const HA_ROUTES={
|
||
docker:{label:"Docker network: http://kilometer-log:3000", base:"http://kilometer-log:3000"},
|
||
host: {label:"Same host (Home Assistant with network_mode: host): http://127.0.0.1:3077", base:"http://127.0.0.1:3077"},
|
||
site: {label:"Public address of this site", base:null}
|
||
};
|
||
function haBase(route){ return (HA_ROUTES[route]||HA_ROUTES.docker).base || location.origin; }
|
||
function haYaml(o){
|
||
const url=haBase(o.route)+"/api/ha/odometer";
|
||
const config=`rest_command:
|
||
kilometer_log_odometer:
|
||
url: "${url}"
|
||
method: POST
|
||
headers:
|
||
Authorization: !secret kilometer_log_auth
|
||
content_type: "application/json"
|
||
payload: >-
|
||
{"plate": "${o.plate}", "odometer": {{ odometer }}, "unit": "{{ unit }}",
|
||
"time": "{{ time }}", "latitude": {{ latitude | to_json }}, "longitude": {{ longitude | to_json }},
|
||
"location": {{ location | to_json }}, "category": "${o.category}"}`;
|
||
const secrets=`kilometer_log_auth: "Bearer <the same token as HA_TOKEN>"`;
|
||
const automation=`alias: "Kilometer Log: send odometer"
|
||
description: "Sends the odometer and position to Kilometer Log, which adds the distance as a trip."
|
||
mode: queued
|
||
triggers:
|
||
- trigger: state
|
||
entity_id: ${o.odo}
|
||
conditions:
|
||
- condition: template
|
||
value_template: "{{ states('${o.odo}') | is_number }}"
|
||
actions:
|
||
# give the car's position a moment to update after the odometer
|
||
- delay: "00:01:00"
|
||
- action: rest_command.kilometer_log_odometer
|
||
# the app's answer (status and message) shows up in this automation's trace
|
||
response_variable: kilometer_log
|
||
data:
|
||
# read from the sensor itself, so "Run actions" (a manual test) works too
|
||
odometer: "{{ states('${o.odo}') }}"
|
||
unit: "{{ state_attr('${o.odo}', 'unit_of_measurement') or 'km' }}"
|
||
time: "{{ states['${o.odo}'].last_changed.isoformat() }}"
|
||
# the app looks up the town and country for this position
|
||
latitude: "{{ state_attr('${o.tracker}', 'latitude') }}"
|
||
longitude: "{{ state_attr('${o.tracker}', 'longitude') }}"
|
||
# only used if the town can't be looked up: the zone name, when the car is in one
|
||
location: >-
|
||
{% set s = states('${o.tracker}') %}
|
||
{% if s == 'home' %}{{ state_attr('zone.home', 'friendly_name') }}{% elif s not in ['not_home', 'unknown', 'unavailable'] %}{{ s }}{% endif %}`;
|
||
return {config, secrets, automation};
|
||
}
|
||
function renderAdminHa(){
|
||
const card=$("#adminHaCard"); if(!card) return;
|
||
if(!haStatus){ card.innerHTML=`<div class="empty">Checking the Home Assistant connection…</div>`; loadHa(); return; }
|
||
if(card.contains(document.activeElement) && document.activeElement.matches("input,select")) return; // don't redraw while typing
|
||
if(haStatus.error){ card.innerHTML=`<div class="empty">Couldn't load the Home Assistant status: ${esc(haStatus.error)}</div>`; return; }
|
||
const plates=[...new Set(trips.map(t=>t.plate).filter(Boolean))].sort();
|
||
const o={ route:haPref("route","docker"), plate:haPref("plate",plates[0]||"AB-123-C"), odo:haPref("odo","sensor.car_odometer"), tracker:haPref("tracker","device_tracker.car_location"), category:haPref("cat","personal") };
|
||
const status = haStatus.enabled
|
||
? `<span class="pill"><span class="dot" style="background:var(--c-personal)"></span>On</span> · The app accepts readings from Home Assistant.${haStatus.geocoder?` Town names come from OpenStreetMap (language: ${esc(haStatus.geocoder.lang)}).`:" Town lookup is off (GEOCODER=off)."}`
|
||
: `<span class="pill"><span class="dot" style="background:var(--muted)"></span>Off</span> · Add a long random <code>HA_TOKEN</code> to the stack's environment variables in Portainer and redeploy to turn it on.`;
|
||
card.innerHTML=`<div class="hapad">
|
||
<p style="margin:0">${status}</p>
|
||
<label class="hafrom">Location of these trips
|
||
<select class="field" id="ha-from">
|
||
<option value="start" ${haStatus.locationFrom!=="end"?"selected":""}>Where the trip started (departure)</option>
|
||
<option value="end" ${haStatus.locationFrom==="end"?"selected":""}>Where the trip ended (arrival)</option>
|
||
</select>
|
||
<span class="small">${haStatus.locationFrom!=="end"
|
||
? "The departure place is where the car stood at the previous reading."
|
||
: "The arrival place is where the car is when the odometer changes."}</span>
|
||
</label>
|
||
${haStatus.lastGet && /HomeAssistant|aiohttp/i.test(haStatus.lastGet.agent) ? `<div class="notice"><p><b>Home Assistant's request arrived without its data</b> (${esc(new Date(haStatus.lastGet.at).toLocaleString("nl-NL",{dateStyle:"medium",timeStyle:"short"}))}). That happens when the address is redirected, usually from <code>http://</code> to <code>https://</code>. Easiest fix: let Home Assistant use the internal address <code>http://kilometer-log:3000/api/ha/odometer</code> (see the setup below), or the exact <code>${esc(location.origin)}/api/ha/odometer</code>, and restart Home Assistant.</p></div>` : ""}
|
||
${location.protocol==="http:" && haPref("route","docker")==="site" ? `<div class="notice"><p>You opened this page over <code>http://</code>, so the address below starts with http://. If your site redirects to https://, open the page via https:// first, so Home Assistant gets the right address.</p></div>` : ""}
|
||
${haStatus.vehicles.length?`<div class="tablewrap"><table><thead><tr>${sortTh("ha","plate","Plate")}${sortTh("ha","odo","Last odometer","r")}${sortTh("ha","read","Received")}${sortTh("ha","event","Last result")}<th></th></tr></thead><tbody>
|
||
${sortRows(haStatus.vehicles,"ha",{plate:v=>v.plate, odo:v=>+v.odometer_km, read:v=>v.read_at, event:v=>v.last_event}).map(v=>`<tr><td style="white-space:nowrap">${esc(v.plate)}</td><td class="r num" style="white-space:nowrap">${fmtKm(+v.odometer_km)} km</td><td class="num" style="white-space:nowrap">${esc(new Date(v.read_at).toLocaleString("nl-NL",{dateStyle:"medium",timeStyle:"short"}))}</td>
|
||
<td class="small">${esc(v.last_event)}</td><td class="actions"><button class="btn ghost" data-act="haForget" data-plate="${esc(v.plate)}" title="The next reading becomes the new starting point">Restart</button></td></tr>`).join("")}</tbody></table></div>`
|
||
: `<p class="small" style="margin:0">No readings received yet. The first reading only sets the starting point; trips start with the second.</p>`}
|
||
<details class="hasetup" id="ha-details" ${(ui.haOpen ?? !haStatus.vehicles.length)?"open":""}><summary>Set up Home Assistant</summary>
|
||
<div class="form hafields">
|
||
<label class="full">How Home Assistant reaches the app<select class="field" id="ha-route" style="width:100%">${Object.entries(HA_ROUTES).map(([k,r])=>`<option value="${k}" ${o.route===k?"selected":""}>${esc(r.label)}${k==="site"?": "+esc(location.origin):""}</option>`).join("")}</select>
|
||
<span class="small" id="ha-route-hint" style="font-weight:400"></span></label>
|
||
<label>License plate<input class="field" id="ha-plate" list="dl-ha-plates" value="${esc(o.plate)}" autocomplete="off"></label>
|
||
<label>Category for these trips<select class="field" id="ha-cat" style="width:100%">${CATS.map(c=>`<option value="${c.key}" ${o.category===c.key?"selected":""}>${esc(c.label)}</option>`).join("")}</select></label>
|
||
<label>Odometer sensor<input class="field" id="ha-odo" value="${esc(o.odo)}" placeholder="sensor.volvo_xc40_odometer" autocomplete="off"></label>
|
||
<label>Location tracker<input class="field" id="ha-tracker" value="${esc(o.tracker)}" placeholder="device_tracker.volvo_xc40_location" autocomplete="off"></label>
|
||
</div>
|
||
<datalist id="dl-ha-plates">${plates.map(p=>`<option value="${esc(p)}">`).join("")}</datalist>
|
||
<ol class="hasteps">
|
||
<li><b>configuration.yaml</b> (in the Home Assistant config folder). Add this, then restart Home Assistant.
|
||
<div class="codewrap"><pre class="code" id="ha-y-config"></pre><button type="button" class="btn" data-copy="ha-y-config">Copy</button></div></li>
|
||
<li><b>secrets.yaml</b> (same folder). Put the token you set as <code>HA_TOKEN</code> after "Bearer ".
|
||
<div class="codewrap"><pre class="code" id="ha-y-secrets"></pre><button type="button" class="btn" data-copy="ha-y-secrets">Copy</button></div></li>
|
||
<li><b>The automation.</b> In Home Assistant go to <i>Settings → Automations & scenes → Create automation → Create new automation</i>, open the ⋮ menu, choose <i>Edit in YAML</i>, replace everything with this and save.
|
||
<div class="codewrap"><pre class="code" id="ha-y-automation"></pre><button type="button" class="btn" data-copy="ha-y-automation">Copy</button></div>
|
||
<p class="small" style="margin:6px 0 0">Adding it to <code>automations.yaml</code> by hand instead? Then put <code>- </code> before <code>alias:</code> and indent the other lines by two spaces.</p></li>
|
||
</ol>
|
||
</details>
|
||
</div>`;
|
||
const ROUTE_HINT={
|
||
docker:"Home Assistant must be on a Docker network that the app is on too, for example your Traefik network. No Traefik or redirects in between.",
|
||
host:"For Home Assistant with network_mode: host. Uncomment the ports line in the compose file, so port 3077 is reachable from the server itself only.",
|
||
site:"Goes through Traefik. Use the exact https:// address: a redirect from http:// drops the data."};
|
||
const paint=()=>{ const route=$("#ha-route").value; haSave("route",route); $("#ha-route-hint").textContent=ROUTE_HINT[route]||"";
|
||
const v={route, plate:$("#ha-plate").value.trim()||"AB-123-C", category:$("#ha-cat").value, odo:$("#ha-odo").value.trim()||"sensor.car_odometer", tracker:$("#ha-tracker").value.trim()||"device_tracker.car_location"};
|
||
haSave("plate",v.plate); haSave("cat",v.category); haSave("odo",v.odo); haSave("tracker",v.tracker);
|
||
const y=haYaml(v); $("#ha-y-config").textContent=y.config; $("#ha-y-secrets").textContent=y.secrets; $("#ha-y-automation").textContent=y.automation; };
|
||
$("#ha-from").addEventListener("change",async e=>{ const v=e.target.value; e.target.disabled=true;
|
||
if(await safe(()=>api("PUT","settings/ha",{locationFrom:v}), v==="end"?"New trips get the arrival place":"New trips get the departure place")){ haStatus.locationFrom=v; e.target.blur(); renderAdminHa(); }
|
||
else e.target.disabled=false; });
|
||
$("#ha-details").addEventListener("toggle",e=>{ ui.haOpen=e.target.open; });
|
||
["ha-route","ha-plate","ha-odo","ha-tracker","ha-cat"].forEach(id=>$("#"+id).addEventListener("input",paint)); paint();
|
||
card.querySelectorAll("[data-copy]").forEach(btn=>btn.onclick=async()=>{ const el=document.getElementById(btn.dataset.copy);
|
||
try{ await navigator.clipboard.writeText(el.textContent); toast("Copied"); }
|
||
catch(e){ const r=document.createRange(); r.selectNodeContents(el); const sel=getSelection(); sel.removeAllRanges(); sel.addRange(r); toast("Selected — press Ctrl+C to copy"); } });
|
||
}
|
||
function renderAdminCategories(){
|
||
const f=$("#catForm"); if(!f) return;
|
||
if(f.contains(document.activeElement)) return; // don't overwrite while typing
|
||
const counts=Object.fromEntries(CATS.map(c=>[c.key,trips.filter(t=>t.category===c.key).length]));
|
||
f.innerHTML=`<div class="catrows">${CATS.map(c=>`<label class="catrow"><span class="dot" style="background:${c.color}"></span>
|
||
<input class="field" id="cat-${c.key}" value="${esc(c.label)}" maxlength="30" placeholder="${esc(c.def)}" aria-label="Name for the ${esc(c.def.toLowerCase())} category">
|
||
<span class="small num">${counts[c.key]} trip${counts[c.key]===1?"":"s"}</span></label>`).join("")}</div>
|
||
<div class="actionsrow" style="justify-content:space-between"><span class="small">Leave a field empty to use the default (${CATS.map(c=>esc(c.def)).join(", ")}).</span>
|
||
<button type="submit" class="btn primary" id="catSave" disabled>Save names</button></div>`;
|
||
const dirty=()=>CATS.some(c=>($("#cat-"+c.key).value.trim()||c.def)!==c.label);
|
||
f.oninput=()=>{ $("#catSave").disabled=!dirty(); };
|
||
f.onsubmit=async e=>{ e.preventDefault(); if(!dirty()) return;
|
||
const labels=Object.fromEntries(CATS.map(c=>[c.key,$("#cat-"+c.key).value.trim()]));
|
||
const names=CATS.map(c=>labels[c.key]||c.def).map(x=>x.toLowerCase());
|
||
if(new Set(names).size<names.length){ toast("Give each category a different name."); return; }
|
||
$("#catSave").disabled=true; document.activeElement.blur();
|
||
if(await safe(()=>store.setCatLabels(labels),"Category names saved")) renderAdminCategories(); else $("#catSave").disabled=false; };
|
||
}
|
||
let vehRows=[];
|
||
function renderAdminVehicles(){
|
||
const card=$("#adminVehCard"), A=ui.adminV;
|
||
if(!loaded){ card.innerHTML=""; return; }
|
||
const lm=latestModels(), m=new Map();
|
||
trips.forEach(t=>{ const k=vkey(t); const e=m.get(k)||{k,plate:t.plate,country:t.country||"",region:t.region||"",n:0,km:0,last:t.start}; e.n++; e.km+=+t.km||0; if(t.start>e.last) e.last=t.start; m.set(k,e); });
|
||
vehRows=[...m.values()].map(v=>({...v,model:lm.get(v.k)||""})).sort((a,b)=>(!b.model-!a.model)||b.km-a.km); // without make/model first, then most km
|
||
if(!vehRows.length){ card.innerHTML=`<div class="empty">Vehicles appear here once trips are added.</div>`; return; }
|
||
const fullRows=vehRows, allVeh=fullRows.length, missing=fullRows.filter(v=>!v.model).length;
|
||
const vq=ci(A.q||"").replace(/[-\s]/g,"");
|
||
if(vq) vehRows=vehRows.filter(v=>ci(v.plate).replace(/[-\s]/g,"").includes(vq)||ci(v.model).replace(/\s/g,"").includes(vq)||ci(countryName(v.country)).includes(vq));
|
||
// a chosen column wins; otherwise vehicles without a make/model first, then most km
|
||
vehRows=sortRows(vehRows,"veh",{plate:v=>v.plate, model:v=>v.model, n:v=>v.n, km:v=>v.km, last:v=>v.last});
|
||
const shownVeh=vehRows.length, LIMIT=25;
|
||
if(!A.all && !vq) vehRows=vehRows.slice(0,LIMIT);
|
||
const tidy=fullRows.map(v=>({from:v.plate,country:v.country,to:formatPlate(v.plate,v.country)})).filter(x=>x.to&&x.to!==x.from);
|
||
const models=[...canonicalNames(trips,x=>normModel(x.model)).values()].sort();
|
||
card.innerHTML=(tidy.length?`<div class="notice" style="margin:12px 16px 0"><p><b>${tidy.length}</b> plate${tidy.length===1?" isn't":"s aren't"} in the standard format, for example ${esc(tidy[0].from)} → ${esc(tidy[0].to)}. Tidying also joins the same car written in different ways.</p><button class="btn" id="tidyPlates">Tidy ${tidy.length} plate${tidy.length===1?"":"s"}</button></div>`:"")+
|
||
`<div class="sumline"><span><b class="num">${allVeh}</b> vehicles${vq?`, <b class="num">${shownVeh}</b> found`:""}</span><span>${missing?`<b>${missing}</b> without make/model`:"All have a make/model"}</span></div>
|
||
<div class="tablewrap"><table><thead><tr>${sortTh("veh","plate","Plate")}${sortTh("veh","model","Make / model")}${sortTh("veh","n","Trips","r")}${sortTh("veh","km","Km","r")}${sortTh("veh","last","Last used")}<th></th></tr></thead><tbody>
|
||
${vehRows.map((v,i)=> A.deleting===v.k ? `<tr class="confirm"><td>${plateHtml(v.plate,v.country,v.region)}</td><td colspan="5">
|
||
<div class="toolbar" style="justify-content:space-between"><span>Delete all <b>${v.n}</b> trip${v.n===1?"":"s"} of ${esc(v.plate)} (${fmtKm(v.km)} km)? This can't be undone.</span>
|
||
<span class="toolbar"><button type="button" class="btn" data-act="cancelDelVeh">Keep them</button><button type="button" class="btn danger" data-act="doDelVeh" data-i="${i}">Delete ${v.n} trip${v.n===1?"":"s"}</button></span></div></td></tr>`
|
||
: A.editing===v.k ? `<tr class="editing"><td>${plateHtml(v.plate,v.country,v.region)}</td><td colspan="5">
|
||
<form class="renamebox" id="vehForm" data-i="${i}"><input class="field" id="vehInput" list="dl-veh-models" value="${esc(v.model)}" placeholder="e.g. Kia Ceed" maxlength="60" autocomplete="off" aria-label="Make and model">
|
||
<button type="button" class="btn" data-act="cancelVeh">Cancel</button><button type="submit" class="btn primary">Save for ${v.n} trip${v.n===1?"":"s"}</button></form>
|
||
<datalist id="dl-veh-models">${models.map(x=>`<option value="${esc(x)}">`).join("")}</datalist></td></tr>`
|
||
: `<tr><td>${plateHtml(v.plate,v.country,v.region)}</td><td>${v.model?esc(v.model):`<span style="color:var(--muted)">Not set</span>`}</td>
|
||
<td class="r num">${v.n}</td><td class="r num km">${fmtKm(v.km)}</td><td class="num" style="color:var(--muted);white-space:nowrap">${fmtDate(v.last)}</td>
|
||
<td class="actions"><button class="btn ghost" data-act="editVeh" data-i="${i}">${v.model?"Edit":"Set make/model"}</button><button class="btn ghost" data-act="delVeh" data-i="${i}">Delete</button></td></tr>`).join("")}
|
||
${!vehRows.length?`<tr><td colspan="6" class="empty">No vehicle matches “${esc(A.q)}”.</td></tr>`:""}
|
||
</tbody></table></div>
|
||
${!vq && allVeh>LIMIT ? `<div class="rankmore" style="padding:0 16px 12px"><span class="num">${A.all?`All ${allVeh}`:`First ${LIMIT} of ${allVeh}`}${ui.tsort.veh?"":" · vehicles without a make/model first"}</span><button class="btn ghost" data-act="vehAll">${A.all?"Show fewer":`Show all ${allVeh}`}</button></div>`:""}`;
|
||
const tb=$("#tidyPlates");
|
||
if(tb) tb.onclick=async()=>{ tb.disabled=true; tb.textContent="Tidying…"; let n=0;
|
||
const ok=await safe(async()=>{ n=await store.renamePlates(tidy); });
|
||
if(ok) toast(`${tidy.length} plate${tidy.length===1?"":"s"} tidied on ${n} trip${n===1?"":"s"}`); else { tb.disabled=false; tb.textContent=`Tidy ${tidy.length} plates`; } };
|
||
const f=$("#vehForm");
|
||
if(f){
|
||
const v=vehRows[+f.dataset.i], inp=$("#vehInput"); inp.focus(); inp.select();
|
||
f.onsubmit=async e=>{ e.preventDefault(); const model=normModel(inp.value);
|
||
let n=0; const ok=await safe(async()=>{ n=await store.setVehicle(v.plate,v.country,{country:v.country,region:v.region,model}); });
|
||
if(ok){ A.editing=null; toast(model?`${v.plate} is now a ${model}`:`Make/model cleared for ${v.plate}`); render(); } };
|
||
}
|
||
}
|
||
function renderAdminLocations(){
|
||
const card=$("#adminCard"), A=ui.admin;
|
||
if(!loaded){ card.innerHTML=`<div class="empty">Loading locations…</div>`; return; }
|
||
const m=new Map();
|
||
trips.forEach(t=>{ const k=t.location||""; const e=m.get(k)||{name:k,n:0,km:0,first:t.start,last:t.start}; e.n++; e.km+=+t.km||0; if(t.start<e.first) e.first=t.start; if(t.start>e.last) e.last=t.start; m.set(k,e); });
|
||
const all=[...m.values()];
|
||
const groups=new Map(); all.forEach(r=>{ if(!r.name) return; const k=locKey(r.name); groups.set(k,[...(groups.get(k)||[]),r.name]); });
|
||
all.forEach(r=>r.similar=r.name?(groups.get(locKey(r.name))||[]).filter(x=>x!==r.name):[]);
|
||
const q=A.q.trim().toLowerCase();
|
||
const dir=A.dir==="asc"?1:-1;
|
||
adminRows=all.filter(r=>!q||r.name.toLowerCase().includes(q)).sort((a,b)=>
|
||
A.sort==="n"?(a.n-b.n)*dir||a.name.localeCompare(b.name):A.sort==="km"?(a.km-b.km)*dir:
|
||
A.sort==="last"?String(a.last||"").localeCompare(String(b.last||""))*dir||a.name.localeCompare(b.name):
|
||
A.sort==="lc"?(countryName(lcOf(a.name)||"~").localeCompare(countryName(lcOf(b.name)||"~")))*dir||a.name.localeCompare(b.name):a.name.localeCompare(b.name)*dir);
|
||
if(!all.length){ card.innerHTML=`<div class="empty"><h2>No locations yet</h2><p>Locations appear here once trips are added.</p></div>`; return; }
|
||
const dupes=all.filter(r=>r.similar.length).length;
|
||
const arrow=k=>A.sort===k?(A.dir==="asc"?" ↑":" ↓"):"";
|
||
const th=(k,l,cls="")=>`<th class="sortable ${cls}" data-asort="${k}" scope="col">${l}${arrow(k)}</th>`;
|
||
card.innerHTML=`<div class="sumline"><span><b class="num">${all.filter(r=>r.name).length}</b> locations${q?`, <b class="num">${adminRows.length}</b> shown`:""}</span><span>${(()=>{ const nc=all.filter(r=>r.name&&!lcOf(r.name)).length; return [nc?`<b>${nc}</b> without a country`:"",dupes?`<b>${dupes}</b> with a near-duplicate name`:""].filter(Boolean).join(" · ")||"All set"; })()}</span></div>
|
||
<div class="tablewrap"><table><thead><tr>${th("name","Location")}${th("n","Trips","r")}${th("km","Km","r")}${th("lc","Country")}${th("last","Used")}<th></th></tr></thead><tbody>
|
||
${adminRows.map((r,i)=>{
|
||
const label=r.name?esc(r.name):`<span style="color:var(--muted)">(no location)</span>`;
|
||
const used=r.first===r.last?fmtDate(r.first):`${fmtDate(r.first)} – ${fmtDate(r.last)}`;
|
||
if(A.editing===r.name) return `<tr class="editing"><td colspan="6">
|
||
<div class="small" style="margin-bottom:6px">${r.name?`Rename “${esc(r.name)}”`:"Set a location"} on ${r.n} trip${r.n===1?"":"s"}</div>
|
||
<form class="renamebox" id="renameForm" data-i="${i}">
|
||
<input class="field" id="renameInput" list="dl-admin-locs" value="${esc(r.name)}" autocomplete="off" aria-label="New location name">
|
||
<button type="button" class="btn" data-act="cancelRename">Cancel</button>
|
||
<button type="submit" class="btn primary" id="renameGo">Rename</button>
|
||
</form>
|
||
<div class="renamehint" id="renameHint"></div>
|
||
<datalist id="dl-admin-locs">${all.filter(x=>x.name&&x.name!==r.name).map(x=>`<option value="${esc(x.name)}">`).join("")}</datalist>
|
||
</td></tr>`;
|
||
return `<tr><td>${label}${r.similar.length?`<span class="similar" title="Same name apart from capitals or spaces: ${esc(r.similar.join(", "))}">similar: ${esc(r.similar.join(", "))}</span>`:""}</td>
|
||
<td class="r num">${r.n}</td><td class="r num km">${fmtKm(r.km)}</td>
|
||
<td>${r.name?`<select class="field lcsel${lcOf(r.name)?"":" unset"}" data-lc="${i}" aria-label="Country of ${esc(r.name)}${lcOf(r.name)?"":" (not set)"}">${countryOptions(lcOf(r.name))}</select>`:""}</td>
|
||
<td class="num" style="color:var(--muted);white-space:nowrap">${used}</td>
|
||
<td class="actions"><button class="btn ghost" data-act="rename" data-i="${i}">${r.name?"Rename":"Set location"}</button></td></tr>`;
|
||
}).join("")||`<tr><td colspan="6" class="empty">No location matches “${esc(A.q)}”.</td></tr>`}
|
||
</tbody></table></div>`;
|
||
card.querySelectorAll("select.lcsel").forEach(sel=>sel.addEventListener("change",async()=>{
|
||
const r=adminRows[+sel.dataset.lc]; sel.disabled=true; sel.classList.toggle("unset",!sel.value);
|
||
const ok=await safe(()=>store.setLocCountry(r.name,sel.value));
|
||
if(ok){ locCountry.set(r.name,sel.value); if(!sel.value) locCountry.delete(r.name); toast(sel.value?`${r.name} is in ${countryName(sel.value)}`:`Country cleared for ${r.name}`); renderAdmin(); return; }
|
||
sel.disabled=false;
|
||
}));
|
||
const inp=$("#renameInput");
|
||
if(inp){
|
||
const row=adminRows[+$("#renameForm").dataset.i];
|
||
const hint=()=>{
|
||
const to=inp.value.trim().replace(/\s+/g," "), go=$("#renameGo"), h=$("#renameHint");
|
||
const target=all.find(x=>x.name===to&&x.name!==row.name);
|
||
go.disabled=!to||to===row.name;
|
||
go.textContent=target?`Merge into “${to}”`:"Rename";
|
||
h.textContent=!to?"Enter a name.":to===row.name?"Type the new name.":target?`${row.n} trip${row.n===1?"":"s"} move to “${to}”, which then has ${row.n+target.n} trips. This can't be undone in one step.`:`${row.n} trip${row.n===1?"":"s"} will be updated.`;
|
||
};
|
||
inp.addEventListener("input",hint); hint(); inp.focus(); inp.select();
|
||
$("#renameForm").onsubmit=async e=>{
|
||
e.preventDefault();
|
||
const to=inp.value.trim().replace(/\s+/g," "); if(!to||to===row.name) return;
|
||
$("#renameGo").disabled=true;
|
||
let n=0; const ok=await safe(async()=>{ n=await store.renameLocation(row.name,to); });
|
||
if(ok){ A.editing=null; toast(`${n} trip${n===1?"":"s"} now at “${to}”`); render(); } else $("#renameGo").disabled=false;
|
||
};
|
||
}
|
||
}
|
||
|
||
/* ---------- add / edit form ---------- */
|
||
function openForm(trip){
|
||
const lt=lastTrip();
|
||
const t=trip||{start:new Date().toISOString().slice(0,10),end:"",plate:lt?.plate||"",country:lt?lt.country:"NL",region:lt?lt.region||"":"",model:lt?latestModels().get(vkey(lt))||"":"",location:"",category:"PNOD",km:""};
|
||
const plates=[...new Set(trips.map(x=>x.plate).filter(Boolean))], locs=[...new Set(trips.map(x=>x.location).filter(Boolean))];
|
||
$("#modalRoot").innerHTML=`<div class="overlay" id="ov"><form class="modal" id="tripForm" novalidate role="dialog" aria-modal="true" aria-labelledby="fh">
|
||
<h2 id="fh">${trip?"Edit trip":"Add trip"}</h2>
|
||
<div class="form">
|
||
<label>Start date<input class="field" type="date" id="f-start" value="${esc(t.start)}" required></label>
|
||
<label>End date<input class="field" type="date" id="f-end" value="${esc(t.end&&t.end!==t.start?t.end:"")}"><span class="small" style="font-weight:400">Leave empty for a one-day trip</span></label>
|
||
<div class="full pair">
|
||
<label>License plate<input class="field" id="f-plate" list="dl-plates" value="${esc(t.plate)}" placeholder="AB-123-C" autocomplete="off" required></label>
|
||
<label>Country<select class="field" id="f-country" style="width:100%">
|
||
<option value="">Unknown</option>
|
||
${COUNTRIES.map(([c,n])=>`<option value="${c}" ${t.country===c?"selected":""}>${esc(n)} (${c})</option>`).join("")}
|
||
<option value="__other" ${t.country&&!COUNTRIES.some(x=>x[0]===t.country)?"selected":""}>Other…</option>
|
||
</select></label>
|
||
</div>
|
||
<label class="full" id="f-otherwrap" hidden>Country code<input class="field" id="f-country-other" value="${esc(t.country&&!COUNTRIES.some(x=>x[0]===t.country)?t.country:"")}" placeholder="e.g. GR" maxlength="3" autocomplete="off"></label>
|
||
<label class="full" id="f-statewrap" hidden>State<select class="field" id="f-state" style="width:100%"><option value="">Choose a state</option>${Object.entries(US_STATES).sort((a,b)=>a[1][0].localeCompare(b[1][0])).map(([k,v])=>`<option value="${k}" ${t.region===k?"selected":""}>${esc(v[0])} (${k})</option>`).join("")}</select></label>
|
||
<label class="full">Make / model <span style="font-weight:400">(optional)</span><input class="field" id="f-model" list="dl-models" value="${esc(t.model||"")}" placeholder="e.g. Kia Ceed" maxlength="60" autocomplete="off"></label>
|
||
<label class="check full" id="f-allwrap" hidden><input type="checkbox" id="f-all"><span id="f-alltext"></span></label>
|
||
<label class="full"><span id="f-distlabel">Distance</span><span class="unitrow"><input class="field num" id="f-km" inputmode="decimal" value="${t.km===""?"":esc(String(t.km).replace(".",","))}" placeholder="0" required aria-describedby="f-conv"><span class="unit" role="group" aria-label="Unit"><button type="button" data-unit="km" aria-pressed="true">km</button><button type="button" data-unit="mi" aria-pressed="false">mi</button></span></span><span class="conv num" id="f-conv"></span></label>
|
||
<div class="full pair">
|
||
<label>Location<input class="field" id="f-loc" list="dl-locs" value="${esc(t.location)}" placeholder="e.g. Rotterdam" autocomplete="off"></label>
|
||
<label>Country of location<select class="field" id="f-loccountry" style="width:100%">${countryOptions(lcOf(t.location))}</select></label>
|
||
</div>
|
||
<p class="small full" id="f-lchint" style="margin-top:-6px" hidden></p>
|
||
<div class="full"><div class="small" style="font-weight:600;margin-bottom:4px">Category</div><div class="seg">${CATS.map(c=>`<label><input type="radio" name="f-cat" id="f-cat-${c.key}" value="${c.key}" ${t.category===c.key?"checked":""}><span class="dot" style="background:${c.color}"></span>${esc(c.label)}</label>`).join("")}</div></div>
|
||
</div>
|
||
<datalist id="dl-plates">${plates.map(p=>`<option value="${esc(p)}">`).join("")}</datalist>
|
||
<datalist id="dl-countries">${COUNTRIES.map(([c,n])=>`<option value="${c}">${n}</option>`).join("")}</datalist>
|
||
<datalist id="dl-models">${[...canonicalNames(trips,x=>normModel(x.model)).values()].sort().map(m=>`<option value="${esc(m)}">`).join("")}</datalist>
|
||
<datalist id="dl-locs">${locs.map(p=>`<option value="${esc(p)}">`).join("")}</datalist>
|
||
<p class="err" id="ferr"></p>
|
||
<div class="actionsrow"><button type="button" class="btn" data-act="close">Cancel</button><button type="submit" class="btn primary">${trip?"Save changes":"Add trip"}</button></div>
|
||
</form></div>`;
|
||
$("#f-km").focus();
|
||
const known=new Map(); trips.forEach(x=>{ if(x.plate) known.set(x.plate.replace(/[-\s]/g,""),[x.country||"",x.region||"",latestModels().get(vkey(x))||""]); });
|
||
let autoModel=trip?null:(t.model||"");
|
||
const getCountry=()=>{ const v=$("#f-country").value; return v==="__other"?normCountry($("#f-country-other").value):v; };
|
||
const putCountry=c=>{ if(!c||COUNTRIES.some(x=>x[0]===c)) $("#f-country").value=c||""; else { $("#f-country").value="__other"; $("#f-country-other").value=c; } };
|
||
const curRegion=()=>getCountry()==="USA"?$("#f-state").value:"";
|
||
/* distance unit: km or miles, converted to km on save */
|
||
let unit="km"; const MI=1.609344;
|
||
function setUnit(u){ unit=u; document.querySelectorAll("[data-unit]").forEach(b=>b.setAttribute("aria-pressed",b.dataset.unit===u)); paintConv(); }
|
||
function paintConv(){
|
||
const v=parseKm($("#f-km").value);
|
||
$("#f-conv").textContent = unit==="mi" ? (v>0?`= ${fmtKm(Math.round(v*MI*10)/10)} km (saved in km)`:"Miles are converted to km when saved") : "";
|
||
}
|
||
document.querySelectorAll("[data-unit]").forEach(b=>b.addEventListener("click",()=>{ setUnit(b.dataset.unit); $("#f-km").focus(); }));
|
||
$("#f-km").addEventListener("input",paintConv);
|
||
$("#f-plate").addEventListener("change",()=>{ const k=known.get(normPlate($("#f-plate").value).replace(/[-\s]/g,"")); const curM=$("#f-model").value.trim(), autoOk=!curM||curM===autoModel; // only replace a model the form filled in itself
|
||
if(k){ putCountry(k[0]); $("#f-state").value=k[1]; if(autoOk){ $("#f-model").value=k[2]; autoModel=k[2]; } }
|
||
else if(autoOk){ $("#f-model").value=""; autoModel=""; } else if(!getCountry()&&looksDutch(normPlate($("#f-plate").value))) putCountry("NL"); syncAll(true); });
|
||
const others=()=>trip?trips.filter(x=>x.id!==trip.id&&x.plate===trip.plate&&(x.country||"")===(trip.country||"")&&(x.region||"")===(trip.region||"")):[];
|
||
let lastC=getCountry();
|
||
function syncAll(countryChanged){
|
||
// New trips: switch to miles for US and UK plates, back to km otherwise
|
||
const cNow=getCountry();
|
||
if(!trip && countryChanged && cNow!==lastC){ setUnit(cNow==="USA"||cNow==="UK"?"mi":"km"); }
|
||
lastC=cNow;
|
||
const c=getCountry(), r=curRegion(), o=others();
|
||
$("#f-statewrap").hidden = c!=="USA";
|
||
$("#f-otherwrap").hidden = $("#f-country").value!=="__other";
|
||
const md=normModel($("#f-model").value), modelChanged=md!==(trip?.model||"");
|
||
const vehChanged=!!trip&&(c!==(trip.country||"")||r!==(trip.region||""));
|
||
const show=!!trip&&o.length>0&&c!==null&&(vehChanged||modelChanged)&&normPlate($("#f-plate").value)===trip.plate;
|
||
$("#f-allwrap").hidden=!show;
|
||
if(show){ const what=[vehChanged?(c?regionLabel(c,r):"no country"):null, modelChanged?(md?`“${md}”`:"an empty make/model"):null].filter(Boolean).join(" and ");
|
||
$("#f-alltext").textContent=`Also set ${what} on the other ${o.length} trip${o.length===1?"":"s"} with ${trip.plate}`; }
|
||
}
|
||
const tidyPlate=()=>{ const v=$("#f-plate").value; if(v.trim()) $("#f-plate").value=formatPlate(v,getCountry()||""); };
|
||
$("#f-plate").addEventListener("blur",tidyPlate);
|
||
// Country of the location: filled in for known locations; changing it applies to every trip there
|
||
const lcHint=()=>{ const l=$("#f-loc").value.trim(), known=locCountry.has(l), c=$("#f-loccountry").value;
|
||
const n=trips.filter(x=>x.location===l&&(!trip||x.id!==trip.id)).length, h=$("#f-lchint");
|
||
h.hidden=!(l&&n&&c!==lcOf(l)); if(!h.hidden) h.textContent=`The country is stored per location, so this also changes it for the other ${n} trip${n===1?"":"s"} to ${l}.`; };
|
||
$("#f-loc").addEventListener("change",()=>{ const l=$("#f-loc").value.trim(); if(locCountry.has(l)) $("#f-loccountry").value=lcOf(l); lcHint(); });
|
||
$("#f-loccountry").addEventListener("change",lcHint);
|
||
$("#f-country").addEventListener("change",()=>{ tidyPlate(); syncAll(true); if($("#f-country").value==="__other") $("#f-country-other").focus(); else if(getCountry()==="USA"&&!$("#f-state").value) $("#f-state").focus(); });
|
||
$("#f-country-other").addEventListener("input",()=>syncAll(true)); $("#f-state").addEventListener("change",()=>syncAll()); $("#f-model").addEventListener("input",()=>syncAll()); syncAll();
|
||
$("#tripForm").onsubmit=async e=>{
|
||
e.preventDefault();
|
||
const start=$("#f-start").value, end=$("#f-end").value||start, km=parseKm($("#f-km").value);
|
||
const plate=formatPlate($("#f-plate").value, getCountry()||"");
|
||
const location=$("#f-loc").value.trim(), category=(document.querySelector('input[name="f-cat"]:checked')||{}).value;
|
||
const err=m=>{ $("#ferr").textContent=m; };
|
||
if(!start) return err("Enter a start date.");
|
||
if(end<start) return err("The end date is before the start date.");
|
||
if(!plate) return err("Enter a license plate.");
|
||
const country=getCountry();
|
||
if(country===null||country===undefined) return err("Enter the country code as 1 to 3 letters, like GR or TR.");
|
||
if(country==="USA"&&!$("#f-state").value) return err("Choose the state for this US plate.");
|
||
if(!(km>0)) return err(`Enter the ${unit==="mi"?"miles":"kilometres"} driven, as a number above 0.`);
|
||
if(!category) return err("Pick a category.");
|
||
const region=country==="USA"?$("#f-state").value:"";
|
||
const kmSaved = unit==="mi" ? Math.round(km*MI*10)/10 : km;
|
||
const model=normModel($("#f-model").value);
|
||
const data={start,end,plate,country,region,model,location,category,km:kmSaved};
|
||
const btn=e.submitter; if(btn){btn.disabled=true;}
|
||
const all=!$("#f-allwrap").hidden&&$("#f-all").checked;
|
||
const lc=$("#f-loccountry").value, lcChanged=location && lc!==lcOf(location);
|
||
if(lcChanged){ const ok1=await safe(()=>store.setLocCountry(location,lc)); if(!ok1){ if(btn) btn.disabled=false; return; } }
|
||
const ok = trip ? await safe(async()=>{ if(all) await store.setVehicle(trip.plate,trip.country||"",{country,region,model}); await store.update(trip.id,data); }, all?"Trip and vehicle saved":"Trip saved")
|
||
: await safe(()=>store.add(data),"Trip added");
|
||
if(ok){ closeModal(); if(unit==="mi") toast(`${fmtKm(km)} mi saved as ${fmtKm(kmSaved)} km`); } else if(btn) btn.disabled=false;
|
||
};
|
||
}
|
||
function lastTrip(){ return [...trips].sort((a,b)=>(+b.id||0)-(+a.id||0))[0]; }
|
||
function closeModal(){ $("#modalRoot").innerHTML=""; }
|
||
|
||
/* ---------- import ---------- */
|
||
function openImport(){
|
||
$("#modalRoot").innerHTML=`<div class="overlay" id="ov"><div class="modal" role="dialog" aria-modal="true" aria-labelledby="ih">
|
||
<h2 id="ih">Import from Excel</h2>
|
||
<p class="small">In Excel, select your rows including the header row, copy them, and paste below. You can also choose a CSV file saved from Excel. Columns are matched by their header: kilometres (or miles), start, end, license plate, country, US state and make/model (all optional), location and category. Without a country column, Dutch-looking plates get NL.</p>
|
||
<textarea class="field" id="imp-text" placeholder="km	start	end	licenseplate	location	category 212	14-10-2026	14-10-2026	AB-123-C	Utrecht	${esc(CATS[0].label)}"></textarea>
|
||
<div class="toolbar"><label class="btn" for="imp-file">Choose CSV file</label><input type="file" id="imp-file" accept=".csv,.txt,.tsv,text/csv" hidden><span class="small" id="imp-fname"></span></div>
|
||
<div id="imp-prev"></div>
|
||
<div class="actionsrow"><button class="btn" data-act="close">Cancel</button><button class="btn primary" id="imp-go" disabled>Import</button></div>
|
||
</div></div>`;
|
||
let parsed=null;
|
||
const update=()=>{ parsed=analyse($("#imp-text").value); renderPreview(parsed); };
|
||
$("#imp-text").addEventListener("input",update);
|
||
$("#imp-file").addEventListener("change",e=>{
|
||
const f=e.target.files[0]; if(!f) return;
|
||
$("#imp-fname").textContent=f.name;
|
||
const r=new FileReader(); r.onload=()=>{ $("#imp-text").value=r.result; update(); }; r.readAsText(f);
|
||
});
|
||
$("#imp-go").onclick=async()=>{
|
||
if(!parsed) return;
|
||
const list=[...parsed.ok, ...(($("#imp-dupes")||{}).checked ? parsed.dupes.map(d=>d.trip) : [])];
|
||
if(!list.length) return;
|
||
const go=$("#imp-go"); go.disabled=true;
|
||
go.textContent=`Importing ${list.length} trips…`;
|
||
let done=0;
|
||
const ok=await safe(async()=>{ done=await store.addMany(list); });
|
||
if(!ok){ go.disabled=false; go.textContent="Import"; return; }
|
||
closeModal(); toast(`${done} trip${done===1?"":"s"} imported`);
|
||
};
|
||
}
|
||
function renderPreview(p){
|
||
const el=$("#imp-prev"), go=$("#imp-go");
|
||
if(!p){ el.innerHTML=""; go.disabled=true; go.textContent="Import"; return; }
|
||
const names={miles:"Miles",km:"Kilometres",start:"Start",end:"End",plate:"License plate",country:"Country",region:"State",model:"Make/model",location:"Location",category:"Category"};
|
||
const found=Object.keys(names).filter(k=>p.map[k]!==undefined).map(k=>names[k]);
|
||
const missing=["km","start","plate","category"].filter(k=>p.map[k]===undefined&&!(k==="km"&&p.map.miles!==undefined)).map(k=>names[k]);
|
||
el.innerHTML=`<div class="preview">
|
||
<div>${p.header?`Columns recognised: <b>${found.join(", ")||"none"}</b>`:"No header row found, so columns are read in this order: km, start, end, plate, location, category, country."}</div>
|
||
${missing.length&&p.header?`<div style="color:var(--danger)">Missing columns: ${missing.join(", ")}. Check the header row.</div>`:""}
|
||
${p.converted?`<div><b class="num">${p.converted}</b> distance${p.converted===1?"":"s"} in miles, converted to km.</div>`:""}
|
||
<div><b class="num">${p.ok.length}</b> new trip${p.ok.length===1?"":"s"} ready to import${p.skipped.length?`, <b class="num">${p.skipped.length}</b> row${p.skipped.length===1?"":"s"} not understood`:""}.</div>
|
||
${p.dupes.length?`<div class="dupebox"><div><b class="num">${p.dupes.length}</b> row${p.dupes.length===1?" is":"s are"} the same as a trip already in the log (same dates, plate, kilometres and location), so ${p.dupes.length===1?"it is":"they are"} left out:</div>
|
||
<ul>${p.dupes.slice(0,5).map(d=>`<li>Row ${d.row}: ${fmtDate(d.trip.start)}, ${esc(d.trip.plate)}, ${fmtKm(d.trip.km)} km${d.trip.location?", "+esc(d.trip.location):""}</li>`).join("")}${p.dupes.length>5?`<li>…and ${p.dupes.length-5} more</li>`:""}</ul>
|
||
<label class="check"><input type="checkbox" id="imp-dupes"> Import ${p.dupes.length===1?"it":"these"} anyway (for example when you drove the same trip twice)</label></div>`:""}
|
||
${p.unknown.length?`<div>Country unknown for ${p.unknown.length} foreign-looking plate${p.unknown.length===1?"":"s"} (${esc(p.unknown.slice(0,5).join(", "))}${p.unknown.length>5?", …":""}). They get a grey “?” band. Edit one trip per plate afterwards and tick “also set on the other trips”, or add a country column before importing.</div>`:""}
|
||
${p.skipped.length?`<ul>${p.skipped.slice(0,6).map(s=>`<li>Row ${s.row}: ${esc(s.why)}</li>`).join("")}${p.skipped.length>6?`<li>…and ${p.skipped.length-6} more</li>`:""}</ul>`:""}
|
||
</div>`;
|
||
const count=()=>p.ok.length+(($("#imp-dupes")||{}).checked?p.dupes.length:0);
|
||
const paintGo=()=>{ const n=count(); go.disabled=!n; go.textContent=n?`Import ${n} trip${n===1?"":"s"}`:"Import"; };
|
||
const cb=$("#imp-dupes"); if(cb) cb.addEventListener("change",paintGo);
|
||
paintGo();
|
||
}
|
||
function splitRows(text){
|
||
const first=text.split(/\r?\n/)[0]||"";
|
||
const delim = first.includes("\t")?"\t" : ((first.match(/;/g)||[]).length>=(first.match(/,/g)||[]).length?";":",");
|
||
const rows=[]; let row=[], cell="", q=false;
|
||
for(let i=0;i<text.length;i++){
|
||
const c=text[i];
|
||
if(q){ if(c==='"'){ if(text[i+1]==='"'){cell+='"';i++;} else q=false; } else cell+=c; continue; }
|
||
if(c==='"'&&cell==="") q=true;
|
||
else if(c===delim){ row.push(cell); cell=""; }
|
||
else if(c==="\n"||c==="\r"){ if(c==="\r"&&text[i+1]==="\n") i++; row.push(cell); rows.push(row); row=[]; cell=""; }
|
||
else cell+=c;
|
||
}
|
||
if(cell!==""||row.length){ row.push(cell); rows.push(row); }
|
||
return rows.filter(r=>r.some(c=>c.trim()!==""));
|
||
}
|
||
function analyse(text){
|
||
if(!text.trim()) return null;
|
||
const rows=splitRows(text.replace(/^/,""));
|
||
if(!rows.length) return null;
|
||
const tests=[["miles",/^mi$|^miles?\b|mijl/],["km",/^km$|kilomet|distance|afstand|gereden/],["start",/start|begin|vertrek/],["end",/end|eind|terug/],["country",/countr|^land|nation/],["region",/^state|^region|^staat|^us.?state/],["model",/model|make|merk|^car\b|^auto\b|vehicle|voertuig/],["plate",/plate|kenteken|licen[cs]e|registration/],["location",/locat|plaats|bestemming|place|adres/],["category",/categ|type|soort|doel/]];
|
||
const head=rows[0].map(c=>c.trim().toLowerCase());
|
||
const map={}; let header=false;
|
||
head.forEach((h,i)=>{ for(const [k,re] of tests){ if(map[k]===undefined && re.test(h)){ map[k]=i; header=true; break; } } });
|
||
if(!header){ ["km","start","end","plate","location","category","country","region"].forEach((k,i)=>map[k]=i); }
|
||
// Trips already in the log, counted per key: each one can "use up" one matching row in the file.
|
||
// Rows in the file are never compared with each other: a car's own export has many identical-looking
|
||
// rows (the trip to work and back on the same day), and those are all real trips.
|
||
const inLog=new Map(); trips.forEach(t=>{ const k=keyOf(t); inLog.set(k,(inLog.get(k)||0)+1); });
|
||
const dupes=[];
|
||
const knownCountry=new Map(); trips.forEach(x=>{ if(x.plate&&x.country) knownCountry.set(x.plate.replace(/[-\s]/g,""),[x.country,x.region||""]); });
|
||
const unknown=new Set(); let converted=0;
|
||
const lm=latestModels(), knownModel=new Map(); trips.forEach(x=>{ const md=lm.get(vkey(x)); if(md) knownModel.set(x.plate.replace(/[-\s]/g,""),md); });
|
||
const ok=[], skipped=[];
|
||
rows.slice(header?1:0).forEach((r,idx)=>{
|
||
const n=idx+(header?2:1), get=k=>map[k]===undefined?"":(r[map[k]]??"").trim();
|
||
const start=parseDate(get("start")); if(!start) return skipped.push({row:n,why:`start date “${get("start")}” not understood`});
|
||
const end=get("end")?parseDate(get("end")):start; if(!end) return skipped.push({row:n,why:`end date “${get("end")}” not understood`});
|
||
// Distance: a km column, a miles column, or a value with "mi"/"miles" after it. Miles become km.
|
||
const rawKm=get("km"), rawMi=get("miles");
|
||
let km;
|
||
if(rawKm && /\d\s*(mi|miles?|mijl)\.?$/i.test(rawKm)){ const v=parseKm(rawKm.replace(/(mi|miles?|mijl)\.?$/i,"")); km=v>0?Math.round(v*1.609344*10)/10:NaN; if(km>0) converted++; }
|
||
else if(!rawKm && rawMi){ const v=parseKm(rawMi); km=v>0?Math.round(v*1.609344*10)/10:NaN; if(km>0) converted++; }
|
||
else km=parseKm(rawKm);
|
||
if(!(km>0)) return skipped.push({row:n,why:`distance “${rawKm||rawMi}” is not a number above 0`});
|
||
const category=normCat(get("category")); if(!category) return skipped.push({row:n,why:`category “${get("category")}” is not ${CATS.map(c=>c.label).join(", ").replace(/, ([^,]*)$/," or $1")}`});
|
||
const plate=normPlate(get("plate"));
|
||
if(!plate) return skipped.push({row:n,why:"no license plate"});
|
||
let country, region="";
|
||
if(map.country!==undefined&&get("country")){
|
||
const cr=parseCountryCell(get("country")); if(!cr) return skipped.push({row:n,why:`country “${get("country")}” not understood`});
|
||
[country,region]=cr;
|
||
} else [country,region] = knownCountry.get(plate.replace(/[-\s]/g,"")) ?? [looksDutch(plate)?"NL":"",""];
|
||
if(map.region!==undefined&&get("region")){ const st=normState(get("region")); if(st===null) return skipped.push({row:n,why:`state “${get("region")}” not understood`}); if(st){ region=st; country="USA"; } }
|
||
if(country!=="USA") region="";
|
||
if(!country) unknown.add(plate);
|
||
const fplate=formatPlate(plate,country);
|
||
const model=normModel(get("model")) || knownModel.get(plate.replace(/[-\s]/g,"")) || "";
|
||
const t={km,start,end:end<start?start:end,plate:fplate,country,region,model,location:get("location"),category};
|
||
const k=keyOf(t), left=inLog.get(k)||0;
|
||
if(left>0){ inLog.set(k,left-1); dupes.push({row:n,trip:t}); return; }
|
||
ok.push(t);
|
||
});
|
||
return {header,map,ok,skipped,dupes,unknown:[...unknown],converted};
|
||
}
|
||
/* "USA - California", "US/CA", "California" or plain country codes */
|
||
function parseCountryCell(v){
|
||
const byName=STATE_BY_NAME[String(v).trim().toUpperCase()]; if(byName) return ["USA",byName]; // full state names only: "DE" stays Germany
|
||
const m=String(v).trim().toUpperCase().match(/^(USA?|UNITED STATES|AMERICA)\s*[-\/,·:\s]\s*(.+)$/);
|
||
if(m){ const s2=normState(m[2]); return s2?["USA",s2]:null; }
|
||
const c=normCountry(v); return c===null?null:[c,""];
|
||
}
|
||
const keyOf=t=>[t.start,t.end||t.start,(t.plate||"").replace(/[-\s]/g,""),t.country||"",t.region||"",+t.km,(t.location||"").toLowerCase()].join("|");
|
||
function parseKm(s){
|
||
s=String(s??"").replace(/\s|km/gi,""); if(!s) return NaN;
|
||
if(s.includes(".")&&s.includes(",")) s=s.replace(/\./g,"").replace(",",".");
|
||
else if(s.includes(",")) s=s.replace(",",".");
|
||
else if(/^\d{1,3}(\.\d{3})+$/.test(s)) s=s.replace(/\./g,"");
|
||
const n=parseFloat(s); return isNaN(n)?NaN:Math.round(n*10)/10;
|
||
}
|
||
/* Month names in Dutch and English, full or abbreviated: jan, feb, mrt/mar/maa, mei/may, okt/oct, ... */
|
||
const MONTH_PREFIX={jan:1,feb:2,mrt:3,mar:3,maa:3,apr:4,mei:5,may:5,jun:6,jul:7,aug:8,sep:9,okt:10,oct:10,nov:11,dec:12};
|
||
function monthFromName(w){ w=String(w).toLowerCase().replace(/\.$/,""); return MONTH_PREFIX[w.slice(0,3)]||null; }
|
||
function parseDate(s){
|
||
s=String(s||"").trim().replace(/\s+\d{1,2}:\d{2}(:\d{2})?$/,""); // drop a trailing time
|
||
s=s.replace(/^([a-z]{2,9})\.?,?\s+(?=\d)/i,(w,word)=>monthFromName(word)?w:""); // drop a leading weekday ("di 09-jan-24"), keep "jan 9, 2024"
|
||
if(!s) return null;
|
||
let y,m,d,x;
|
||
const fullYear=v=>{ v=+v; return v<100?2000+v:v; };
|
||
if((x=s.match(/^(\d{4})[-\/.](\d{1,2})[-\/.](\d{1,2})/))) [y,m,d]=[+x[1],+x[2],+x[3]];
|
||
else if((x=s.match(/^(\d{1,2})[-\/.](\d{1,2})[-\/.](\d{2}|\d{4})$/))) [d,m,y]=[+x[1],+x[2],fullYear(x[3])];
|
||
else if(/^\d{5}(\.\d+)?$/.test(s)){ const dt=new Date(Date.UTC(1899,11,30)+Math.floor(+s)*864e5); return dt.toISOString().slice(0,10); }
|
||
else if((x=s.match(/^(\d{1,2})[\s\-\/.]+([a-z]{3,10})\.?[\s\-\/.,]+(\d{2}|\d{4})$/i))){ m=monthFromName(x[2]); if(!m) return null; [d,y]=[+x[1],fullYear(x[3])]; } // 09-jan-24, 9 januari 2024, 9.okt.2024
|
||
else if((x=s.match(/^([a-z]{3,10})\.?[\s\-\/]+(\d{1,2}),?[\s\-\/]+(\d{2}|\d{4})$/i))){ m=monthFromName(x[1]); if(!m) return null; [d,y]=[+x[2],fullYear(x[3])]; } // jan 9, 2024
|
||
else return null;
|
||
if(m<1||m>12||d<1) return null;
|
||
const dt=new Date(Date.UTC(y,m-1,d)); if(dt.getUTCMonth()!==m-1) return null; // rejects 31-feb
|
||
return `${y}-${String(m).padStart(2,"0")}-${String(d).padStart(2,"0")}`;
|
||
}
|
||
function normCat(s){ s=String(s||"").trim().toLowerCase();
|
||
const byLabel=CATS.find(c=>c.label.toLowerCase()===s); if(byLabel) return byLabel.key; // e.g. "PNOD" or your own name
|
||
if(/^(business|zakelijk|work|werk)/.test(s)) return "PNOD"; if(s==="pnod") return "PNOD"; if(/^(hire|huur|verhuur|rental)/.test(s)) return "hire"; if(/^(personal|priv[eé]|private|eigen)/.test(s)) return "personal"; return null; }
|
||
function normPlate(s){ return String(s||"").trim().toUpperCase().replace(/\s+/g," "); }
|
||
/* Plate formatting per country. Only countries with one clear standard pattern are reformatted;
|
||
anything that doesn't match is kept as typed (upper-case, single spaces). */
|
||
function formatPlate(plate,country){
|
||
const typed=String(plate||"").trim().toUpperCase().replace(/\s+/g," ");
|
||
const raw=typed.replace(/[\s\-.·]/g,"");
|
||
if(!raw) return "";
|
||
let m;
|
||
switch(country){
|
||
case "NL": {
|
||
if(!/^[A-Z0-9]{6}$/.test(raw)) return typed;
|
||
// Split where letters and digits alternate; a 4-long block of one kind is two 2-blocks (sidecodes 1-6).
|
||
let groups=raw.match(/[A-Z]+|[0-9]+/g);
|
||
if(groups.length===2) groups=groups.flatMap(g=>g.length===4?[g.slice(0,2),g.slice(2)]:[g]);
|
||
if(groups.length===3 && groups.every(g=>g.length<=3)) return groups.join("-");
|
||
return typed;
|
||
}
|
||
case "B": if((m=raw.match(/^(\d)([A-Z]{3})(\d{3})$/))) return m.slice(1).join("-"); // 1-ABC-234
|
||
if((m=raw.match(/^([A-Z]{3})(\d{3})$/))) return m.slice(1).join("-"); // ABC-123 (older)
|
||
return typed;
|
||
case "F": if((m=raw.match(/^([A-Z]{2})(\d{3})([A-Z]{2})$/))) return m.slice(1).join("-"); return typed; // AB-123-CD
|
||
case "I": if((m=raw.match(/^([A-Z]{2})(\d{3})([A-Z]{2})$/))) return m.slice(1).join(" "); return typed; // AB 123 CD
|
||
case "E": if((m=raw.match(/^(\d{4})([A-Z]{3})$/))) return m.slice(1).join(" "); return typed; // 1234 ABC
|
||
case "P": if((m=raw.match(/^([A-Z0-9]{2})([A-Z0-9]{2})([A-Z0-9]{2})$/))) return m.slice(1).join("-"); return typed; // AA-00-AA
|
||
case "UK": if((m=raw.match(/^([A-Z]{2}\d{2})([A-Z]{3})$/))) return m.slice(1).join(" "); return typed; // AB12 CDE
|
||
case "N": if((m=raw.match(/^([A-Z]{2})(\d{4,5})$/))) return m.slice(1).join(" "); return typed; // EV 41827
|
||
case "CH": if((m=raw.match(/^([A-Z]{2})(\d{1,6})$/))) return m.slice(1).join(" "); return typed; // ZH 123456
|
||
case "S": if((m=raw.match(/^([A-Z]{3})(\d{2}[A-Z0-9])$/))) return m.slice(1).join(" "); return typed; // ABC 12D
|
||
default: return typed; // D, SLO, USA and others: too many local variants, keep as typed
|
||
}
|
||
}
|
||
|
||
/* ---------- export ---------- */
|
||
async function exportCsv(){
|
||
const list=filtered().slice().sort((a,b)=>String(a.start).localeCompare(String(b.start)));
|
||
const q=v=>{ v=String(v??""); return /[;"\n]/.test(v)?`"${v.replace(/"/g,'""')}"`:v; };
|
||
const csv="km;start;end;licenseplate;country;state;makemodel;location;locationcountry;category\n"+list.map(t=>[String(t.km).replace(".",","),fmtNl(t.start),fmtNl(t.end||t.start),t.plate,t.country||"",t.region||"",t.model||"",t.location,lcOf(t.location),(CAT[t.category]||{label:t.category}).label].map(q).join(";")).join("\n");
|
||
const url=URL.createObjectURL(new Blob([csv],{type:"text/csv;charset=utf-8"}));
|
||
const link=document.createElement("a"); link.href=url; link.download=`kilometer-log-${new Date().toISOString().slice(0,10)}.csv`;
|
||
document.body.appendChild(link); link.click(); link.remove(); setTimeout(()=>URL.revokeObjectURL(url),1000);
|
||
}
|
||
const fmtNl=iso=>{ if(!iso) return ""; const [y,m,d]=iso.split("-"); return `${d}-${m}-${y}`; };
|
||
|
||
/* ---------- theme ---------- */
|
||
const SUN='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>';
|
||
const MOON='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg>';
|
||
function paintThemeBtn(){
|
||
const dark=document.documentElement.getAttribute("data-theme")!=="light";
|
||
const b=$("#themeBtn"); b.innerHTML=dark?SUN:MOON;
|
||
b.setAttribute("aria-label",dark?"Switch to light mode":"Switch to dark mode"); b.title=b.getAttribute("aria-label");
|
||
}
|
||
$("#themeBtn").addEventListener("click",()=>{
|
||
const next=document.documentElement.getAttribute("data-theme")==="light"?"dark":"light";
|
||
document.documentElement.setAttribute("data-theme",next);
|
||
try{ localStorage.setItem("kmlog-theme",next); }catch(e){}
|
||
paintThemeBtn();
|
||
});
|
||
paintThemeBtn();
|
||
|
||
/* ---------- events ---------- */
|
||
document.addEventListener("click",async e=>{
|
||
const b=e.target.closest("button,[data-act],th[data-sort],th[data-asort],th[data-rsort],th[data-tsort]"); if(!b) { if(e.target.id==="ov") closeModal(); return; }
|
||
if(b.dataset.atab){ ui.adminTab=b.dataset.atab; try{ localStorage.setItem("kmlog-admintab",ui.adminTab); }catch(_){} renderAdmin(); return; }
|
||
if(b.dataset.clear){ clearSearch(b.dataset.clear); return; }
|
||
if(b.dataset.view){ if(b.dataset.view==="admin") haStatus=null; ui.view=b.dataset.view; try{ history.replaceState(null,"","#"+ui.view);}catch(_){}; render(); return; }
|
||
if(b.dataset.fcat){ ui[b.dataset.scope].cat=b.dataset.fcat; render(); return; }
|
||
if(b.dataset.rsort){ const p=b.dataset.panel, k=b.dataset.rsort, cur=ui.rankSort[p]||{key:"km",dir:"desc"};
|
||
ui.rankSort[p] = cur.key===k ? {key:k,dir:cur.dir==="asc"?"desc":"asc"} : {key:k,dir:k==="name"?"asc":"desc"}; renderStats(); return; }
|
||
if(b.dataset.tsort){ const [t,k]=b.dataset.tsort.split(":"), cur=ui.tsort[t]||{};
|
||
const textual=["plate","model","event"].includes(k);
|
||
ui.tsort[t] = cur.key===k ? {key:k,dir:cur.dir==="asc"?"desc":"asc"} : {key:k,dir:textual?"asc":"desc"}; renderAdmin(); return; }
|
||
if(b.dataset.asort){ const k=b.dataset.asort, A=ui.admin; A.dir=A.sort===k?(A.dir==="asc"?"desc":"asc"):(k==="name"?"asc":"desc"); A.sort=k; render(); return; }
|
||
if(b.dataset.sort){ const k=b.dataset.sort; ui.dir = ui.sort===k ? (ui.dir==="asc"?"desc":"asc") : (k==="start"||k==="end"||k==="km"?"desc":"asc"); ui.sort=k; render(); return; }
|
||
const id=b.dataset.id;
|
||
switch(b.dataset.act||b.id){
|
||
case "addBtn": case "add": openForm(); break;
|
||
case "importBtn": case "import": openImport(); break;
|
||
case "exportBtn": exportCsv(); break;
|
||
case "edit": openForm(trips.find(t=>t.id===id)); break;
|
||
case "del": ui.confirmId=id; render(); break;
|
||
case "cancelDel": ui.confirmId=null; render(); break;
|
||
case "doDel": ui.confirmId=null; await safe(()=>store.remove(id),"Trip deleted"); break;
|
||
case "close": closeModal(); break;
|
||
case "expand": { const p=b.dataset.panel; ui.expanded.has(p)?ui.expanded.delete(p):ui.expanded.add(p); renderStats(); break; }
|
||
case "rename": ui.admin.editing=adminRows[+b.dataset.i].name; render(); break;
|
||
case "cancelRename": ui.admin.editing=null; render(); break;
|
||
case "editVeh": ui.adminV.deleting=null; ui.adminV.editing=vehRows[+b.dataset.i].k; render(); break;
|
||
case "delVeh": ui.adminV.editing=null; ui.adminV.deleting=vehRows[+b.dataset.i].k; render(); break;
|
||
case "haForget": { const v={plate:b.dataset.plate}; if(await safe(()=>api("DELETE","ha/odometer/"+encodeURIComponent(v.plate)),`${v.plate}: the next reading becomes the new starting point`)){ haStatus=null; renderAdminHa(); } break; }
|
||
case "vehAll": ui.adminV.all=!ui.adminV.all; renderAdminVehicles(); break;
|
||
case "cancelDelVeh": ui.adminV.deleting=null; render(); break;
|
||
case "doDelVeh": { const v=vehRows[+b.dataset.i]; b.disabled=true; let n=0;
|
||
const ok=await safe(async()=>{ n=await store.deleteVehicle(v.plate,v.country,v.region); });
|
||
if(ok){ ui.adminV.deleting=null; toast(`${n} trip${n===1?"":"s"} of ${v.plate} deleted`); render(); } else b.disabled=false; break; }
|
||
case "cancelVeh": ui.adminV.editing=null; render(); break;
|
||
case "reset": { const f=ui[b.dataset.scope]; f.cat=f.veh=f.loc=f.car="all"; if(b.dataset.scope==="t"){ f.year="all"; ui.q=""; $("#q").value=""; } render(); break; }
|
||
}
|
||
});
|
||
document.addEventListener("keydown",e=>{
|
||
const a=document.activeElement;
|
||
if(e.key==="Escape" && a && a.type==="search" && a.value){ e.preventDefault(); clearSearch(a.id); return; } // Esc clears a filled search field
|
||
if(e.key==="Escape"){ if($("#modalRoot").innerHTML) closeModal(); else if(ui.admin.editing!==null){ ui.admin.editing=null; render(); } else if(ui.confirmId){ ui.confirmId=null; render(); } } });
|
||
$("#vehQ").addEventListener("input",e=>{ ui.adminV.q=e.target.value; ui.adminV.editing=ui.adminV.deleting=null; syncClearButtons(); renderAdminVehicles(); });
|
||
$("#adminQ").addEventListener("input",e=>{ ui.admin.q=e.target.value; ui.admin.editing=null; syncClearButtons(); renderAdminLocations(); });
|
||
$("#q").addEventListener("input",e=>{ ui.q=e.target.value; syncClearButtons(); renderTrips(); });
|
||
document.addEventListener("change",e=>{ const el=e.target; if(el.dataset&&el.dataset.f){ ui[el.dataset.scope][el.dataset.f]=el.value; render(); } });
|
||
|
||
const h=(location.hash||"").slice(1); if(h==="stats"||h==="trips"||h==="admin") ui.view=h;
|
||
boot();
|
||
})();
|
||
</script>
|
||
|
||
</body>
|
||
</html>
|