feat(orchestrator): export and import the accounts as CSV or TSV

Requirement 065. GET /api/accounts/export?format=csv|tsv answers the
accounts as an attachment, one header line and one line per account,
with spreadsheet formulas guarded. POST /api/accounts/import/preview
parses an uploaded file (base64, size and row limits, UTF-8 with an
optional byte order mark), detects or takes the separator, maps the
columns by header or by the operator's mapping and marks each row new,
update, unchanged or error. POST /api/accounts/import/apply writes the
previewed rows in one Ledger.batch, keep or overwrite per conflicting
email, and refuses when the ledger digest changed since the preview.
The Accounts page gains export links, the file picker, the mapping
sheet and the per-conflict choice.

🎯 Fix: 88 %
💥 Break: 5 %
💸 Tokens: 100 %
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 84
🚦 Gate: ⛔ fix 88 % < 90 (E2E spec not run yet): operator approved the commit

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-27 10:45:25 +00:00
1 parent 30862411f3
commit 5c969be21c
6 files changed
+809 -6

No files matched your search

@@ -0,0 +1,359 @@
from __future__ import annotations
import base64
import binascii
import csv
import datetime
import hashlib
import io
import json
import re
from .accounts import KEYS, valid_account
from .errors import Conflict, ToolError
from .fields import decode
from .ledger import Ledger
from .settings import section
FORMATS = {"csv": (",", "text/csv; charset=utf-8"), "tsv": ("\t", "text/tab-separated-values; charset=utf-8")}
SEPARATORS = (",", ";", "\t")
HEADER = ("provider", "email", "renewal_day", "renewal_time", "reset_day", "reset_time", "resubscribe", "autorenew", "limit", "note")
MAPPED = ("provider", "email", "renewal", "renewal_day", "renewal_time", "reset", "reset_day", "reset_time", "resubscribe", "autorenew", "limit", "note")
LABELS = {"provider": "Provider", "email": "Email", "renewal": "Renewal", "reset": "Next reset", "resubscribe": "Resubscribe", "autorenew": "Autorenew", "limit": "Weekly token limit", "note": "Note"}
MOMENTS = ("renewal", "reset")
REQUIRED = ("provider", "email", *MOMENTS)
SHORT_DAYS = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
DAY_WORDS = (
("sun", "sunday", "so", "sonntag"),
("mon", "monday", "mo", "montag"),
("tue", "tuesday", "di", "dienstag"),
("wed", "wednesday", "mi", "mittwoch"),
("thu", "thursday", "do", "donnerstag"),
("fri", "friday", "fr", "freitag"),
("sat", "saturday", "sa", "samstag"),
)
WEEKDAYS = {word: index for index, words in enumerate(DAY_WORDS) for word in (*words, str(index))}
YES = ("yes", "true", "1", "ja")
NO = ("no", "false", "0", "nein", "")
CLOCK = re.compile(r"([0-9]{1,2}):([0-5][0-9])")
WHOLE = re.compile(r"[0-9]{1,16}")
INJECTION = ("=", "+", "-", "@", "\t", "\r")
GUARD = "'"
FILE_LIMIT = 256 << 10
ROW_LIMIT = 500
CHOICES = ("overwrite", "keep")
PREVIEW_KEYS = ("file", "separator", "mapping", "choices")
APPLY_KEYS = (*PREVIEW_KEYS, "digest")
DIGEST_LENGTH = 32
def guarded(value: str) -> str:
return f"{GUARD}{value}" if value.startswith(INJECTION) else value
def unguarded(value: str) -> str:
return value[1:] if value.startswith(GUARD) and value[1:].startswith(INJECTION) else value
def exported_row(account: dict) -> list[str]:
limit = "" if account["limit"] is None else str(account["limit"])
cells = [account["provider"], account["email"]]
for name in MOMENTS:
cells += [SHORT_DAYS[account[name]["day"]], account[name]["time"]]
cells += [account["resubscribe"], "yes" if account["autorenew"] else "no", limit, account["note"]]
return [guarded(cell) for cell in cells]
def export(accounts: list[dict], fmt: str) -> tuple[str, bytes]:
"""Args:
accounts: the stored accounts in table order.
fmt: csv or tsv; anything else raises ToolError.
Returns:
(content type, file bytes): HEADER and one line per account, every
cell starting with a formula character prefixed with a quote.
"""
if fmt not in FORMATS:
raise ToolError(f"format must be one of {', '.join(FORMATS)}")
separator, content_type = FORMATS[fmt]
out = io.StringIO()
writer = csv.writer(out, delimiter=separator, lineterminator="\r\n")
writer.writerow(HEADER)
writer.writerows(exported_row(account) for account in accounts)
return content_type, out.getvalue().encode("utf-8")
def file_text(encoded: object) -> str:
"""Returns:
The file's text without a leading byte order mark; a file that is no
base64, over FILE_LIMIT or not UTF-8 raises ToolError.
"""
if not isinstance(encoded, str):
raise ToolError("file must be the file's bytes in base64")
try:
data = base64.b64decode(encoded, validate=True)
except (binascii.Error, ValueError):
raise ToolError("file must be the file's bytes in base64") from None
if len(data) > FILE_LIMIT:
raise ToolError(f"the file is larger than {FILE_LIMIT >> 10} KiB")
try:
return data.decode("utf-8-sig")
except UnicodeDecodeError:
raise ToolError("the file is not UTF-8 text") from None
def detected(text: str) -> str:
first = text.split("\n", 1)[0]
counts = {separator: first.count(separator) for separator in SEPARATORS}
best = max(SEPARATORS, key=lambda separator: counts[separator])
return best if counts[best] else ","
def separator_of(requested: object, text: str) -> str:
if requested == "":
return detected(text)
if requested not in SEPARATORS:
raise ToolError("separator must be empty, a comma, a semicolon or a tab")
return requested
def table(text: str, separator: str) -> tuple[list[str], list[list[str]]]:
"""Returns:
(header, rows): the first line and every non-empty line after it;
more than ROW_LIMIT rows or broken quoting raises ToolError.
"""
try:
lines = [row for row in csv.reader(io.StringIO(text, newline=""), delimiter=separator) if any(cell.strip() for cell in row)]
except csv.Error as error:
raise ToolError(f"the file is no valid table: {error}") from None
if not lines:
raise ToolError("the file has no header line")
if len(lines) - 1 > ROW_LIMIT:
raise ToolError(f"the file has more than {ROW_LIMIT} rows")
return [cell.strip() for cell in lines[0]], lines[1:]
def proposed(columns: list[str]) -> dict[str, int | None]:
"""Returns:
Per field of MAPPED the first column whose header equals the field
name or its table label, ignoring case, else None.
"""
lowered = [column.lower() for column in columns]
found: dict[str, int | None] = {}
for name in MAPPED:
names = {name, LABELS.get(name, name).lower()}
found[name] = next((index for index, column in enumerate(lowered) if column in names), None)
return found
def requested_mapping(raw: object, columns: list[str]) -> dict[str, int | None]:
if raw is None:
return proposed(columns)
data = section(raw, "mapping", MAPPED)
for name, index in data.items():
if index is not None and (isinstance(index, bool) or not isinstance(index, int) or not 0 <= index < len(columns)):
raise ToolError(f"mapping.{name} must be a column number from 0 to {len(columns) - 1} or null")
return data
def missing(mapping: dict[str, int | None]) -> list[str]:
absent = [name for name in ("provider", "email") if mapping[name] is None]
split = [name for name in MOMENTS if mapping[name] is None and None in (mapping[f"{name}_day"], mapping[f"{name}_time"])]
return [name for name in REQUIRED if name in absent or name in split]
def cell(row: list[str], index: int | None) -> str | None:
if index is None:
return None
return unguarded(row[index].strip()) if index < len(row) else ""
def weekday(value: str, column: str) -> int:
day = WEEKDAYS.get(value.strip().lower())
if day is None:
raise ToolError(f"column {column}: no weekday from 0 (Sunday) to 6 or a day name")
return day
def clock(value: str, column: str) -> str:
match = CLOCK.fullmatch(value.strip())
if match is None or int(match.group(1)) > 23:
raise ToolError(f"column {column}: no time HH:MM")
return f"{int(match.group(1)):02d}:{match.group(2)}"
def moment_of(row: list[str], mapping: dict[str, int | None], columns: list[str], name: str) -> dict:
day_index, time_index = mapping[f"{name}_day"], mapping[f"{name}_time"]
if day_index is not None and time_index is not None:
return {"day": weekday(cell(row, day_index), columns[day_index]), "time": clock(cell(row, time_index), columns[time_index])}
index = mapping[name]
parts = cell(row, index).rsplit(None, 1)
if len(parts) != 2:
raise ToolError(f"column {columns[index]}: no weekday and time like Mon 09:00")
return {"day": weekday(parts[0], columns[index]), "time": clock(parts[1], columns[index])}
def autorenew_of(value: str | None, column: str) -> bool:
lowered = (value or "").lower()
if lowered in YES:
return True
if lowered in NO:
return False
raise ToolError(f"column {column}: no yes/no, true/false, 1/0 or ja/nein")
def limit_of(value: str | None, column: str) -> int | None:
if not value:
return None
if not WHOLE.fullmatch(value):
raise ToolError(f"column {column}: no whole number of tokens")
return int(value)
def column_name(columns: list[str], index: int | None) -> str:
return "-" if index is None else columns[index]
def account_of(row: list[str], mapping: dict[str, int | None], columns: list[str]) -> dict:
"""Returns:
The row as valid_account() accepts it, absent optional fields empty;
a cell that cannot be read raises ToolError naming its column.
"""
raw = {name: cell(row, mapping[name]) or "" for name in ("provider", "email", "resubscribe", "note")}
raw["renewal"], raw["reset"] = (moment_of(row, mapping, columns, name) for name in MOMENTS)
raw["autorenew"] = autorenew_of(cell(row, mapping["autorenew"]), column_name(columns, mapping["autorenew"]))
raw["limit"] = limit_of(cell(row, mapping["limit"]), column_name(columns, mapping["limit"]))
return valid_account(raw)
def parsed(rows: list[list[str]], mapping: dict[str, int | None], columns: list[str]) -> list[dict]:
found = []
for number, row in enumerate(rows, start=2):
try:
found.append({"line": number, "account": account_of(row, mapping, columns), "error": None})
except ToolError as error:
found.append({"line": number, "account": None, "error": str(error)})
return found
def stored(account: dict) -> dict:
return {name: account[name] for name in KEYS}
def digest(accounts: list[dict]) -> str:
"""Returns:
The digest of the stored accounts with their ids, for apply to
refuse a ledger that changed since the preview.
"""
canonical = json.dumps([{**stored(account), "id": account["id"]} for account in accounts], sort_keys=True)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:DIGEST_LENGTH]
def duplicates(found: list[dict]) -> None:
lines: dict[str, list[int]] = {}
for entry in found:
if entry["account"] is not None:
lines.setdefault(entry["account"]["email"].lower(), []).append(entry["line"])
for entry in found:
twins = lines.get(entry["account"]["email"].lower(), []) if entry["account"] is not None else []
if len(twins) > 1:
entry.update(account=None, error=f"email appears in lines {', '.join(map(str, twins))}")
def choices_of(raw: object) -> dict[str, str]:
if not isinstance(raw, dict) or any(not isinstance(email, str) or choice not in CHOICES for email, choice in raw.items()):
raise ToolError(f"choices must map an email to one of {', '.join(CHOICES)}")
return {email.lower(): choice for email, choice in raw.items()}
def classified(entry: dict, known: dict[str, dict], choices: dict[str, str]) -> dict:
if entry["error"] is not None:
return {"line": entry["line"], "status": "error", "error": entry["error"]}
account = entry["account"]
email = account["email"].lower()
existing = known.get(email)
if existing is None:
return {"line": entry["line"], "status": "new", "account": account}
changed = [name for name in KEYS if stored(existing)[name] != account[name]]
if not changed:
return {"line": entry["line"], "status": "unchanged", "account": account, "id": existing["id"]}
return {"line": entry["line"], "status": "update", "account": account, "id": existing["id"], "changed": changed, "choice": choices.get(email, "overwrite")}
def preview(body: dict, accounts: list[dict]) -> dict:
"""Args:
body: {file, separator, mapping, choices}: file the bytes in base64,
separator "" to detect it, mapping null for the proposal else
a column number or null per field of MAPPED, choices overwrite
or keep per conflicting email.
accounts: the stored accounts.
Returns:
{separator, columns, mapping, missing, rows, errors, digest}: each
row {line, status new|update|unchanged|error, account?, id?,
changed?, choice?, error?}; rows stay empty while a required field
is missing.
"""
text = file_text(body["file"])
separator = separator_of(body["separator"], text)
columns, rows = table(text, separator)
mapping = requested_mapping(body["mapping"], columns)
choices = choices_of(body["choices"])
absent = missing(mapping)
found = [] if absent else parsed(rows, mapping, columns)
duplicates(found)
known = {account["email"].lower(): account for account in accounts}
classes = [classified(entry, known, choices) for entry in found]
errors = sum(entry["status"] == "error" for entry in classes)
return {"separator": separator, "columns": columns, "mapping": mapping, "missing": absent, "rows": classes, "errors": errors, "digest": digest(accounts)}
def planned(result: dict) -> tuple[dict[str, dict], list[dict], dict]:
"""Returns:
(changes by id, additions, counts): the overwrite updates, the new
accounts and how many rows were added, updated, kept and unchanged;
a missing field or an error row raises ToolError.
"""
if result["missing"] or result["errors"]:
raise ToolError("the import has missing fields or error rows; fix them in the preview first")
rows = result["rows"]
changes = {row["id"]: row["account"] for row in rows if row["status"] == "update" and row["choice"] == "overwrite"}
additions = [row["account"] for row in rows if row["status"] == "new"]
kept = sum(row["status"] == "update" and row["choice"] == "keep" for row in rows)
unchanged = sum(row["status"] == "unchanged" for row in rows)
return changes, additions, {"added": len(additions), "updated": len(changes), "kept": kept, "unchanged": unchanged}
class Transfer:
def __init__(self, ledger: Ledger) -> None:
self.ledger = ledger
def exported(self, fmt: str, today: datetime.date) -> tuple[str, bytes, str]:
"""Returns:
(content type, file bytes, file name accounts-<YYYY-MM-DD>.<fmt>).
"""
content_type, data = export(self.ledger.listed(), fmt)
return content_type, data, f"accounts-{today.isoformat()}.{fmt}"
def preview(self, body: bytes) -> dict:
return preview(section(decode(body), "body", PREVIEW_KEYS), self.ledger.listed())
def apply(self, body: bytes) -> dict:
"""Args:
body: the preview's body plus digest, the preview's ledger digest.
Returns:
The counts of planned(); the rows land in one ledger write, or
none: an error row raises ToolError, a ledger changed since the
preview raises Conflict.
"""
data = section(decode(body), "body", APPLY_KEYS)
accounts = self.ledger.listed()
changes, additions, counts = planned(preview(data, accounts))
def unchanged(current: list[dict]) -> None:
if digest(current) != data["digest"]:
raise Conflict({"reason": "the accounts changed since the preview", "digest": digest(current)})
self.ledger.batch(unchanged, changes, additions)
return counts
+19 -1
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import datetime
import re
import secrets
import time
@@ -7,9 +8,11 @@ from collections.abc import Callable
from http import HTTPStatus
from urllib.parse import urlsplit
from .accounts_io import Transfer
from .diffs import DIFF_BODY_LIMIT
from .engines import INPUT_LIMIT, STT_LIMIT
from .exchange import PLAIN_CSP, Exchange
from .fields import single
from .rates import rated
from .resources import RESOURCES, sampled
from .scores import scored
@@ -82,8 +85,10 @@ FIREWALL_STATUS = {"settings_preview": HTTPStatus.OK, "change_settings": HTTPSta
WAV_POSTS = (STT_ROUTE, VOICE_ROUTE)
ACCOUNTS_ROUTE = "/api/accounts"
ACCOUNT_DROP = re.compile(r"/api/accounts/([0-9a-f]{16})/delete")
ACCOUNTS_EXPORT = "/api/accounts/export"
ACCOUNTS_IMPORT = {"/api/accounts/import/preview": "preview", "/api/accounts/import/apply": "apply"}
SCHEDULES_ROUTE = "/api/schedules"
ACTION_POSTS = (ACCOUNTS_ROUTE, SCHEDULES_ROUTE,"/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
ACTION_POSTS = (ACCOUNTS_ROUTE, *ACCOUNTS_IMPORT, SCHEDULES_ROUTE,"/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
class Handler(Exchange):
@@ -95,6 +100,14 @@ class Handler(Exchange):
def hear(self, body: bytes) -> None:
self.answer(lambda: self.server.hub.speech.transcribe(body), HTTPStatus.OK)
def export_accounts(self) -> None:
transfer = Transfer(self.server.hub.accounts.ledger)
self.attempt(lambda: transfer.exported(single(self.query(), "format") or "", datetime.date.today()), self.send_file)
def send_file(self, exported: tuple[str, bytes, str]) -> None:
content_type, data, name = exported
self.send(HTTPStatus.OK, content_type, data, {"Content-Security-Policy": PLAIN_CSP, "Content-Disposition": f'attachment; filename="{name}"'})
def replay_voice(self, note_id: str) -> None:
headers = {"Content-Security-Policy": PLAIN_CSP}
self.attempt(lambda: self.server.hub.voice_notes.audio(note_id), lambda wav: self.send(HTTPStatus.OK, WAV_TYPE, wav, headers))
@@ -148,6 +161,8 @@ class Handler(Exchange):
self.answer(hub.match_cards, HTTPStatus.OK)
elif path == ACCOUNTS_ROUTE:
self.answer(lambda: hub.accounts.view(time.time()), HTTPStatus.OK)
elif path == ACCOUNTS_EXPORT:
self.export_accounts()
elif path == "/api/resources":
self.answer(lambda: sampled(hub.kept / RESOURCES, hub.span(self.query(), time.time())), HTTPStatus.OK)
elif path == "/api/scores":
@@ -194,6 +209,9 @@ class Handler(Exchange):
drop = ACCOUNT_DROP.fullmatch(path)
if path == ACCOUNTS_ROUTE:
return lambda body: self.answer(lambda: hub.accounts.save(body), HTTPStatus.OK)
if path in ACCOUNTS_IMPORT:
method = getattr(Transfer(hub.accounts.ledger), ACCOUNTS_IMPORT[path])
return lambda body: self.answer(lambda: method(body), HTTPStatus.OK)
if drop:
return lambda _body: self.answer(lambda: hub.accounts.drop(drop.group(1)), HTTPStatus.OK)
if path == SCHEDULES_ROUTE:
+25 -4
View File
@@ -10,6 +10,13 @@ from .diffs import SEALED_SUFFIX
from .records import read_json, stamp, write_atomic
def unused(items: dict[str, dict]) -> str:
item_id = secrets.token_hex(8)
while item_id in items:
item_id = secrets.token_hex(8)
return item_id
class Ledger:
def __init__(self, file: Path) -> None:
self.file = file
@@ -20,10 +27,24 @@ class Ledger:
def fresh(self) -> str:
with self.changed:
item_id = secrets.token_hex(8)
while item_id in self.items:
item_id = secrets.token_hex(8)
return item_id
return unused(self.items)
def batch(self, check: Callable[[list[dict]], None], changes: dict[str, dict], added: list[dict]) -> None:
"""Args:
check: raises to refuse the whole batch; it sees every record
under the lock the write holds.
changes: fields merged into the record of each id, which keeps
its id and created stamp.
added: new records, each under a fresh id.
"""
with self.changed:
check(self.listed())
items = {**self.items, **{item_id: {**self.items[item_id], **fields} for item_id, fields in changes.items()}}
created = stamp()
for fields in added:
item_id = unused(items)
items[item_id] = {**fields, "id": item_id, "created": created}
self.write(items)
def write(self, items: dict[str, dict]) -> None:
write_atomic(self.file, json.dumps(items, indent=1, sort_keys=True).encode("utf-8"))
+124 -1
View File
@@ -8,10 +8,38 @@
accountsView.body = body;
const add = iconBtn("bi-plus-lg", "Add account", "btn small soft", () => accountSheet(null), "Add account: provider, email, renewal and weekly reset; kept on this host only");
const panel = h("section", {class: "card res-panel res-accounts", "data-panel": "resources-accounts", "aria-label": "Accounts"},
h("div", {class: "res-head", "data-legend-slot": ""}, h("span", {class: "res-title", title: "Accounts", "aria-label": "Accounts"}, icon("bi-person-badge")), h("span", {class: "acc-title"}, "Accounts"), h("span", {class: "spacer"}), add), body);
h("div", {class: "res-head", "data-legend-slot": ""}, h("span", {class: "res-title", title: "Accounts", "aria-label": "Accounts"}, icon("bi-person-badge")), h("span", {class: "acc-title"}, "Accounts"), h("span", {class: "spacer"}),
accountsExportMenu(), accountsImportButton(), add), body);
return {panel, body};
}
function accountsExportMenu() {
const link = (format, label) => h("a", {class: "menu-item", href: `/api/accounts/export?format=${format}`, download: "", "data-export": format, ...named(label, `${label}: download every stored account; the hub keeps no copy`)}, label);
return h("details", {class: "menu acc-export"}, h("summary", {class: "btn small soft icon-only", ...named("Export accounts", "Export: download the accounts as CSV or TSV")}, icon("bi-download")),
h("div", {class: "menu-box end", role: "group", "aria-label": "Export format"}, link("csv", "CSV"), link("tsv", "TSV")));
}
function accountsImportButton() {
const picker = h("input", {type: "file", accept: ".csv,.tsv,.txt,text/csv,text/tab-separated-values", hidden: true, "aria-label": "Import file", "data-import-file": ""});
picker.addEventListener("change", async () => {
const file = picker.files[0];
picker.value = "";
if (file) {
accountImportSheet(file.name, bytesBase64(await file.arrayBuffer()));
}
});
return h("span", {class: "acc-import"}, picker, iconBtn("bi-upload", "Import accounts", "btn small soft", () => picker.click(), "Import: a CSV or TSV file, mapped to the fields and previewed before anything is saved"));
}
function bytesBase64(buffer) {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let start = 0; start < bytes.length; start += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(start, start + 0x8000));
}
return btoa(binary);
}
async function fetchAccounts() {
if (accountsView.busy) {
return;
@@ -87,6 +115,101 @@
return h("div", {class: "acc-body"}, accountsContent(accountsView.data));
}
const IMPORT_FIELDS = [
["provider", "Provider"], ["email", "Email"], ["renewal", "Renewal (day and time)"], ["renewal_day", "Renewal day"], ["renewal_time", "Renewal time"],
["reset", "Next reset (day and time)"], ["reset_day", "Reset day"], ["reset_time", "Reset time"], ["resubscribe", "Resubscribe"], ["autorenew", "Autorenew"],
["limit", "Weekly token limit"], ["note", "Note"],
];
const IMPORT_SEPARATORS = [["", "Detect"], [",", "Comma"], [";", "Semicolon"], ["\t", "Tab"]];
function accountImportSheet(name, file) {
const state = {file, separator: "", mapping: null, choices: {}, result: null};
const box = h("div", {class: "acc-import-body"}, h("p", {class: "muted"}, "…"));
const run = async () => {
const result = await sendJson("/api/accounts/import/preview", {file: state.file, separator: state.separator, mapping: state.mapping, choices: state.choices});
if (!result.ok) {
box.replaceChildren(h("p", {class: "muted", "data-import-refused": ""}, fail(result)[0]));
return;
}
state.result = result.data;
box.replaceChildren(...importContent(state, run));
};
openSheet(`Import accounts: ${name}`, [h("p", {class: "muted"}, "Nothing is saved before Apply; accounts not in the file stay."), box], true);
run();
}
function importMapping(state, run) {
const {columns, mapping} = state.result;
const select = (field, label) => h("label", {class: "acc-field"}, h("span", {}, label), h("select", {class: "field", "aria-label": `${label} column`, "data-map": field, on: {change: (event) => {
state.mapping = {...state.result.mapping, [field]: event.target.value === "" ? null : Number(event.target.value)};
run();
}}}, h("option", {value: ""}, "not in file"), columns.map((column, index) => h("option", {value: String(index), ...(mapping[field] === index ? {selected: true} : {})}, column || `column ${index + 1}`))));
const separator = h("label", {class: "acc-field"}, h("span", {}, "Separator"), h("select", {class: "field", "aria-label": "Separator", "data-separator": "", on: {change: (event) => {
state.separator = event.target.value;
state.mapping = null;
run();
}}}, IMPORT_SEPARATORS.map(([value, label]) => h("option", {value, ...(state.separator === value ? {selected: true} : {})}, label))));
return h("div", {class: "acc-form"}, separator, IMPORT_FIELDS.map(([field, label]) => select(field, label)));
}
function importChoice(state, row, run) {
if (row.status !== "update") {
return null;
}
const email = row.account.email;
return h("select", {class: "field", "aria-label": `Conflict ${email}`, "data-choice": email, on: {change: (event) => {
state.choices = {...state.choices, [email]: event.target.value};
run();
}}}, ["overwrite", "keep"].map((choice) => h("option", {value: choice, ...(row.choice === choice ? {selected: true} : {})}, choice)));
}
function importRow(state, row, run) {
const detail = row.status === "error" ? row.error : row.status === "update" ? row.changed.join(", ") : "";
const who = row.account ? `${row.account.provider} · ${row.account.email}` : "–";
return h("tr", {"data-import-row": row.status}, h("td", {}, String(row.line)), h("td", {}, h("span", {class: "pill", "data-tone": row.status === "error" ? "bad" : "ok"}, row.status)),
h("td", {}, who), h("td", {}, detail), h("td", {}, importChoice(state, row, run)));
}
function importAll(state, run) {
const updates = state.result.rows.filter((row) => row.status === "update");
if (!updates.length) {
return null;
}
const all = (choice) => btn(`All ${choice}`, "btn small ghost", () => {
state.choices = Object.fromEntries(updates.map((row) => [row.account.email, choice]));
run();
});
return h("div", {class: "actions", role: "group", "aria-label": "Every conflict"}, all("overwrite"), all("keep"));
}
function importContent(state, run) {
const {rows, missing, errors} = state.result;
const blocked = missing.length > 0 || errors > 0 || rows.length === 0;
const apply = h("button", {type: "button", class: "btn primary", "data-import-apply": "", ...(blocked ? {disabled: true} : {})}, icon("bi-check-lg"), "Apply");
apply.addEventListener("click", () => applyImport(state, run));
const notice = missing.length ? h("p", {class: "muted", "data-import-missing": ""}, `Missing: ${missing.join(", ")}`) : null;
const table = rows.length ? h("div", {class: "acc-scroll"}, h("table", {class: "acc-table"},
h("thead", {}, h("tr", {}, ["Line", "Status", "Account", "Changes or error", "Conflict"].map((label) => h("th", {scope: "col"}, label)))),
h("tbody", {}, rows.map((row) => importRow(state, row, run))))) : null;
return [importMapping(state, run), notice, importAll(state, run), table, h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), apply)];
}
async function applyImport(state, run) {
const result = await sendJson("/api/accounts/import/apply", {file: state.file, separator: state.separator, mapping: state.result.mapping, choices: state.choices, digest: state.result.digest});
if (result.status === 409) {
toast("Import: the accounts changed meanwhile", ["The preview was refreshed; check it and apply again."], false);
run();
return;
}
if (!result.ok) {
toast("Import: not applied", fail(result), false);
return;
}
closeSheet();
fetchAccounts();
toast("Import applied", [`${result.data.added} added, ${result.data.updated} updated, ${result.data.kept} kept, ${result.data.unchanged} unchanged`], true);
}
function momentFields(label, moment) {
const day = h("select", {class: "field", "aria-label": `${label} weekday`}, ACCOUNT_DAYS.map((name, index) => h("option", {value: String(index), ...(moment && moment.day === index ? {selected: true} : {})}, name)));
const time = h("input", {type: "time", class: "field", "aria-label": `${label} time`, value: moment ? moment.time : "00:00"});