Prune files not in the deploy set (stale build context)
Browse files
api/content_studio.py
DELETED
|
@@ -1,638 +0,0 @@
|
|
| 1 |
-
"""Content Studio: an App template that creates its own References and Posts databases.
|
| 2 |
-
|
| 3 |
-
S67-T40 (owner instruction 1; rulings R17, R18, R21, R11). Plan-only (round 1 R5): nothing here
|
| 4 |
-
publishes to any network. The template creates two TENANT-OWNED databases and binds the App to
|
| 5 |
-
Posts, opening on a calendar of posts. The App is delete-safe (rule 13, ARCHITECTURE section 24):
|
| 6 |
-
deleting it removes only the App record, so References and Posts and every row in them outlive it.
|
| 7 |
-
|
| 8 |
-
This module is the App's own code. Shared files reach it only through a guarded import
|
| 9 |
-
(`routes_templates.py`), so deleting this file removes the template and nothing else breaks.
|
| 10 |
-
"""
|
| 11 |
-
from __future__ import annotations
|
| 12 |
-
|
| 13 |
-
TEMPLATE_KEY = "content_studio"
|
| 14 |
-
LABEL = "Content Studio"
|
| 15 |
-
DESCRIPTION = "Plan posts from your references. Creates References and Posts databases."
|
| 16 |
-
|
| 17 |
-
#: R4: the channels a post is planned for. Channel length limits are ADVISED, never enforced (O4).
|
| 18 |
-
CHANNELS = ["LinkedIn", "X", "Instagram", "TikTok", "YouTube", "Reddit"]
|
| 19 |
-
NETWORKS = CHANNELS + ["Other"]
|
| 20 |
-
STATUSES = ["Idea", "Draft", "Ready", "Posted", "Skipped"]
|
| 21 |
-
CALENDAR_VIEW_ID = "cs_calendar"
|
| 22 |
-
|
| 23 |
-
#: R15 (structure, not words): the three fields a Reference is drafted FROM are extracted from its
|
| 24 |
-
#: pasted text by the per-row AI field machinery (`ai_enrich`), re-run when that text changes.
|
| 25 |
-
_EXTRACT = {
|
| 26 |
-
"hook": ("Hook", "In one sentence, describe the opening move this post uses to earn attention "
|
| 27 |
-
"(for example a surprising number, a contrarian claim, a question). Describe "
|
| 28 |
-
"the technique; do not quote the post. Post: {pasted_text}"),
|
| 29 |
-
"structure": ("Structure", "List the post's structure as 3 to 6 short numbered beats, each "
|
| 30 |
-
"naming what that part does (setup, proof, turn, ask). Describe, "
|
| 31 |
-
"never quote. Post: {pasted_text}"),
|
| 32 |
-
"angle": ("Angle", "In one sentence, name the point of view or argument the post takes and "
|
| 33 |
-
"who it is for. Do not quote the post. Post: {pasted_text}"),
|
| 34 |
-
}
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
#: The platform ladder leads with a REASONING model, which spends a few hundred tokens thinking
|
| 38 |
-
#: before it answers; at 300 the column's ceiling was reached with no answer ("the model had
|
| 39 |
-
#: nothing to answer from"), so each extraction gets room for thought plus a short answer.
|
| 40 |
-
EXTRACT_MAX_TOKENS = 1500
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def reference_fields():
|
| 44 |
-
"""References: URL, network, author, pasted text, tags, hook, structure, angle (T40 done-when)."""
|
| 45 |
-
fields = [
|
| 46 |
-
{"key": "title", "label": "Title", "type": "text"},
|
| 47 |
-
{"key": "url", "label": "URL", "type": "url"},
|
| 48 |
-
{"key": "network", "label": "Network", "type": "select", "options": list(NETWORKS)},
|
| 49 |
-
{"key": "author", "label": "Author", "type": "text"},
|
| 50 |
-
{"key": "pasted_text", "label": "Pasted text", "type": "text"},
|
| 51 |
-
{"key": "tags", "label": "Tags", "type": "multiselect", "options": []},
|
| 52 |
-
]
|
| 53 |
-
for key, (label, prompt) in _EXTRACT.items():
|
| 54 |
-
fields.append({"key": key, "label": label, "type": "ai_enrich",
|
| 55 |
-
"aiEnrich": {"prompt": prompt, "maxTokens": EXTRACT_MAX_TOKENS,
|
| 56 |
-
"trigger": {"mode": "on_change"}, "overwrite": "always"}})
|
| 57 |
-
return fields
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
def post_fields(references_key):
|
| 61 |
-
"""Posts: caption, channel, scheduled, status, media, campaign, post URL, References link,
|
| 62 |
-
attribution (T40 done-when). `media` is an `image` field: the store has no attachment type."""
|
| 63 |
-
return [
|
| 64 |
-
{"key": "caption", "label": "Caption", "type": "text"},
|
| 65 |
-
{"key": "channel", "label": "Channel", "type": "select", "options": list(CHANNELS)},
|
| 66 |
-
{"key": "scheduled", "label": "Scheduled", "type": "date"},
|
| 67 |
-
{"key": "status", "label": "Status", "type": "select", "options": list(STATUSES)},
|
| 68 |
-
{"key": "media", "label": "Media", "type": "image"},
|
| 69 |
-
{"key": "campaign", "label": "Campaign", "type": "text"},
|
| 70 |
-
{"key": "post_url", "label": "Post URL", "type": "url"},
|
| 71 |
-
{"key": "references", "label": "References", "type": "link",
|
| 72 |
-
"link": {"table": references_key, "selectionMode": "manual"}},
|
| 73 |
-
{"key": "attribution", "label": "Attribution", "type": "text"},
|
| 74 |
-
]
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
class ContentStudioError(RuntimeError):
|
| 78 |
-
"""A refusal the route turns into a plain sentence; nothing half-created is left behind."""
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def _create_table(label, username, fields, st):
|
| 82 |
-
"""`user_tables.create` refuses a duplicate label, so a second Studio gets "Posts 2" and so on."""
|
| 83 |
-
from core import user_tables
|
| 84 |
-
for attempt in range(1, 10):
|
| 85 |
-
name = label if attempt == 1 else f"{label} {attempt}"
|
| 86 |
-
key = user_tables.create(name, username, fields=fields, st=st)
|
| 87 |
-
if key:
|
| 88 |
-
return key
|
| 89 |
-
raise ContentStudioError(f"The {label} database could not be created. "
|
| 90 |
-
"Rename or delete an older one, then try again.")
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
def create(session, name=""):
|
| 94 |
-
"""Create References + Posts (tenant-owned), a calendar View on Posts, and the App bound to
|
| 95 |
-
Posts. Returns `{address, application, databases}`; on a failure part-way, the databases this
|
| 96 |
-
call created are deleted again, so a refusal leaves the workspace as it was."""
|
| 97 |
-
import application_registry
|
| 98 |
-
from core import user_tables, view_templates
|
| 99 |
-
from core import table_store
|
| 100 |
-
|
| 101 |
-
st = session.runtime
|
| 102 |
-
user = session.uname
|
| 103 |
-
app_name = " ".join(str(name or "").split())[:120] or LABEL
|
| 104 |
-
created = []
|
| 105 |
-
try:
|
| 106 |
-
references = _create_table("References", user, reference_fields(), st)
|
| 107 |
-
created.append(references)
|
| 108 |
-
posts = _create_table("Posts", user, post_fields(references), st)
|
| 109 |
-
created.append(posts)
|
| 110 |
-
ops = table_store.make(view_templates.workspace_key(posts), st=st)
|
| 111 |
-
ops.save_view(user, {"id": CALENDAR_VIEW_ID, "name": "Calendar", "createdBy": user,
|
| 112 |
-
"config": {"filters": [], "sorts": [],
|
| 113 |
-
"display": {"mode": "calendar", "dateField": "scheduled",
|
| 114 |
-
"titleField": "caption"}}})
|
| 115 |
-
application = application_registry.create(
|
| 116 |
-
st, session.tenant, user,
|
| 117 |
-
{"templateKind": TEMPLATE_KEY, "name": app_name, "sourceDatabase": posts,
|
| 118 |
-
"navPlacement": {"section": "app", "order": 0}},
|
| 119 |
-
allowed_databases=None)
|
| 120 |
-
except Exception:
|
| 121 |
-
for key in reversed(created):
|
| 122 |
-
try:
|
| 123 |
-
user_tables.delete(key, st=st)
|
| 124 |
-
except Exception:
|
| 125 |
-
pass
|
| 126 |
-
raise
|
| 127 |
-
# S67-T41 owner correction: the App opens on its own surface in the App module, not in Data.
|
| 128 |
-
return {"address": "#" + app_link(application["id"]), "application": application,
|
| 129 |
-
"databases": {"references": references, "posts": posts}}
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
# ---------------------------------------------------------------------------------------------
|
| 133 |
-
# S67-T41 (R13, R14, R15, R19, R20, R5, O4): DRAFTING. One Draft row per chosen channel, from
|
| 134 |
-
# several selected References plus a one-line topic, written from their extracted STRUCTURE
|
| 135 |
-
# (hook, structure, angle), never their words, with every author credited. Plan-only: a draft
|
| 136 |
-
# is a Posts row with status Draft; nothing is published anywhere.
|
| 137 |
-
# ---------------------------------------------------------------------------------------------
|
| 138 |
-
import re
|
| 139 |
-
|
| 140 |
-
from fastapi import APIRouter, Body, Depends
|
| 141 |
-
|
| 142 |
-
from deps import Session, err, require_session
|
| 143 |
-
|
| 144 |
-
router = APIRouter(prefix="/content-studio")
|
| 145 |
-
|
| 146 |
-
#: O4: channel limits are ADVICE in the prompt and on screen, never a truncation.
|
| 147 |
-
CHANNEL_ADVICE = {
|
| 148 |
-
"LinkedIn": "LinkedIn post: up to about 3,000 characters, short paragraphs, no hashtag wall.",
|
| 149 |
-
"X": "X post: aim for 280 characters or fewer.",
|
| 150 |
-
"Instagram": "Instagram caption: up to about 2,200 characters; a strong first line.",
|
| 151 |
-
"TikTok": "TikTok caption: short, about 150 characters.",
|
| 152 |
-
"YouTube": "YouTube: a title line, then a two or three sentence description.",
|
| 153 |
-
"Reddit": "Reddit: a title line, then the body; plain, specific, no marketing tone.",
|
| 154 |
-
}
|
| 155 |
-
DRAFT_SYSTEM = (
|
| 156 |
-
"You draft ONE original social media post for the channel named. You are given a one-line "
|
| 157 |
-
"topic and the STRUCTURE of several reference posts: the technique of each hook, its beats "
|
| 158 |
-
"and its angle. Borrow those structural moves; write entirely new sentences. Never copy or "
|
| 159 |
-
"closely paraphrase any sentence from anywhere. Answer with the post text only: no preamble, "
|
| 160 |
-
"no quotation marks around it, no markdown heading. Never use an em dash or an en dash; use "
|
| 161 |
-
"a comma, a colon or a full stop.")
|
| 162 |
-
LEDGER_SURFACE = "field_agent"
|
| 163 |
-
DRAFT_MAX_TOKENS = 3000 # a reasoning model thinks first; see EXTRACT_MAX_TOKENS
|
| 164 |
-
DRAFT_TIMEOUT_S = 60
|
| 165 |
-
#: A shared run of this many words is a copied sentence, whatever surrounds it (R15).
|
| 166 |
-
VERBATIM_WORDS = 8
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
def _studio(session, app_id):
|
| 170 |
-
"""(app, posts_key, references_key) for a Content Studio App this session may open."""
|
| 171 |
-
import application_registry
|
| 172 |
-
from core import user_tables
|
| 173 |
-
doc = application_registry.load(session.runtime)
|
| 174 |
-
app = doc["applications"].get(str(app_id or ""))
|
| 175 |
-
if (not isinstance(app, dict) or app.get("templateKind") != TEMPLATE_KEY
|
| 176 |
-
or not application_registry.may_read(app, session.uname, session.admin)):
|
| 177 |
-
raise err(404, "content_studio_not_found", "That Content Studio does not exist.")
|
| 178 |
-
posts = str(app.get("sourceDatabase") or "")
|
| 179 |
-
defn = user_tables.get(posts, session.runtime) or {}
|
| 180 |
-
link = next((f.get("link") for f in defn.get("fields") or ()
|
| 181 |
-
if isinstance(f, dict) and f.get("key") == "references"), None)
|
| 182 |
-
references = str((link or {}).get("table") or "")
|
| 183 |
-
if not posts or not references:
|
| 184 |
-
raise err(409, "content_studio_incomplete",
|
| 185 |
-
"This Content Studio has lost its Posts or References database.")
|
| 186 |
-
return app, posts, references
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
def _reference_rows(session, references):
|
| 190 |
-
from core import user_tables
|
| 191 |
-
defn = user_tables.get(references, session.runtime) or {}
|
| 192 |
-
rows = defn.get("rows") or {}
|
| 193 |
-
return {str(rid): (row if isinstance(row, dict) else {}) for rid, row in rows.items()}
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
# ---------------------------------------------------------------------------------------------
|
| 197 |
-
# S67-T42 (R35, standing rule 1): THE MONTHLY DRAFTING ALLOWANCE. Drafting runs on Loopable's
|
| 198 |
-
# platform keys, so each tenant gets a monthly count of drafts (one Draft row = one draft). Past
|
| 199 |
-
# it, Draft pauses with a sentence naming the reset date; the platform admin raises it per tenant
|
| 200 |
-
# (`PUT /content-studio/allowance`). A tenant admin cannot: that would defeat R35.
|
| 201 |
-
# One per-tenant bucket, owned by this module: {"allowance": int (absent = default),
|
| 202 |
-
# "months": {"YYYY-MM": drafts made}}. Month and reset are UTC.
|
| 203 |
-
# ---------------------------------------------------------------------------------------------
|
| 204 |
-
ALLOWANCE_KEY = "content_studio_usage"
|
| 205 |
-
DEFAULT_MONTHLY_DRAFTS = 100
|
| 206 |
-
ALLOWANCE_KEEP_MONTHS = 12
|
| 207 |
-
_MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", "August",
|
| 208 |
-
"September", "October", "November", "December")
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
def _now():
|
| 212 |
-
from datetime import datetime, timezone
|
| 213 |
-
return datetime.now(timezone.utc)
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
def _month_key(now):
|
| 217 |
-
return f"{now.year:04d}-{now.month:02d}"
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
def _reset_on(now):
|
| 221 |
-
"""The first day of next month (UTC): the day this month's count stops counting."""
|
| 222 |
-
from datetime import date
|
| 223 |
-
return date(now.year + 1, 1, 1) if now.month == 12 else date(now.year, now.month + 1, 1)
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
def _spoken_date(day):
|
| 227 |
-
return f"{_MONTH_NAMES[day.month - 1]} {day.day}, {day.year}"
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
def _limit(doc):
|
| 231 |
-
raw = (doc or {}).get("allowance")
|
| 232 |
-
if isinstance(raw, bool) or not isinstance(raw, int) or raw < 0:
|
| 233 |
-
return DEFAULT_MONTHLY_DRAFTS
|
| 234 |
-
return raw
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
def allowance_state(doc, now=None):
|
| 238 |
-
"""{used, limit, remaining, resetsOn, paused, message}: the ONE reading of month and reset
|
| 239 |
-
that both the panel and the enforcement use."""
|
| 240 |
-
now = now or _now()
|
| 241 |
-
doc = doc if isinstance(doc, dict) else {}
|
| 242 |
-
months = doc.get("months") if isinstance(doc.get("months"), dict) else {}
|
| 243 |
-
try:
|
| 244 |
-
used = max(0, int(months.get(_month_key(now)) or 0))
|
| 245 |
-
except (TypeError, ValueError):
|
| 246 |
-
used = 0
|
| 247 |
-
limit = _limit(doc)
|
| 248 |
-
remaining = max(0, limit - used)
|
| 249 |
-
reset = _reset_on(now)
|
| 250 |
-
paused = remaining <= 0
|
| 251 |
-
message = (f"This workspace has used this month's drafting allowance. "
|
| 252 |
-
f"It resets on {_spoken_date(reset)}.") if paused else ""
|
| 253 |
-
return {"used": used, "limit": limit, "remaining": remaining,
|
| 254 |
-
"resetsOn": reset.isoformat(), "paused": paused, "message": message}
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
def _short_message(remaining):
|
| 258 |
-
drafts = "1 draft" if remaining == 1 else f"{remaining} drafts"
|
| 259 |
-
channels = "1 channel" if remaining == 1 else f"up to {remaining} channels"
|
| 260 |
-
return f"This workspace has {drafts} left this month. Choose {channels}."
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
def _refusal(state, wanted):
|
| 264 |
-
"""The 429 a draft of `wanted` drafts earns against `state`, or None when it fits."""
|
| 265 |
-
if state["remaining"] <= 0:
|
| 266 |
-
return err(429, "drafting_allowance_used", state["message"])
|
| 267 |
-
if state["remaining"] < wanted:
|
| 268 |
-
return err(429, "drafting_allowance_short", _short_message(state["remaining"]))
|
| 269 |
-
return None
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
def _read_allowance(st):
|
| 273 |
-
doc = st.get(ALLOWANCE_KEY)
|
| 274 |
-
return doc if isinstance(doc, dict) else {}
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
def _count(st, month, delta):
|
| 278 |
-
"""Add `delta` drafts to `month` in one read-modify-write; keeps the last 12 months."""
|
| 279 |
-
def _up(doc):
|
| 280 |
-
doc = dict(doc) if isinstance(doc, dict) else {}
|
| 281 |
-
months = dict(doc.get("months")) if isinstance(doc.get("months"), dict) else {}
|
| 282 |
-
months[month] = max(0, int(months.get(month) or 0) + int(delta))
|
| 283 |
-
for stale in sorted(months)[:-ALLOWANCE_KEEP_MONTHS]:
|
| 284 |
-
months.pop(stale, None)
|
| 285 |
-
doc["months"] = months
|
| 286 |
-
return doc
|
| 287 |
-
st.update(ALLOWANCE_KEY, _up, flush="sync")
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
def reserve_drafts(st, wanted, now=None):
|
| 291 |
-
"""Check AND reserve `wanted` drafts in ONE store update, so two concurrent drafts cannot both
|
| 292 |
-
take the last slot. Raises the 429 (no write) when it does not fit; returns the month key the
|
| 293 |
-
reservation was booked to, for `release_drafts` on a failure."""
|
| 294 |
-
now = now or _now()
|
| 295 |
-
try:
|
| 296 |
-
current = _read_allowance(st)
|
| 297 |
-
except Exception: # noqa: BLE001
|
| 298 |
-
raise err(503, "allowance_unavailable",
|
| 299 |
-
"The drafting allowance could not be checked, so nothing was drafted. Try again.")
|
| 300 |
-
refusal = _refusal(allowance_state(current, now), wanted)
|
| 301 |
-
if refusal is not None: # fast path: a paused workspace writes nothing
|
| 302 |
-
raise refusal
|
| 303 |
-
month = _month_key(now)
|
| 304 |
-
verdict = {}
|
| 305 |
-
|
| 306 |
-
def _up(doc):
|
| 307 |
-
doc = dict(doc) if isinstance(doc, dict) else {}
|
| 308 |
-
refused = _refusal(allowance_state(doc, now), wanted)
|
| 309 |
-
if refused is not None:
|
| 310 |
-
verdict["refusal"] = refused
|
| 311 |
-
return doc
|
| 312 |
-
months = dict(doc.get("months")) if isinstance(doc.get("months"), dict) else {}
|
| 313 |
-
months[month] = max(0, int(months.get(month) or 0)) + int(wanted)
|
| 314 |
-
for stale in sorted(months)[:-ALLOWANCE_KEEP_MONTHS]:
|
| 315 |
-
months.pop(stale, None)
|
| 316 |
-
doc["months"] = months
|
| 317 |
-
return doc
|
| 318 |
-
|
| 319 |
-
try:
|
| 320 |
-
st.update(ALLOWANCE_KEY, _up, flush="sync")
|
| 321 |
-
except Exception: # noqa: BLE001
|
| 322 |
-
raise err(503, "allowance_unavailable",
|
| 323 |
-
"The drafting allowance could not be checked, so nothing was drafted. Try again.")
|
| 324 |
-
if "refusal" in verdict:
|
| 325 |
-
raise verdict["refusal"]
|
| 326 |
-
return month
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
def release_drafts(st, month, n):
|
| 330 |
-
"""Hand back a reservation whose drafts were never written (AI failure, copy refusal, store)."""
|
| 331 |
-
try:
|
| 332 |
-
_count(st, month, -int(n))
|
| 333 |
-
except Exception: # noqa: BLE001
|
| 334 |
-
pass
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
@router.put("/allowance")
|
| 338 |
-
def set_allowance(body: dict = Body(default=None), session: Session = Depends(require_session)):
|
| 339 |
-
"""The owner raises (or resets) one tenant's monthly drafting allowance. Platform admin only."""
|
| 340 |
-
import core.platform_admin as platform_admin
|
| 341 |
-
from harness import runtime
|
| 342 |
-
if not platform_admin.is_platform_admin(session.user):
|
| 343 |
-
raise err(403, "forbidden", "your account does not have access to this surface")
|
| 344 |
-
body = body if isinstance(body, dict) else {}
|
| 345 |
-
slug = str(body.get("tenant") or "").strip().lower()
|
| 346 |
-
monthly = body.get("monthly")
|
| 347 |
-
if monthly is not None and (isinstance(monthly, bool) or not isinstance(monthly, int)
|
| 348 |
-
or monthly < 0):
|
| 349 |
-
raise err(400, "bad_allowance",
|
| 350 |
-
"The monthly allowance must be a whole number of drafts, 0 or more.")
|
| 351 |
-
if not slug or slug not in runtime.known_tenants():
|
| 352 |
-
raise err(404, "tenant_not_found", "That workspace does not exist.")
|
| 353 |
-
try:
|
| 354 |
-
st = runtime.get_runtime(slug)
|
| 355 |
-
except KeyError:
|
| 356 |
-
raise err(404, "tenant_not_found", "That workspace does not exist.")
|
| 357 |
-
|
| 358 |
-
def _up(doc):
|
| 359 |
-
doc = dict(doc) if isinstance(doc, dict) else {}
|
| 360 |
-
if monthly is None:
|
| 361 |
-
doc.pop("allowance", None)
|
| 362 |
-
else:
|
| 363 |
-
doc["allowance"] = int(monthly)
|
| 364 |
-
return doc
|
| 365 |
-
|
| 366 |
-
st.update(ALLOWANCE_KEY, _up, flush="sync")
|
| 367 |
-
return {"tenant": slug, "allowance": allowance_state(_read_allowance(st))}
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
@router.get("/references")
|
| 371 |
-
def list_references(app: str = "", session: Session = Depends(require_session)):
|
| 372 |
-
"""The References a Draft can use: id, title, author, network, and whether its structure is in.
|
| 373 |
-
Also this workspace's drafting allowance, so the panel reports the limit before it bites."""
|
| 374 |
-
_app, _posts, references = _studio(session, app)
|
| 375 |
-
rows = _reference_rows(session, references)
|
| 376 |
-
try:
|
| 377 |
-
allowance = allowance_state(_read_allowance(session.runtime))
|
| 378 |
-
except Exception: # noqa: BLE001
|
| 379 |
-
allowance = None # unreadable: the draft route still enforces it
|
| 380 |
-
return {"references": [
|
| 381 |
-
{"id": rid, "title": str(row.get("title") or row.get("url") or "Untitled reference")[:160],
|
| 382 |
-
"author": str(row.get("author") or "")[:120], "network": str(row.get("network") or ""),
|
| 383 |
-
"extracted": bool(str(row.get("structure") or "").strip())}
|
| 384 |
-
for rid, row in rows.items()],
|
| 385 |
-
"channels": list(CHANNELS), "advice": dict(CHANNEL_ADVICE), "allowance": allowance}
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
# ---------------------------------------------------------------------------------------------
|
| 389 |
-
# S67-T41 OWNER CORRECTION (Telegram update 437342853, 2026-09-28): "Content studio should be an
|
| 390 |
-
# App ... it should act like Catalog / Route where it just uses the data module as what its
|
| 391 |
-
# building on top." So the App opens in the App module on its OWN surface (`#/app?studio=<id>`,
|
| 392 |
-
# `apps/contentStudio/ContentStudioApp.tsx`): a calendar and a board over Posts, the Draft door,
|
| 393 |
-
# and the two databases underneath. Data still holds References and Posts; the App never sends
|
| 394 |
-
# anyone there to use it.
|
| 395 |
-
# ⚠ The shared `/applications` doors (`routes_assets.py`) admit only topic-backed databases, so
|
| 396 |
-
# they refuse an App bound to a user table; the read, star and delete this App needs live here,
|
| 397 |
-
# on the registry's own writers, behind the same `_studio` + `may_read` / `may_edit` walls.
|
| 398 |
-
# ---------------------------------------------------------------------------------------------
|
| 399 |
-
def app_link(app_id):
|
| 400 |
-
"""The one address a Content Studio App opens at (App module, its own surface)."""
|
| 401 |
-
return f"/app?studio={app_id}"
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
#: The Posts fields the surface draws, in the grid's own Field shape so `viewModes.CalendarView`
|
| 405 |
-
#: (by Scheduled) and `KanbanView` (by Status) render them unchanged.
|
| 406 |
-
SURFACE_FIELDS = ("caption", "channel", "scheduled", "status", "attribution", "campaign")
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
def _surface_field(defn):
|
| 410 |
-
kind = {"date": "date", "select": "select"}.get(defn.get("type"), "text")
|
| 411 |
-
field = {"key": defn["key"], "label": str(defn.get("label") or defn["key"]), "type": kind,
|
| 412 |
-
"source": "overlay"}
|
| 413 |
-
if kind == "select":
|
| 414 |
-
field["options"] = [str(o) for o in (defn.get("options") or ())]
|
| 415 |
-
return field
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
def _studio_or_missing(session, app_id):
|
| 419 |
-
"""`_studio`, answering an absent App with the code the App home already reads as 'gone'."""
|
| 420 |
-
try:
|
| 421 |
-
return _studio(session, app_id)
|
| 422 |
-
except Exception as exc: # noqa: BLE001
|
| 423 |
-
if getattr(exc, "status_code", None) == 404:
|
| 424 |
-
raise err(404, "application_not_found", "That Content Studio no longer exists.")
|
| 425 |
-
raise
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
@router.get("/studio")
|
| 429 |
-
def studio(app: str = "", session: Session = Depends(require_session)):
|
| 430 |
-
"""Everything the App surface draws: the App, Posts (surface fields + rows), References'
|
| 431 |
-
count, the statuses in board order, and the drafting allowance."""
|
| 432 |
-
from core import user_tables
|
| 433 |
-
application, posts, references = _studio(session, app)
|
| 434 |
-
if not user_tables.may_open(posts, session.uname, session.admin, st=session.runtime):
|
| 435 |
-
raise err(404, "content_studio_not_found", "That Content Studio does not exist.")
|
| 436 |
-
posts_def = user_tables.get(posts, session.runtime) or {}
|
| 437 |
-
refs_def = user_tables.get(references, session.runtime) or {}
|
| 438 |
-
by_key = {f.get("key"): f for f in posts_def.get("fields") or () if isinstance(f, dict)}
|
| 439 |
-
fields = [_surface_field(by_key[key]) for key in SURFACE_FIELDS if key in by_key]
|
| 440 |
-
rows = []
|
| 441 |
-
for rid, row in (posts_def.get("rows") or {}).items():
|
| 442 |
-
try:
|
| 443 |
-
pid = int(rid)
|
| 444 |
-
except (TypeError, ValueError):
|
| 445 |
-
continue
|
| 446 |
-
row = row if isinstance(row, dict) else {}
|
| 447 |
-
rows.append({"pid": pid, **{key: row.get(key) for key in SURFACE_FIELDS}})
|
| 448 |
-
rows.sort(key=lambda r: r["pid"])
|
| 449 |
-
try:
|
| 450 |
-
allowance = allowance_state(_read_allowance(session.runtime))
|
| 451 |
-
except Exception: # noqa: BLE001
|
| 452 |
-
allowance = None
|
| 453 |
-
return {"app": {"id": application["id"], "name": application.get("name") or LABEL},
|
| 454 |
-
"posts": {"database": posts, "label": str(posts_def.get("label") or "Posts"),
|
| 455 |
-
"fields": fields, "rows": rows},
|
| 456 |
-
"references": {"database": references,
|
| 457 |
-
"label": str(refs_def.get("label") or "References"),
|
| 458 |
-
"count": len(refs_def.get("rows") or {})},
|
| 459 |
-
"statuses": list(STATUSES), "allowance": allowance}
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
@router.patch("/apps/{app_id}")
|
| 463 |
-
def star_app(app_id: str, body: dict = Body(default=None),
|
| 464 |
-
session: Session = Depends(require_session)):
|
| 465 |
-
"""Star or unstar a Content Studio on the App home (the registry's own star writer)."""
|
| 466 |
-
import application_registry
|
| 467 |
-
_app, posts, _references = _studio_or_missing(session, app_id)
|
| 468 |
-
body = body if isinstance(body, dict) else {}
|
| 469 |
-
if set(body) != {"starred"} or not isinstance(body.get("starred"), bool):
|
| 470 |
-
raise err(400, "bad_patch", "Only the star of a Content Studio changes here.")
|
| 471 |
-
try:
|
| 472 |
-
landed = application_registry.mutate(session.runtime, app_id, session.uname, session.admin,
|
| 473 |
-
{"starred": body["starred"]}, allowed_databases=[posts])
|
| 474 |
-
except PermissionError:
|
| 475 |
-
raise err(403, "forbidden", "You cannot change this App.")
|
| 476 |
-
except application_registry.ApplicationError:
|
| 477 |
-
raise err(404, "application_not_found", "That Content Studio no longer exists.")
|
| 478 |
-
return {"application": landed}
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
@router.delete("/apps/{app_id}")
|
| 482 |
-
def delete_app(app_id: str, body: dict = Body(default=None),
|
| 483 |
-
session: Session = Depends(require_session)):
|
| 484 |
-
"""Delete the App and nothing else (rule 13): References and Posts, every row in them, and
|
| 485 |
-
every View on them outlive it. The name is confirmed inside the registry's own update."""
|
| 486 |
-
import application_registry
|
| 487 |
-
application, posts, _references = _studio_or_missing(session, app_id)
|
| 488 |
-
confirm = (body or {}).get("confirmName") if isinstance(body, dict) else None
|
| 489 |
-
if not isinstance(confirm, str) or confirm != application.get("name"):
|
| 490 |
-
raise err(400, "confirm_name", "Enter the exact App name to confirm.")
|
| 491 |
-
|
| 492 |
-
class _NameConfirmed:
|
| 493 |
-
def update(self, key, delete):
|
| 494 |
-
def confirmed(raw):
|
| 495 |
-
deleted = delete(raw)
|
| 496 |
-
if (raw.get("applications") or {}).get(app_id, {}).get("name") != confirm:
|
| 497 |
-
raise application_registry.ApplicationError("the App name changed")
|
| 498 |
-
return deleted
|
| 499 |
-
return session.runtime.update(key, confirmed)
|
| 500 |
-
|
| 501 |
-
try:
|
| 502 |
-
return application_registry.delete(_NameConfirmed(), app_id, session.uname, session.admin,
|
| 503 |
-
allowed_databases=[posts])
|
| 504 |
-
except PermissionError:
|
| 505 |
-
raise err(403, "forbidden", "You no longer have permission to delete this App.")
|
| 506 |
-
except application_registry.ApplicationError:
|
| 507 |
-
raise err(400, "confirm_name", "The App name may have changed. Close this dialog and reload to retry.")
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
def _words(text):
|
| 511 |
-
return re.findall(r"[a-z0-9']+", str(text or "").lower())
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
def copied_sentence(draft, sources):
|
| 515 |
-
"""The first run of VERBATIM_WORDS consecutive words a draft shares with any source, or ''."""
|
| 516 |
-
grams = set()
|
| 517 |
-
for source in sources:
|
| 518 |
-
words = _words(source)
|
| 519 |
-
grams.update(" ".join(words[i:i + VERBATIM_WORDS])
|
| 520 |
-
for i in range(0, max(0, len(words) - VERBATIM_WORDS + 1)))
|
| 521 |
-
words = _words(draft)
|
| 522 |
-
for i in range(0, max(0, len(words) - VERBATIM_WORDS + 1)):
|
| 523 |
-
gram = " ".join(words[i:i + VERBATIM_WORDS])
|
| 524 |
-
if gram in grams:
|
| 525 |
-
return gram
|
| 526 |
-
return ""
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
def attribution(rows):
|
| 530 |
-
"""Every selected reference's author, credited in plain words (R14 traceability)."""
|
| 531 |
-
names = list(dict.fromkeys(
|
| 532 |
-
str(row.get("author") or row.get("title") or "an unnamed source").strip() for row in rows))
|
| 533 |
-
joined = names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]
|
| 534 |
-
return f"Structure drawn from posts by {joined}."
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
def draft_prompt(topic, channel, rows):
|
| 538 |
-
parts = [f"Channel: {channel}. {CHANNEL_ADVICE.get(channel, '')}", f"Topic: {topic}", ""]
|
| 539 |
-
for n, row in enumerate(rows, 1):
|
| 540 |
-
parts.append(f"Reference {n} ({row.get('network') or 'post'}):")
|
| 541 |
-
for key, label in (("hook", "Hook technique"), ("structure", "Structure"), ("angle", "Angle")):
|
| 542 |
-
value = " ".join(str(row.get(key) or "").split())[:900]
|
| 543 |
-
if value:
|
| 544 |
-
parts.append(f" {label}: {value}")
|
| 545 |
-
parts.append("")
|
| 546 |
-
parts.append("Write the post now.")
|
| 547 |
-
return "\n".join(parts)
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
def draft_posts(session, app_id, reference_ids, topic, channels, *, ask=None):
|
| 551 |
-
"""Generate EVERY channel first; write the Posts rows only if all succeeded (no half row)."""
|
| 552 |
-
topic = " ".join(str(topic or "").split())[:200]
|
| 553 |
-
ids = [str(x) for x in dict.fromkeys(reference_ids or ())][:50]
|
| 554 |
-
wanted = [c for c in dict.fromkeys(channels or ()) if c in CHANNELS]
|
| 555 |
-
if not ids:
|
| 556 |
-
raise err(400, "no_references", "Select at least one reference to draft from.")
|
| 557 |
-
if not topic:
|
| 558 |
-
raise err(400, "no_topic", "Type a one-line topic for the draft.")
|
| 559 |
-
if not wanted:
|
| 560 |
-
raise err(400, "no_channels", "Choose at least one channel.")
|
| 561 |
-
_app, posts, references = _studio(session, app_id)
|
| 562 |
-
rows_by_id = _reference_rows(session, references)
|
| 563 |
-
missing = [rid for rid in ids if rid not in rows_by_id]
|
| 564 |
-
if missing:
|
| 565 |
-
raise err(409, "references_missing", "A selected reference no longer exists. Reload and try again.")
|
| 566 |
-
chosen = [rows_by_id[rid] for rid in ids]
|
| 567 |
-
if not any(str(row.get("structure") or "").strip() for row in chosen):
|
| 568 |
-
raise err(409, "references_not_extracted",
|
| 569 |
-
"The selected references have no extracted structure yet. Paste their text first.")
|
| 570 |
-
# R35: the allowance is checked and reserved BEFORE any provider is resolved or called. One
|
| 571 |
-
# draft per channel; the reservation is handed back unless every row is written.
|
| 572 |
-
month = reserve_drafts(session.runtime, len(wanted))
|
| 573 |
-
try:
|
| 574 |
-
return _generate_and_save(session, posts, ids, topic, wanted, chosen, ask=ask)
|
| 575 |
-
except BaseException:
|
| 576 |
-
release_drafts(session.runtime, month, len(wanted))
|
| 577 |
-
raise
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
def _generate_and_save(session, posts, ids, topic, wanted, chosen, *, ask=None):
|
| 581 |
-
import ai_enrich
|
| 582 |
-
import ai_review
|
| 583 |
-
import usage_ledger
|
| 584 |
-
from core import user_tables
|
| 585 |
-
|
| 586 |
-
live = ai_review.ladder()
|
| 587 |
-
if not live and ask is None:
|
| 588 |
-
raise err(503, "ai_unavailable", "No AI provider is configured here, so nothing was drafted.")
|
| 589 |
-
provider = (live or [{"name": "injected", "model": "injected"}])[0]
|
| 590 |
-
model = provider["model"]
|
| 591 |
-
caller = ask or ai_enrich._ask
|
| 592 |
-
sources = [row.get("pasted_text") or "" for row in chosen]
|
| 593 |
-
drafts, tokens, calls = [], 0, 0
|
| 594 |
-
try:
|
| 595 |
-
for channel in wanted:
|
| 596 |
-
prompt = draft_prompt(topic, channel, chosen)
|
| 597 |
-
text = ""
|
| 598 |
-
for attempt in range(2):
|
| 599 |
-
answer, used, problem = caller(provider, model, prompt, DRAFT_MAX_TOKENS,
|
| 600 |
-
DRAFT_TIMEOUT_S, system=DRAFT_SYSTEM)
|
| 601 |
-
calls += 1
|
| 602 |
-
tokens += int(used or 0)
|
| 603 |
-
if problem or not str(answer or "").strip():
|
| 604 |
-
raise err(502, "draft_failed", f"The {channel} draft could not be written "
|
| 605 |
-
f"({problem or 'the model returned nothing'}). Nothing was saved.")
|
| 606 |
-
text = ai_enrich.no_dashes(str(answer).strip())
|
| 607 |
-
copied = copied_sentence(text, sources)
|
| 608 |
-
if not copied:
|
| 609 |
-
break
|
| 610 |
-
prompt += f"\n\nYour last draft reused this wording from a reference: \"{copied}\". Rewrite it in new words."
|
| 611 |
-
text = ""
|
| 612 |
-
if not text:
|
| 613 |
-
raise err(502, "draft_copied", f"The {channel} draft kept repeating a reference's "
|
| 614 |
-
"wording, so it was not saved. Nothing was saved.")
|
| 615 |
-
drafts.append({"channel": channel, "caption": text})
|
| 616 |
-
finally:
|
| 617 |
-
if calls:
|
| 618 |
-
# `usage_ledger.SURFACES` names four surfaces and refuses any other, so drafts are
|
| 619 |
-
# booked as `field_agent` (AI-written cells of a user table) until a `content_studio`
|
| 620 |
-
# surface exists there (a finding for the ledger's owner; this module cannot add it).
|
| 621 |
-
usage_ledger.record(LEDGER_SURFACE, provider["name"], model, total=tokens,
|
| 622 |
-
calls=calls, st=session.runtime, user=session.uname)
|
| 623 |
-
credit = attribution(chosen)
|
| 624 |
-
new_rows = [{"caption": d["caption"], "channel": d["channel"], "status": "Draft",
|
| 625 |
-
"references": ",".join(ids), "attribution": credit} for d in drafts]
|
| 626 |
-
created = user_tables.add_rows(posts, new_rows, username=session.uname, st=session.runtime)
|
| 627 |
-
if not created:
|
| 628 |
-
raise err(503, "store_unavailable", "The drafts could not be saved. Nothing was saved.")
|
| 629 |
-
return {"created": list(created) if isinstance(created, (list, tuple)) else created,
|
| 630 |
-
"drafts": drafts, "attribution": credit, "tokens": tokens, "calls": calls,
|
| 631 |
-
"provider": provider["name"], "model": model}
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
@router.post("/draft")
|
| 635 |
-
def draft(body: dict = Body(default=None), session: Session = Depends(require_session)):
|
| 636 |
-
body = body if isinstance(body, dict) else {}
|
| 637 |
-
return draft_posts(session, body.get("app"), body.get("references"), body.get("topic"),
|
| 638 |
-
body.get("channels"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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0,0 @@
|
|
| 1 |
-
import { Suspense, lazy, useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
|
| 2 |
-
import { API_V1, CREDENTIALS } from "../../apiContract";
|
| 3 |
-
import { BodyPortal, useOverlayLayer } from "../../customer-grid/OverlaySurface";
|
| 4 |
-
import { dataPathHash } from "../../customer-grid/dataPath";
|
| 5 |
-
import type { Field, Row } from "../../customer-grid/types";
|
| 6 |
-
import { CalendarView, KanbanView } from "../../customer-grid/viewModes";
|
| 7 |
-
import "../../styles/wave50/grid.css";
|
| 8 |
-
|
| 9 |
-
/** Drafting is its own drawer (S67-T41/T42); it loads only when the owner asks to draft. */
|
| 10 |
-
const DraftPanel = lazy(() => import("./DraftPanel"));
|
| 11 |
-
|
| 12 |
-
interface StudioPost { pid: number; caption?: string | null; channel?: string | null; scheduled?: string | null;
|
| 13 |
-
status?: string | null; attribution?: string | null; campaign?: string | null }
|
| 14 |
-
interface Studio {
|
| 15 |
-
app: { id: string; name: string };
|
| 16 |
-
posts: { database: string; label: string; fields: Field[]; rows: StudioPost[] };
|
| 17 |
-
references: { database: string; label: string; count: number };
|
| 18 |
-
statuses: string[];
|
| 19 |
-
}
|
| 20 |
-
type Load = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; studio: Studio };
|
| 21 |
-
type Mode = "calendar" | "board";
|
| 22 |
-
|
| 23 |
-
/** The server's own sentence first (top-level `error.message`), then the legacy nesting. */
|
| 24 |
-
const sentence = (body: unknown, fallback: string): string => {
|
| 25 |
-
const row = body as { error?: { message?: string }; detail?: { error?: { message?: string } } } | null;
|
| 26 |
-
return row?.error?.message || row?.detail?.error?.message || fallback;
|
| 27 |
-
};
|
| 28 |
-
|
| 29 |
-
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
|
| 30 |
-
|
| 31 |
-
/** A post's one-line name on a calendar chip or a board card: its channel, then its opening words. */
|
| 32 |
-
const titleOf = (post: StudioPost): string => {
|
| 33 |
-
const words = String(post.caption ?? "").replace(/\s+/g, " ").trim();
|
| 34 |
-
const head = words.length > 70 ? `${words.slice(0, 70).trimEnd()}…` : words || "Untitled post";
|
| 35 |
-
return post.channel ? `${post.channel}: ${head}` : head;
|
| 36 |
-
};
|
| 37 |
-
|
| 38 |
-
const TITLE_FIELD: Field = { key: "title", label: "Post", type: "text", source: "overlay" };
|
| 39 |
-
|
| 40 |
-
/**
|
| 41 |
-
* S67-T41 OWNER CORRECTION (Telegram update 437342853, 2026-09-28): "Content studio should be an
|
| 42 |
-
* App ... it should act like Catalog / Route where it just uses the data module as what its
|
| 43 |
-
* building on top." So this is the App: it opens in the App module on its own surface and works
|
| 44 |
-
* the Posts and References databases underneath, which stay in Data. A calendar of posts by
|
| 45 |
-
* Scheduled beside the posts not yet scheduled, a board of posts by Status (a drag moves one),
|
| 46 |
-
* a post drawer to schedule it, and the Draft door. Plan-only (round 1 R5): nothing publishes.
|
| 47 |
-
* The calendar and the board are the grid's own `CalendarView` and `KanbanView`, unchanged.
|
| 48 |
-
*/
|
| 49 |
-
export default function ContentStudioApp({ appId }: { appId: string }) {
|
| 50 |
-
const [load, setLoad] = useState<Load>({ phase: "loading" });
|
| 51 |
-
const [epoch, setEpoch] = useState(0);
|
| 52 |
-
const [mode, setMode] = useState<Mode>("calendar");
|
| 53 |
-
const [draftOpen, setDraftOpen] = useState(false);
|
| 54 |
-
const [openPid, setOpenPid] = useState<number | null>(null);
|
| 55 |
-
const [notice, setNotice] = useState("");
|
| 56 |
-
const [moved, setMoved] = useState<Record<number, string>>({});
|
| 57 |
-
|
| 58 |
-
useEffect(() => {
|
| 59 |
-
const controller = new AbortController();
|
| 60 |
-
void fetch(`${API_V1}/content-studio/studio?app=${encodeURIComponent(appId)}`,
|
| 61 |
-
{ credentials: CREDENTIALS, signal: controller.signal })
|
| 62 |
-
.then(async (response) => {
|
| 63 |
-
const body = await response.json().catch(() => null);
|
| 64 |
-
if (!response.ok) throw new Error(sentence(body, "This Content Studio could not be loaded. Reload to retry."));
|
| 65 |
-
setLoad({ phase: "ready", studio: body as Studio });
|
| 66 |
-
setMoved({});
|
| 67 |
-
})
|
| 68 |
-
.catch((failure: unknown) => {
|
| 69 |
-
if (controller.signal.aborted) return;
|
| 70 |
-
setLoad({ phase: "error",
|
| 71 |
-
message: failure instanceof Error ? failure.message : "This Content Studio could not be loaded. Reload to retry." });
|
| 72 |
-
});
|
| 73 |
-
return () => controller.abort();
|
| 74 |
-
}, [appId, epoch]);
|
| 75 |
-
|
| 76 |
-
// A draft written from the drawer lands in Posts; read the App again so it appears here.
|
| 77 |
-
useEffect(() => {
|
| 78 |
-
const reload = () => setEpoch((value) => value + 1);
|
| 79 |
-
window.addEventListener("aios:grid-refresh", reload);
|
| 80 |
-
return () => window.removeEventListener("aios:grid-refresh", reload);
|
| 81 |
-
}, []);
|
| 82 |
-
|
| 83 |
-
const studio = load.phase === "ready" ? load.studio : null;
|
| 84 |
-
const fieldByKey = useMemo(() => {
|
| 85 |
-
const map = new Map<string, Field>((studio?.posts.fields ?? []).map((field) => [field.key, field]));
|
| 86 |
-
map.set(TITLE_FIELD.key, TITLE_FIELD);
|
| 87 |
-
return map;
|
| 88 |
-
}, [studio]);
|
| 89 |
-
const rows: Row[] = useMemo(() => (studio?.posts.rows ?? []).map((post) => ({
|
| 90 |
-
...post, status: moved[post.pid] ?? post.status ?? null, title: titleOf(post),
|
| 91 |
-
}) as Row), [studio, moved]);
|
| 92 |
-
const scheduledField = fieldByKey.get("scheduled");
|
| 93 |
-
const statusField = fieldByKey.get("status");
|
| 94 |
-
const unscheduled = rows.filter((row) => !String(row.scheduled ?? "").trim());
|
| 95 |
-
const openPost = studio?.posts.rows.find((post) => post.pid === openPid) ?? null;
|
| 96 |
-
|
| 97 |
-
const postsDatabase = studio?.posts.database ?? "";
|
| 98 |
-
// KanbanView is memo'd and keeps its props stable on purpose, so both handlers are too.
|
| 99 |
-
const openCard = useCallback((pid: number) => setOpenPid(pid), []);
|
| 100 |
-
const move = useCallback((pid: number, value: string) => {
|
| 101 |
-
if (!postsDatabase) return;
|
| 102 |
-
setNotice("");
|
| 103 |
-
setMoved((current) => ({ ...current, [pid]: value }));
|
| 104 |
-
void fetch(`${API_V1}/tables/${encodeURIComponent(postsDatabase)}/rows/${pid}`, {
|
| 105 |
-
method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
|
| 106 |
-
body: JSON.stringify({ status: value }),
|
| 107 |
-
}).then(async (response) => {
|
| 108 |
-
if (!response.ok) throw new Error(sentence(await response.json().catch(() => null), "The post could not be moved. Try again."));
|
| 109 |
-
setEpoch((current) => current + 1);
|
| 110 |
-
}).catch((failure: unknown) => {
|
| 111 |
-
setMoved((current) => { const next = { ...current }; delete next[pid]; return next; });
|
| 112 |
-
setNotice(failure instanceof Error ? failure.message : "The post could not be moved. Try again.");
|
| 113 |
-
});
|
| 114 |
-
}, [postsDatabase]);
|
| 115 |
-
|
| 116 |
-
if (load.phase === "loading") {
|
| 117 |
-
return <div className="shell-home" data-content-studio-app={appId} aria-busy="true">
|
| 118 |
-
<div className="home-page-head"><h1 className="home-title">Content Studio</h1></div>
|
| 119 |
-
<div className="sheet-template-list" role="status" aria-label="Loading Content Studio">
|
| 120 |
-
{[0, 1, 2].map((row) => <div key={row} className="sheet-template-skeleton" aria-hidden="true">
|
| 121 |
-
<span className="sheet-template-skeleton-title" /><span className="sheet-template-skeleton-answer" />
|
| 122 |
-
</div>)}
|
| 123 |
-
</div>
|
| 124 |
-
</div>;
|
| 125 |
-
}
|
| 126 |
-
if (load.phase === "error" || !studio) {
|
| 127 |
-
return <div className="shell-home" data-content-studio-app={appId}>
|
| 128 |
-
<div className="home-page-head"><h1 className="home-title">Content Studio</h1></div>
|
| 129 |
-
<p className="shell-newdb-err" role="alert">{load.phase === "error" ? load.message : ""}</p>
|
| 130 |
-
</div>;
|
| 131 |
-
}
|
| 132 |
-
|
| 133 |
-
return <div className="shell-home" data-content-studio-app={appId}>
|
| 134 |
-
<div className="home-page-head" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
|
| 135 |
-
<div>
|
| 136 |
-
<h1 className="home-title">{studio.app.name}</h1>
|
| 137 |
-
<p className="home-empty" style={{ margin: "4px 0 0" }} data-content-studio-counts="">
|
| 138 |
-
{plural(studio.posts.rows.length, "post", "posts")} · {plural(studio.references.count, "reference", "references")}
|
| 139 |
-
</p>
|
| 140 |
-
</div>
|
| 141 |
-
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
|
| 142 |
-
<a className="lp-dialog-btn lp-dialog-btn-quiet" style={{ textDecoration: "none" }}
|
| 143 |
-
href={dataPathHash({ database: studio.references.database })}
|
| 144 |
-
title={`Open the ${studio.references.label} database this App drafts from`}>{studio.references.label}</a>
|
| 145 |
-
<a className="lp-dialog-btn lp-dialog-btn-quiet" style={{ textDecoration: "none" }}
|
| 146 |
-
href={dataPathHash({ database: studio.posts.database })}
|
| 147 |
-
title={`Open the ${studio.posts.label} database this App plans`}>{studio.posts.label}</a>
|
| 148 |
-
<button type="button" className="lp-dialog-btn lp-dialog-btn-primary" data-content-studio-draft-door=""
|
| 149 |
-
onClick={() => setDraftOpen(true)}>Draft posts</button>
|
| 150 |
-
</div>
|
| 151 |
-
</div>
|
| 152 |
-
|
| 153 |
-
{/* The same worded toggle the Templates picker uses (`home-layout-btn`, sized to its words). */}
|
| 154 |
-
<div className="home-layout-toggle" role="group" aria-label="Show posts as" style={{ margin: "4px 0 12px" }}>
|
| 155 |
-
{(["calendar", "board"] as const).map((value) => <button key={value} type="button"
|
| 156 |
-
className={"home-layout-btn" + (mode === value ? " is-on" : "")} aria-pressed={mode === value}
|
| 157 |
-
style={{ width: "auto", paddingInline: 12 }}
|
| 158 |
-
data-content-studio-mode={value} onClick={() => setMode(value)}>
|
| 159 |
-
{value === "calendar" ? "Calendar" : "Board"}
|
| 160 |
-
</button>)}
|
| 161 |
-
</div>
|
| 162 |
-
{notice ? <p className="shell-newdb-err" role="alert">{notice}</p> : null}
|
| 163 |
-
|
| 164 |
-
{mode === "calendar" ? <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) 300px", gap: 20, alignItems: "start" }}>
|
| 165 |
-
<div data-content-studio-calendar="" style={{ minWidth: 0 }}>
|
| 166 |
-
{!scheduledField ? <p className="home-empty">Posts has no Scheduled date field, so there is no calendar.</p>
|
| 167 |
-
: rows.length === 0 ? <p className="home-empty" data-content-studio-calendar-empty="">
|
| 168 |
-
No posts yet. Use Draft posts to write some from your references.</p>
|
| 169 |
-
: rows.length === unscheduled.length ? <p className="home-empty" data-content-studio-calendar-empty="">
|
| 170 |
-
No post is scheduled yet. Open one under Not scheduled to give it a date.</p>
|
| 171 |
-
: <CalendarView rows={rows} field={scheduledField} titleKey="title"
|
| 172 |
-
fieldByKey={fieldByKey} onOpen={openCard} />}
|
| 173 |
-
</div>
|
| 174 |
-
<section aria-label="Not scheduled" data-content-studio-unscheduled="" style={{ minWidth: 0, overflow: "hidden" }}>
|
| 175 |
-
<h2 className="home-section-title">Not scheduled</h2>
|
| 176 |
-
{unscheduled.length === 0 ? <p className="home-empty">
|
| 177 |
-
{rows.length === 0 ? "Nothing is waiting for a date." : "Every post has a date."}</p>
|
| 178 |
-
: <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "grid", gap: 8,
|
| 179 |
-
gridTemplateColumns: "minmax(0, 1fr)" }}>
|
| 180 |
-
{unscheduled.map((row) => <li key={row.pid} style={{ minWidth: 0 }}>
|
| 181 |
-
<button type="button" className="home-tile"
|
| 182 |
-
style={{ width: "100%", maxWidth: "100%", boxSizing: "border-box", minWidth: 0, textAlign: "left" }}
|
| 183 |
-
onClick={() => setOpenPid(row.pid)}>
|
| 184 |
-
<span className="home-tile-text" style={{ minWidth: 0, overflow: "hidden" }}>
|
| 185 |
-
<span className="home-tile-name">{String(row.title ?? "")}</span>
|
| 186 |
-
<span className="home-tile-ago">{String(row.status ?? "Idea")}</span>
|
| 187 |
-
</span>
|
| 188 |
-
</button>
|
| 189 |
-
</li>)}
|
| 190 |
-
</ul>}
|
| 191 |
-
</section>
|
| 192 |
-
</div> : statusField ? <div data-content-studio-board="">
|
| 193 |
-
<KanbanView rows={rows} field={statusField} fieldByKey={fieldByKey} cardKeys={["scheduled"]}
|
| 194 |
-
titleKey="title" canMove readOnlyReason={null} onMove={move} onOpen={openCard}
|
| 195 |
-
onAddOption={null} />
|
| 196 |
-
</div> : <p className="home-empty">Posts has no Status field, so there is no board.</p>}
|
| 197 |
-
|
| 198 |
-
{openPost ? <PostDrawer post={openPost} database={studio.posts.database} statuses={studio.statuses}
|
| 199 |
-
onClose={() => setOpenPid(null)} onSaved={() => { setOpenPid(null); setEpoch((value) => value + 1); }} /> : null}
|
| 200 |
-
{draftOpen ? <Suspense fallback={null}>
|
| 201 |
-
<DraftPanel appId={appId} onClose={() => setDraftOpen(false)} />
|
| 202 |
-
</Suspense> : null}
|
| 203 |
-
</div>;
|
| 204 |
-
}
|
| 205 |
-
|
| 206 |
-
/** One post: read its caption and credit, set its date and status. Saved through Posts' own row door. */
|
| 207 |
-
function PostDrawer({ post, database, statuses, onClose, onSaved }: {
|
| 208 |
-
post: StudioPost; database: string; statuses: string[]; onClose: () => void; onSaved: () => void;
|
| 209 |
-
}) {
|
| 210 |
-
const panelRef = useRef<HTMLDivElement>(null);
|
| 211 |
-
const titleId = useId();
|
| 212 |
-
const dateId = useId();
|
| 213 |
-
const statusId = useId();
|
| 214 |
-
const [scheduled, setScheduled] = useState(String(post.scheduled ?? "").slice(0, 10));
|
| 215 |
-
const [status, setStatus] = useState(String(post.status ?? "") || statuses[0] || "");
|
| 216 |
-
const [busy, setBusy] = useState(false);
|
| 217 |
-
const [error, setError] = useState("");
|
| 218 |
-
const dismiss = () => { if (!busy) onClose(); };
|
| 219 |
-
useOverlayLayer({ panelRef, onDismiss: dismiss, dismissOnOutside: false,
|
| 220 |
-
initialFocus: "[data-overlay-autofocus]", restoreFocus: true, trapFocus: true });
|
| 221 |
-
|
| 222 |
-
const save = async () => {
|
| 223 |
-
setBusy(true);
|
| 224 |
-
setError("");
|
| 225 |
-
try {
|
| 226 |
-
const response = await fetch(`${API_V1}/tables/${encodeURIComponent(database)}/rows/${post.pid}`, {
|
| 227 |
-
method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
|
| 228 |
-
body: JSON.stringify({ scheduled, status }),
|
| 229 |
-
});
|
| 230 |
-
if (!response.ok) throw new Error(sentence(await response.json().catch(() => null), "The post could not be saved. Try again."));
|
| 231 |
-
onSaved();
|
| 232 |
-
} catch (failure) {
|
| 233 |
-
setError(failure instanceof Error ? failure.message : "The post could not be saved. Try again.");
|
| 234 |
-
setBusy(false);
|
| 235 |
-
}
|
| 236 |
-
};
|
| 237 |
-
|
| 238 |
-
return <BodyPortal>
|
| 239 |
-
<div ref={panelRef} className="lp-dialog" role="dialog" aria-modal="true" aria-labelledby={titleId}
|
| 240 |
-
data-content-studio-post={post.pid} aria-busy={busy}
|
| 241 |
-
style={{ position: "fixed", top: 0, right: 0, bottom: 0, width: "min(420px, 100vw)", maxHeight: "100dvh",
|
| 242 |
-
borderRadius: 0, overflowY: "auto", zIndex: 60, boxShadow: "-12px 0 30px rgb(34 25 74 / 12%)" }}>
|
| 243 |
-
<div className="lp-dialog-head">
|
| 244 |
-
<h2 className="lp-dialog-title" id={titleId}>{post.channel ? `${post.channel} post` : "Post"}</h2>
|
| 245 |
-
<button type="button" className="lp-dialog-x" aria-label="Close" disabled={busy} onClick={dismiss}>
|
| 246 |
-
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">
|
| 247 |
-
<path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5" />
|
| 248 |
-
</svg>
|
| 249 |
-
</button>
|
| 250 |
-
</div>
|
| 251 |
-
<div className="lp-dialog-body">
|
| 252 |
-
<p style={{ whiteSpace: "pre-wrap", margin: 0 }}>{post.caption || "No caption yet."}</p>
|
| 253 |
-
{post.attribution ? <p className="home-empty" style={{ marginTop: 10 }}>{post.attribution}</p> : null}
|
| 254 |
-
<label htmlFor={dateId} style={{ display: "block", marginTop: 16, fontWeight: 600 }}>Scheduled</label>
|
| 255 |
-
<input id={dateId} className="cg-input" type="date" value={scheduled} disabled={busy} data-overlay-autofocus=""
|
| 256 |
-
onChange={(event) => setScheduled(event.target.value)} />
|
| 257 |
-
<label htmlFor={statusId} style={{ display: "block", marginTop: 12, fontWeight: 600 }}>Status</label>
|
| 258 |
-
<select id={statusId} className="cg-input" value={status} disabled={busy}
|
| 259 |
-
onChange={(event) => setStatus(event.target.value)}>
|
| 260 |
-
{statuses.map((value) => <option key={value} value={value}>{value}</option>)}
|
| 261 |
-
</select>
|
| 262 |
-
{error ? <p className="shell-newdb-err" role="alert">{error}</p> : null}
|
| 263 |
-
</div>
|
| 264 |
-
<div className="lp-dialog-actions">
|
| 265 |
-
<button type="button" className="lp-dialog-btn lp-dialog-btn-quiet" disabled={busy} onClick={dismiss}>Close</button>
|
| 266 |
-
<button type="button" className="lp-dialog-btn lp-dialog-btn-primary" disabled={busy}
|
| 267 |
-
data-content-studio-post-save="" onClick={() => void save()}>{busy ? "Saving…" : "Save"}</button>
|
| 268 |
-
</div>
|
| 269 |
-
</div>
|
| 270 |
-
</BodyPortal>;
|
| 271 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
web/src/apps/contentStudio/ContentStudioSetup.tsx
DELETED
|
@@ -1,83 +0,0 @@
|
|
| 1 |
-
import { useId, useRef, useState } from "react";
|
| 2 |
-
import { API_V1, CREDENTIALS } from "../../apiContract";
|
| 3 |
-
import { BodyPortal, useOverlayLayer } from "../../customer-grid/OverlaySurface";
|
| 4 |
-
|
| 5 |
-
/** The Templates catalogue key this dialog answers for (`content_studio.TEMPLATE_KEY`). */
|
| 6 |
-
export const CONTENT_STUDIO_TEMPLATE_KEY = "content_studio";
|
| 7 |
-
|
| 8 |
-
/**
|
| 9 |
-
* S67-T40 (R21, O2): Content Studio's create-for-me step, IN PLACE of "Choose a database". The
|
| 10 |
-
* template makes its own tenant-owned References and Posts databases, so there is nothing to
|
| 11 |
-
* choose; this dialog names what will be created and hands back the App's address.
|
| 12 |
-
*/
|
| 13 |
-
export default function ContentStudioSetup({ onCancel, onCreated }: {
|
| 14 |
-
onCancel: () => void;
|
| 15 |
-
onCreated: (address: string) => void;
|
| 16 |
-
}) {
|
| 17 |
-
const panelRef = useRef<HTMLDivElement>(null);
|
| 18 |
-
const titleId = useId();
|
| 19 |
-
const nameId = useId();
|
| 20 |
-
const [name, setName] = useState("Content Studio");
|
| 21 |
-
const [busy, setBusy] = useState(false);
|
| 22 |
-
const [error, setError] = useState("");
|
| 23 |
-
const dismiss = () => { if (!busy) onCancel(); };
|
| 24 |
-
useOverlayLayer({ panelRef, onDismiss: dismiss, dismissOnOutside: false,
|
| 25 |
-
initialFocus: "[data-overlay-autofocus]", restoreFocus: true, trapFocus: true });
|
| 26 |
-
|
| 27 |
-
const create = async () => {
|
| 28 |
-
if (busy) return;
|
| 29 |
-
setBusy(true);
|
| 30 |
-
setError("");
|
| 31 |
-
try {
|
| 32 |
-
const response = await fetch(`${API_V1}/templates/app/${CONTENT_STUDIO_TEMPLATE_KEY}`, {
|
| 33 |
-
method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
|
| 34 |
-
body: JSON.stringify({ name }),
|
| 35 |
-
});
|
| 36 |
-
const body = await response.json().catch(() => null);
|
| 37 |
-
if (!response.ok || typeof body?.address !== "string") {
|
| 38 |
-
throw new Error(body?.error?.message || body?.detail?.error?.message
|
| 39 |
-
|| "Content Studio could not be created. Nothing was changed. Try again.");
|
| 40 |
-
}
|
| 41 |
-
window.dispatchEvent(new Event("aios:applications-changed"));
|
| 42 |
-
onCreated(body.address);
|
| 43 |
-
} catch (failure) {
|
| 44 |
-
setError(failure instanceof Error ? failure.message : "Content Studio could not be created. Try again.");
|
| 45 |
-
setBusy(false);
|
| 46 |
-
}
|
| 47 |
-
};
|
| 48 |
-
|
| 49 |
-
return <BodyPortal>
|
| 50 |
-
<div className="lp-dialog-scrim">
|
| 51 |
-
<div ref={panelRef} className="lp-dialog" role="dialog" aria-modal="true" aria-labelledby={titleId}
|
| 52 |
-
aria-busy={busy} style={{ width: "min(520px, calc(100vw - 32px))" }}>
|
| 53 |
-
<div className="lp-dialog-head">
|
| 54 |
-
<h2 className="lp-dialog-title" id={titleId}>Content Studio</h2>
|
| 55 |
-
<button type="button" className="lp-dialog-x" aria-label="Close" disabled={busy} onClick={dismiss}>
|
| 56 |
-
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">
|
| 57 |
-
<path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5" />
|
| 58 |
-
</svg>
|
| 59 |
-
</button>
|
| 60 |
-
</div>
|
| 61 |
-
<div className="lp-dialog-body">
|
| 62 |
-
<p>This creates two databases in this workspace, then opens a calendar of your posts.</p>
|
| 63 |
-
<ul data-content-studio-databases="">
|
| 64 |
-
<li><strong>References</strong>: URL, network, author, pasted text, tags, hook, structure and angle.</li>
|
| 65 |
-
<li><strong>Posts</strong>: caption, channel, scheduled date, status, media, campaign, post URL, references and attribution.</li>
|
| 66 |
-
</ul>
|
| 67 |
-
<label htmlFor={nameId}>App name</label>
|
| 68 |
-
<input id={nameId} className="cg-input" type="text" value={name} maxLength={120}
|
| 69 |
-
disabled={busy} onChange={(event) => setName(event.target.value)} />
|
| 70 |
-
{error ? <p className="shell-newdb-err" role="alert">{error}</p> : null}
|
| 71 |
-
</div>
|
| 72 |
-
<div className="lp-dialog-actions">
|
| 73 |
-
<button type="button" className="lp-dialog-btn lp-dialog-btn-quiet" data-overlay-autofocus=""
|
| 74 |
-
disabled={busy} onClick={dismiss}>Cancel</button>
|
| 75 |
-
<button type="button" className="lp-dialog-btn lp-dialog-btn-primary"
|
| 76 |
-
disabled={busy || !name.trim()} onClick={() => void create()}>
|
| 77 |
-
{busy ? "Creating…" : "Create"}
|
| 78 |
-
</button>
|
| 79 |
-
</div>
|
| 80 |
-
</div>
|
| 81 |
-
</div>
|
| 82 |
-
</BodyPortal>;
|
| 83 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
web/src/apps/contentStudio/DraftPanel.tsx
DELETED
|
@@ -1,179 +0,0 @@
|
|
| 1 |
-
import { useEffect, useId, useRef, useState } from "react";
|
| 2 |
-
import { API_V1, CREDENTIALS } from "../../apiContract";
|
| 3 |
-
import { BodyPortal, useOverlayLayer } from "../../customer-grid/OverlaySurface";
|
| 4 |
-
|
| 5 |
-
interface StudioReference { id: string; title: string; author: string; network: string; extracted: boolean }
|
| 6 |
-
interface Drafted { channel: string; caption: string }
|
| 7 |
-
/** S67-T42 (R35): this workspace's monthly drafting allowance, as the server counts it. */
|
| 8 |
-
interface Allowance { used: number; limit: number; remaining: number; resetsOn: string; paused: boolean; message: string }
|
| 9 |
-
|
| 10 |
-
/** The server's own sentence first (top-level `error.message`), then the legacy nesting. */
|
| 11 |
-
const sentence = (body: unknown, fallback: string): string => {
|
| 12 |
-
const row = body as { error?: { message?: string }; detail?: { error?: { message?: string } } } | null;
|
| 13 |
-
return row?.error?.message || row?.detail?.error?.message || fallback;
|
| 14 |
-
};
|
| 15 |
-
|
| 16 |
-
const listed = (names: string[]): string =>
|
| 17 |
-
names.length <= 1 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
|
| 18 |
-
|
| 19 |
-
/**
|
| 20 |
-
* S67-T41 (R13-R15, R19, R20, R5, O4): Content Studio's drafting drawer. Several References plus
|
| 21 |
-
* a one-line topic become one Draft row per chosen channel in Posts, written from the references'
|
| 22 |
-
* extracted structure and crediting their authors. Plan-only: nothing is published.
|
| 23 |
-
*/
|
| 24 |
-
export default function DraftPanel({ appId, onClose }: { appId: string; onClose: () => void }) {
|
| 25 |
-
const panelRef = useRef<HTMLDivElement>(null);
|
| 26 |
-
const titleId = useId();
|
| 27 |
-
const topicId = useId();
|
| 28 |
-
const [phase, setPhase] = useState<"loading" | "ready" | "error">("loading");
|
| 29 |
-
const [loadError, setLoadError] = useState("");
|
| 30 |
-
const [references, setReferences] = useState<StudioReference[]>([]);
|
| 31 |
-
const [channels, setChannels] = useState<string[]>([]);
|
| 32 |
-
const [advice, setAdvice] = useState<Record<string, string>>({});
|
| 33 |
-
const [selected, setSelected] = useState<string[]>([]);
|
| 34 |
-
const [chosen, setChosen] = useState<string[]>([]);
|
| 35 |
-
const [topic, setTopic] = useState("");
|
| 36 |
-
const [busy, setBusy] = useState(false);
|
| 37 |
-
const [error, setError] = useState("");
|
| 38 |
-
const [drafted, setDrafted] = useState<Drafted[]>([]);
|
| 39 |
-
const [allowance, setAllowance] = useState<Allowance | null>(null);
|
| 40 |
-
const dismiss = () => { if (!busy) onClose(); };
|
| 41 |
-
useOverlayLayer({ panelRef, onDismiss: dismiss, dismissOnOutside: false,
|
| 42 |
-
initialFocus: "[data-overlay-autofocus]", restoreFocus: true, trapFocus: true });
|
| 43 |
-
|
| 44 |
-
useEffect(() => {
|
| 45 |
-
const controller = new AbortController();
|
| 46 |
-
void fetch(`${API_V1}/content-studio/references?app=${encodeURIComponent(appId)}`,
|
| 47 |
-
{ credentials: CREDENTIALS, signal: controller.signal })
|
| 48 |
-
.then(async (response) => {
|
| 49 |
-
const body = await response.json().catch(() => null);
|
| 50 |
-
if (!response.ok) throw new Error(sentence(body, "References could not be loaded. Try again."));
|
| 51 |
-
setReferences(Array.isArray(body?.references) ? body.references : []);
|
| 52 |
-
setChannels(Array.isArray(body?.channels) ? body.channels : []);
|
| 53 |
-
setAdvice(body?.advice && typeof body.advice === "object" ? body.advice : {});
|
| 54 |
-
setAllowance(body?.allowance && typeof body.allowance === "object" ? body.allowance : null);
|
| 55 |
-
setPhase("ready");
|
| 56 |
-
})
|
| 57 |
-
.catch((failure: unknown) => {
|
| 58 |
-
if (controller.signal.aborted) return;
|
| 59 |
-
setLoadError(failure instanceof Error ? failure.message : "References could not be loaded. Try again.");
|
| 60 |
-
setPhase("error");
|
| 61 |
-
});
|
| 62 |
-
return () => controller.abort();
|
| 63 |
-
}, [appId]);
|
| 64 |
-
|
| 65 |
-
const toggle = (list: string[], value: string) =>
|
| 66 |
-
list.includes(value) ? list.filter((item) => item !== value) : [...list, value];
|
| 67 |
-
// NC: Draft stays disabled, WITH the reason, until every input it needs is there.
|
| 68 |
-
// R35: a used allowance pauses Draft and says when it resets, ahead of every other reason.
|
| 69 |
-
const reason = allowance?.paused ? allowance.message
|
| 70 |
-
: selected.length === 0 ? "Select at least one reference to draft from."
|
| 71 |
-
: !topic.trim() ? "Type a one-line topic for the draft."
|
| 72 |
-
: chosen.length === 0 ? "Choose at least one channel." : "";
|
| 73 |
-
|
| 74 |
-
const draft = async () => {
|
| 75 |
-
if (busy || reason) return;
|
| 76 |
-
setBusy(true);
|
| 77 |
-
setError("");
|
| 78 |
-
setDrafted([]);
|
| 79 |
-
try {
|
| 80 |
-
const response = await fetch(`${API_V1}/content-studio/draft`, {
|
| 81 |
-
method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
|
| 82 |
-
body: JSON.stringify({ app: appId, references: selected, topic, channels: chosen }),
|
| 83 |
-
});
|
| 84 |
-
const body = await response.json().catch(() => null);
|
| 85 |
-
if (response.status === 429 && body?.error?.code === "drafting_allowance_used") {
|
| 86 |
-
const message = sentence(body, "This workspace has used this month's drafting allowance.");
|
| 87 |
-
setAllowance((current) => current ? { ...current, remaining: 0, paused: true, message }
|
| 88 |
-
: { used: 0, limit: 0, remaining: 0, resetsOn: "", paused: true, message });
|
| 89 |
-
}
|
| 90 |
-
if (!response.ok) throw new Error(sentence(body, "The drafts could not be written. Nothing was saved."));
|
| 91 |
-
const made: Drafted[] = Array.isArray(body?.drafts) ? body.drafts : [];
|
| 92 |
-
setDrafted(made);
|
| 93 |
-
// The server owns the count and its sentence: re-read it rather than guess it here.
|
| 94 |
-
void fetch(`${API_V1}/content-studio/references?app=${encodeURIComponent(appId)}`, { credentials: CREDENTIALS })
|
| 95 |
-
.then((reply) => reply.ok ? reply.json() : null)
|
| 96 |
-
.then((fresh) => { if (fresh?.allowance && typeof fresh.allowance === "object") setAllowance(fresh.allowance); })
|
| 97 |
-
.catch(() => undefined);
|
| 98 |
-
window.dispatchEvent(new Event("aios:grid-refresh"));
|
| 99 |
-
} catch (failure) {
|
| 100 |
-
setError(failure instanceof Error ? failure.message : "The drafts could not be written. Nothing was saved.");
|
| 101 |
-
} finally {
|
| 102 |
-
setBusy(false);
|
| 103 |
-
}
|
| 104 |
-
};
|
| 105 |
-
|
| 106 |
-
return <BodyPortal>
|
| 107 |
-
<div ref={panelRef} className="lp-dialog" role="dialog" aria-modal="true" aria-labelledby={titleId}
|
| 108 |
-
data-content-studio-draft="" aria-busy={busy}
|
| 109 |
-
style={{ position: "fixed", top: 0, right: 0, bottom: 0, width: "min(420px, 100vw)", maxHeight: "100dvh",
|
| 110 |
-
borderRadius: 0, overflowY: "auto", zIndex: 60, boxShadow: "-12px 0 30px rgb(34 25 74 / 12%)" }}>
|
| 111 |
-
<div className="lp-dialog-head">
|
| 112 |
-
<h2 className="lp-dialog-title" id={titleId}>Draft posts</h2>
|
| 113 |
-
<button type="button" className="lp-dialog-x" aria-label="Close" disabled={busy} onClick={dismiss}>
|
| 114 |
-
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">
|
| 115 |
-
<path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5" />
|
| 116 |
-
</svg>
|
| 117 |
-
</button>
|
| 118 |
-
</div>
|
| 119 |
-
<div className="lp-dialog-body">
|
| 120 |
-
<h3 className="home-section-title">References</h3>
|
| 121 |
-
{phase === "loading" ? <div className="sheet-template-list" role="status" aria-label="Loading references">
|
| 122 |
-
{[0, 1, 2].map((row) => <div key={row} className="sheet-template-skeleton" aria-hidden="true">
|
| 123 |
-
<span className="sheet-template-skeleton-title" /><span className="sheet-template-skeleton-answer" />
|
| 124 |
-
</div>)}
|
| 125 |
-
</div> : phase === "error" ? <p className="shell-newdb-err" role="alert">{loadError}</p>
|
| 126 |
-
: references.length === 0 ? <p className="home-empty">No references yet. Add one to References, then paste its text.</p>
|
| 127 |
-
: <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 6 }}>
|
| 128 |
-
{references.map((row) => <li key={row.id}>
|
| 129 |
-
<label style={{ display: "flex", gap: 8, alignItems: "flex-start" }}>
|
| 130 |
-
<input type="checkbox" checked={selected.includes(row.id)} disabled={busy}
|
| 131 |
-
onChange={() => setSelected((list) => toggle(list, row.id))} />
|
| 132 |
-
<span>
|
| 133 |
-
<span style={{ display: "block", fontWeight: 600 }}>{row.title}</span>
|
| 134 |
-
<span style={{ display: "block", color: "var(--lp-ink-2, inherit)" }}>
|
| 135 |
-
{[row.author, row.network].filter(Boolean).join(" · ")}
|
| 136 |
-
{row.extracted ? "" : " · structure not extracted yet"}
|
| 137 |
-
</span>
|
| 138 |
-
</span>
|
| 139 |
-
</label>
|
| 140 |
-
</li>)}
|
| 141 |
-
</ul>}
|
| 142 |
-
<label htmlFor={topicId} style={{ display: "block", marginTop: 14, fontWeight: 600 }}>Topic</label>
|
| 143 |
-
<input id={topicId} className="cg-input" type="text" maxLength={200} value={topic} disabled={busy}
|
| 144 |
-
data-overlay-autofocus="" placeholder="One line: what the post is about"
|
| 145 |
-
style={{ width: "100%", boxSizing: "border-box" }} onChange={(event) => setTopic(event.target.value)} />
|
| 146 |
-
<fieldset style={{ border: 0, padding: 0, margin: "14px 0 0" }}>
|
| 147 |
-
<legend style={{ fontWeight: 600 }}>Channels</legend>
|
| 148 |
-
<div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
|
| 149 |
-
{channels.map((channel) => <label key={channel} style={{ display: "flex", gap: 6, alignItems: "center" }}>
|
| 150 |
-
<input type="checkbox" checked={chosen.includes(channel)} disabled={busy}
|
| 151 |
-
onChange={() => setChosen((list) => toggle(list, channel))} />{channel}
|
| 152 |
-
</label>)}
|
| 153 |
-
</div>
|
| 154 |
-
</fieldset>
|
| 155 |
-
{chosen.length ? <ul style={{ margin: "8px 0 0", paddingLeft: 18 }} aria-label="Channel guidance">
|
| 156 |
-
{chosen.map((channel) => <li key={channel}>{advice[channel] || channel}</li>)}
|
| 157 |
-
</ul> : null}
|
| 158 |
-
{reason ? <p className="home-empty" data-draft-reason="">{reason}</p> : null}
|
| 159 |
-
{busy ? <p role="status" aria-live="polite">Drafting {listed(chosen)}…</p> : null}
|
| 160 |
-
{error ? <p className="shell-newdb-err" role="alert">{error}</p> : null}
|
| 161 |
-
{drafted.length ? <div data-drafted="" aria-live="polite">
|
| 162 |
-
<p><strong>{drafted.length === 1 ? "1 draft" : `${drafted.length} drafts`} added to Posts as Draft.</strong></p>
|
| 163 |
-
<ul style={{ paddingLeft: 18 }}>
|
| 164 |
-
{drafted.map((row) => <li key={row.channel}><strong>{row.channel}</strong>: {row.caption.slice(0, 160)}{row.caption.length > 160 ? "…" : ""}</li>)}
|
| 165 |
-
</ul>
|
| 166 |
-
</div> : null}
|
| 167 |
-
</div>
|
| 168 |
-
<div className="lp-dialog-actions">
|
| 169 |
-
<button type="button" className="lp-dialog-btn lp-dialog-btn-quiet" disabled={busy} onClick={dismiss}>Close</button>
|
| 170 |
-
<button type="button" className="lp-dialog-btn lp-dialog-btn-primary" disabled={busy || !!reason}
|
| 171 |
-
title={reason || undefined} onClick={() => void draft()}>{busy ? "Drafting…" : "Draft"}</button>
|
| 172 |
-
</div>
|
| 173 |
-
{allowance && !allowance.paused ? <p className="home-empty" data-draft-allowance=""
|
| 174 |
-
style={{ marginTop: 8, textAlign: "right" }}>
|
| 175 |
-
{allowance.used} of {allowance.limit} drafts used this month
|
| 176 |
-
</p> : null}
|
| 177 |
-
</div>
|
| 178 |
-
</BodyPortal>;
|
| 179 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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-1,414 +0,0 @@
|
|
| 1 |
-
/**
|
| 2 |
-
* SavedChartNav.tsx — W47-T31 (owner R7, contract C6): the Time series view's right-side
|
| 3 |
-
* navigator over SAVED CHARTS.
|
| 4 |
-
*
|
| 5 |
-
* ⭐ **A SAVED CHART IS A RECORD, NOT A VIEW SETTING (C6).** It carries its own id, name and
|
| 6 |
-
* owner on the server (`/api/v1/charts`, `core.chart_system`) and is listed independently of
|
| 7 |
-
* `ws["views"]`. That is the whole point of R7, in the owner's words: *"every interface like
|
| 8 |
-
* chart, swap etc. that we need to configure should act like route with the right side
|
| 9 |
-
* navigation to choose the specific view we want to see. So its not pegged on a per view
|
| 10 |
-
* basis."* Deleting a view therefore cannot delete a chart, and one chart is reachable from
|
| 11 |
-
* every view on the same database.
|
| 12 |
-
*
|
| 13 |
-
* ⛔ THIS FILE OWNS NO DISPLAY STATE. `TimeSeriesPanel` is fully controlled by its `display`
|
| 14 |
-
* prop, so "open this chart" is exactly one `onApply(...)` call that the panel forwards to
|
| 15 |
-
* `onDisplay`. A second copy of the bucket/span/field state here would be a second answer to
|
| 16 |
-
* the question the view already answers, and the two would drift on the first save.
|
| 17 |
-
*
|
| 18 |
-
* ⚠ NO STYLESHEET OF ITS OWN, ON PURPOSE. `.cg-workspace-drawer` is the shipped right-side
|
| 19 |
-
* drawer idiom (`styles/wave45/data-applications.css`, imported by `CustomerGrid.tsx`) and
|
| 20 |
-
* `.cg-history-list` is that drawer's own list rule: a bordered row of `1fr auto`, which is a
|
| 21 |
-
* name on the left and its actions on the right. Both are reused rather than re-declared, so
|
| 22 |
-
* this navigator cannot drift from the drawer beside it and `verify_reachability`'s
|
| 23 |
-
* orphan-stylesheet lens has nothing new to find. The `cg-history-list` NAME is inherited from
|
| 24 |
-
* its first caller and describes its shape, not its subject.
|
| 25 |
-
*/
|
| 26 |
-
import { useCallback, useEffect, useState } from "react";
|
| 27 |
-
import { API_V1, CREDENTIALS } from "../apiContract";
|
| 28 |
-
import { MenuIcon } from "./icons";
|
| 29 |
-
import { cleanDisplay } from "./types";
|
| 30 |
-
import type { DisplaySpec } from "./types";
|
| 31 |
-
|
| 32 |
-
/**
|
| 33 |
-
* The display keys a time-series chart owns, and the ONLY ones it may write back.
|
| 34 |
-
*
|
| 35 |
-
* ⛔ EVERY KEY IS ALWAYS PRESENT, `undefined` when the chart does not carry it. The host merges
|
| 36 |
-
* with `{ ...spec, ...next }` and persists through `JSON.stringify`, so an explicitly
|
| 37 |
-
* `undefined` key DELETES the stored one. Omitting a key instead would leave a toggle from the
|
| 38 |
-
* previously loaded chart switched on under a configuration that never asked for it.
|
| 39 |
-
*/
|
| 40 |
-
export type TsChartConfig = Pick<
|
| 41 |
-
DisplaySpec,
|
| 42 |
-
| "tsFields"
|
| 43 |
-
| "tsMetrics"
|
| 44 |
-
| "tsBucket"
|
| 45 |
-
| "tsSpan"
|
| 46 |
-
| "tsDeltas"
|
| 47 |
-
| "tsStyles"
|
| 48 |
-
| "tsGridlines"
|
| 49 |
-
| "tsSparkline"
|
| 50 |
-
| "tsRows"
|
| 51 |
-
>;
|
| 52 |
-
|
| 53 |
-
/** One row of `GET /api/v1/charts`, after narrowing. `config` stays opaque here (C6). */
|
| 54 |
-
export interface SavedChartRecord {
|
| 55 |
-
id: string;
|
| 56 |
-
name: string;
|
| 57 |
-
database: string;
|
| 58 |
-
kind: string;
|
| 59 |
-
config: Record<string, unknown>;
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
-
/** `chart_system._MAX_NAME`. Said here so the field stops the user rather than the server. */
|
| 63 |
-
const NAME_MAX = 120;
|
| 64 |
-
const CHART_KIND = "timeseries";
|
| 65 |
-
const JSON_HEADERS = { "Content-Type": "application/json" };
|
| 66 |
-
|
| 67 |
-
const LOAD_FAILED = "Saved charts could not be loaded.";
|
| 68 |
-
|
| 69 |
-
/**
|
| 70 |
-
* A stored config, narrowed into the eight keys this panel owns.
|
| 71 |
-
*
|
| 72 |
-
* ⭐ `cleanDisplay` IS THE NARROWER, rather than a second validator written here. It is the
|
| 73 |
-
* same function the View reader uses, it already knows every asymmetry these keys carry
|
| 74 |
-
* (`tsGridlines` is the literal `false`, `tsSparkline` the literal `true`, `tsSpan.lastN` is
|
| 75 |
-
* bounded), and a private copy would be a second set of rules for one question. It needs a
|
| 76 |
-
* legal `mode` to return anything at all, so one is supplied: the record's `kind` already says
|
| 77 |
-
* what this config is, and the stored blob is not required to repeat it.
|
| 78 |
-
*/
|
| 79 |
-
export function tsChartConfigFrom(raw: unknown): TsChartConfig {
|
| 80 |
-
const source = raw && typeof raw === "object" && !Array.isArray(raw)
|
| 81 |
-
? (raw as Record<string, unknown>)
|
| 82 |
-
: {};
|
| 83 |
-
const spec = cleanDisplay({ ...source, mode: "timeseries" });
|
| 84 |
-
return {
|
| 85 |
-
tsFields: spec?.tsFields,
|
| 86 |
-
tsMetrics: spec?.tsMetrics,
|
| 87 |
-
tsBucket: spec?.tsBucket,
|
| 88 |
-
tsSpan: spec?.tsSpan,
|
| 89 |
-
tsDeltas: spec?.tsDeltas,
|
| 90 |
-
tsStyles: spec?.tsStyles,
|
| 91 |
-
tsGridlines: spec?.tsGridlines,
|
| 92 |
-
tsSparkline: spec?.tsSparkline,
|
| 93 |
-
tsRows: spec?.tsRows,
|
| 94 |
-
};
|
| 95 |
-
}
|
| 96 |
-
|
| 97 |
-
function readChart(raw: unknown): SavedChartRecord | null {
|
| 98 |
-
if (!raw || typeof raw !== "object") return null;
|
| 99 |
-
const row = raw as Record<string, unknown>;
|
| 100 |
-
const id = typeof row.id === "string" ? row.id : "";
|
| 101 |
-
const name = typeof row.name === "string" ? row.name : "";
|
| 102 |
-
if (!id || !name) return null;
|
| 103 |
-
return {
|
| 104 |
-
id,
|
| 105 |
-
name,
|
| 106 |
-
database: typeof row.database === "string" ? row.database : "",
|
| 107 |
-
kind: typeof row.kind === "string" ? row.kind : CHART_KIND,
|
| 108 |
-
config: row.config && typeof row.config === "object" && !Array.isArray(row.config)
|
| 109 |
-
? (row.config as Record<string, unknown>)
|
| 110 |
-
: {},
|
| 111 |
-
};
|
| 112 |
-
}
|
| 113 |
-
|
| 114 |
-
export interface SavedChartNavProps {
|
| 115 |
-
/** The DATABASE key these charts belong to, never a `SurfaceScope`. */
|
| 116 |
-
database: string;
|
| 117 |
-
/** The configuration a save would capture: the RESOLVED one now on screen. */
|
| 118 |
-
current: TsChartConfig;
|
| 119 |
-
/** Apply a saved chart. Always receives all eight keys, so stale ones are cleared. */
|
| 120 |
-
onApply: (config: TsChartConfig) => void;
|
| 121 |
-
/** The id last applied from here, so the list can say which chart is on screen. */
|
| 122 |
-
activeId: string | null;
|
| 123 |
-
onActiveId: (id: string | null) => void;
|
| 124 |
-
onClose: () => void;
|
| 125 |
-
}
|
| 126 |
-
|
| 127 |
-
export default function SavedChartNav({
|
| 128 |
-
database,
|
| 129 |
-
current,
|
| 130 |
-
onApply,
|
| 131 |
-
activeId,
|
| 132 |
-
onActiveId,
|
| 133 |
-
onClose,
|
| 134 |
-
}: SavedChartNavProps) {
|
| 135 |
-
const [charts, setCharts] = useState<SavedChartRecord[]>([]);
|
| 136 |
-
const [loading, setLoading] = useState(false);
|
| 137 |
-
const [error, setError] = useState("");
|
| 138 |
-
const [busy, setBusy] = useState(false);
|
| 139 |
-
const [reload, setReload] = useState(0);
|
| 140 |
-
const [newName, setNewName] = useState("");
|
| 141 |
-
const [renaming, setRenaming] = useState<string | null>(null);
|
| 142 |
-
const [renameText, setRenameText] = useState("");
|
| 143 |
-
const [deleting, setDeleting] = useState<string | null>(null);
|
| 144 |
-
|
| 145 |
-
// The list is re-keyed on `database`: switching grids asks a different question, and showing
|
| 146 |
-
// the previous database's charts for one paint would invite a click that then 403s.
|
| 147 |
-
useEffect(() => {
|
| 148 |
-
if (!database) {
|
| 149 |
-
setCharts([]);
|
| 150 |
-
return;
|
| 151 |
-
}
|
| 152 |
-
const controller = new AbortController();
|
| 153 |
-
setLoading(true);
|
| 154 |
-
void fetch(`${API_V1}/charts?database=${encodeURIComponent(database)}`, {
|
| 155 |
-
credentials: CREDENTIALS,
|
| 156 |
-
signal: controller.signal,
|
| 157 |
-
})
|
| 158 |
-
.then(async (response) => ({ ok: response.ok, body: await response.json().catch(() => ({})) }))
|
| 159 |
-
.then(({ ok, body }) => {
|
| 160 |
-
if (controller.signal.aborted) return;
|
| 161 |
-
if (!ok) {
|
| 162 |
-
setCharts([]);
|
| 163 |
-
setError(LOAD_FAILED);
|
| 164 |
-
return;
|
| 165 |
-
}
|
| 166 |
-
const rows = Array.isArray((body as { charts?: unknown })?.charts)
|
| 167 |
-
? ((body as { charts: unknown[] }).charts)
|
| 168 |
-
: [];
|
| 169 |
-
setCharts(rows.map(readChart).filter((row): row is SavedChartRecord => row !== null));
|
| 170 |
-
setError("");
|
| 171 |
-
})
|
| 172 |
-
.catch(() => {
|
| 173 |
-
if (!controller.signal.aborted) setError(LOAD_FAILED);
|
| 174 |
-
})
|
| 175 |
-
.finally(() => {
|
| 176 |
-
if (!controller.signal.aborted) setLoading(false);
|
| 177 |
-
});
|
| 178 |
-
return () => controller.abort();
|
| 179 |
-
}, [database, reload]);
|
| 180 |
-
|
| 181 |
-
const refresh = useCallback(() => setReload((n) => n + 1), []);
|
| 182 |
-
|
| 183 |
-
/**
|
| 184 |
-
* Create. ⛔ NO `id` IN THE BODY: the server refuses one with `server_managed_chart_id`,
|
| 185 |
-
* deliberately, so that POST cannot become an undocumented update door.
|
| 186 |
-
*
|
| 187 |
-
* The list is REFETCHED rather than prepended. The server sorts by name then id, so a
|
| 188 |
-
* prepended row would sit somewhere the next reload does not reproduce.
|
| 189 |
-
*/
|
| 190 |
-
const save = useCallback(async () => {
|
| 191 |
-
const name = newName.trim().slice(0, NAME_MAX);
|
| 192 |
-
if (!name || !database) return;
|
| 193 |
-
setBusy(true);
|
| 194 |
-
try {
|
| 195 |
-
const response = await fetch(`${API_V1}/charts`, {
|
| 196 |
-
method: "POST",
|
| 197 |
-
credentials: CREDENTIALS,
|
| 198 |
-
headers: JSON_HEADERS,
|
| 199 |
-
body: JSON.stringify({ kind: CHART_KIND, database, name, config: current }),
|
| 200 |
-
});
|
| 201 |
-
if (!response.ok) {
|
| 202 |
-
setError("That chart could not be saved. Nothing was stored.");
|
| 203 |
-
return;
|
| 204 |
-
}
|
| 205 |
-
const body = await response.json().catch(() => ({}));
|
| 206 |
-
const made = readChart((body as { chart?: unknown })?.chart);
|
| 207 |
-
if (made) onActiveId(made.id);
|
| 208 |
-
setNewName("");
|
| 209 |
-
setError("");
|
| 210 |
-
refresh();
|
| 211 |
-
} catch {
|
| 212 |
-
setError("That chart could not be saved. Nothing was stored.");
|
| 213 |
-
} finally {
|
| 214 |
-
setBusy(false);
|
| 215 |
-
}
|
| 216 |
-
}, [current, database, newName, onActiveId, refresh]);
|
| 217 |
-
|
| 218 |
-
/** Rename. ⛔ `database` is never sent: the server holds it prior-wins and a payload naming
|
| 219 |
-
* another one would be a permission escape rather than a move. */
|
| 220 |
-
const rename = useCallback(async (chart: SavedChartRecord) => {
|
| 221 |
-
const name = renameText.trim().slice(0, NAME_MAX);
|
| 222 |
-
if (!name) return;
|
| 223 |
-
setBusy(true);
|
| 224 |
-
try {
|
| 225 |
-
const response = await fetch(`${API_V1}/charts/${encodeURIComponent(chart.id)}`, {
|
| 226 |
-
method: "PATCH",
|
| 227 |
-
credentials: CREDENTIALS,
|
| 228 |
-
headers: JSON_HEADERS,
|
| 229 |
-
body: JSON.stringify({ name }),
|
| 230 |
-
});
|
| 231 |
-
if (!response.ok) {
|
| 232 |
-
setError("That chart could not be renamed. Its old name is still in place.");
|
| 233 |
-
return;
|
| 234 |
-
}
|
| 235 |
-
setRenaming(null);
|
| 236 |
-
setError("");
|
| 237 |
-
refresh();
|
| 238 |
-
} catch {
|
| 239 |
-
setError("That chart could not be renamed. Its old name is still in place.");
|
| 240 |
-
} finally {
|
| 241 |
-
setBusy(false);
|
| 242 |
-
}
|
| 243 |
-
}, [refresh, renameText]);
|
| 244 |
-
|
| 245 |
-
const remove = useCallback(async (chart: SavedChartRecord) => {
|
| 246 |
-
setBusy(true);
|
| 247 |
-
try {
|
| 248 |
-
const response = await fetch(`${API_V1}/charts/${encodeURIComponent(chart.id)}`, {
|
| 249 |
-
method: "DELETE",
|
| 250 |
-
credentials: CREDENTIALS,
|
| 251 |
-
});
|
| 252 |
-
if (!response.ok) {
|
| 253 |
-
setError("That chart could not be deleted. It is still saved.");
|
| 254 |
-
return;
|
| 255 |
-
}
|
| 256 |
-
setDeleting(null);
|
| 257 |
-
setError("");
|
| 258 |
-
if (activeId === chart.id) onActiveId(null);
|
| 259 |
-
refresh();
|
| 260 |
-
} catch {
|
| 261 |
-
setError("That chart could not be deleted. It is still saved.");
|
| 262 |
-
} finally {
|
| 263 |
-
setBusy(false);
|
| 264 |
-
}
|
| 265 |
-
}, [activeId, onActiveId, refresh]);
|
| 266 |
-
|
| 267 |
-
const canSave = !!newName.trim() && !busy && !!database;
|
| 268 |
-
|
| 269 |
-
return (
|
| 270 |
-
<section className="cg-workspace-drawer" aria-label="Saved charts">
|
| 271 |
-
<header>
|
| 272 |
-
<strong>Saved charts</strong>
|
| 273 |
-
<button type="button" className="cg-btn" onClick={onClose}>
|
| 274 |
-
Close
|
| 275 |
-
</button>
|
| 276 |
-
</header>
|
| 277 |
-
|
| 278 |
-
{loading && <span className="lp-spin" role="status" aria-label="Loading saved charts" />}
|
| 279 |
-
{error && <p role="alert">{error}</p>}
|
| 280 |
-
|
| 281 |
-
<div className="cg-ts-group">
|
| 282 |
-
<input
|
| 283 |
-
className="cg-input"
|
| 284 |
-
aria-label="Name for this chart"
|
| 285 |
-
placeholder="Name this chart"
|
| 286 |
-
maxLength={NAME_MAX}
|
| 287 |
-
value={newName}
|
| 288 |
-
disabled={busy}
|
| 289 |
-
onChange={(event) => setNewName(event.target.value)}
|
| 290 |
-
onKeyDown={(event) => {
|
| 291 |
-
if (event.key === "Enter" && canSave) {
|
| 292 |
-
event.preventDefault();
|
| 293 |
-
void save();
|
| 294 |
-
}
|
| 295 |
-
}}
|
| 296 |
-
/>
|
| 297 |
-
<button
|
| 298 |
-
type="button"
|
| 299 |
-
className="cg-btn cg-btn--primary"
|
| 300 |
-
disabled={!canSave}
|
| 301 |
-
onClick={() => void save()}
|
| 302 |
-
>
|
| 303 |
-
Save chart
|
| 304 |
-
</button>
|
| 305 |
-
</div>
|
| 306 |
-
|
| 307 |
-
{charts.length === 0 && !loading ? (
|
| 308 |
-
<p>No saved charts yet. Name the chart on screen and save it.</p>
|
| 309 |
-
) : (
|
| 310 |
-
<ul className="cg-history-list">
|
| 311 |
-
{charts.map((chart) => (
|
| 312 |
-
<li key={chart.id}>
|
| 313 |
-
{renaming === chart.id ? (
|
| 314 |
-
<>
|
| 315 |
-
<input
|
| 316 |
-
className="cg-input"
|
| 317 |
-
aria-label={`Rename ${chart.name}`}
|
| 318 |
-
maxLength={NAME_MAX}
|
| 319 |
-
value={renameText}
|
| 320 |
-
disabled={busy}
|
| 321 |
-
onChange={(event) => setRenameText(event.target.value)}
|
| 322 |
-
/>
|
| 323 |
-
<span className="cg-ts-group">
|
| 324 |
-
<button
|
| 325 |
-
type="button"
|
| 326 |
-
className="cg-btn cg-btn--primary"
|
| 327 |
-
disabled={busy || !renameText.trim()}
|
| 328 |
-
onClick={() => void rename(chart)}
|
| 329 |
-
>
|
| 330 |
-
Save name
|
| 331 |
-
</button>
|
| 332 |
-
<button
|
| 333 |
-
type="button"
|
| 334 |
-
className="cg-btn"
|
| 335 |
-
disabled={busy}
|
| 336 |
-
onClick={() => setRenaming(null)}
|
| 337 |
-
>
|
| 338 |
-
Cancel
|
| 339 |
-
</button>
|
| 340 |
-
</span>
|
| 341 |
-
</>
|
| 342 |
-
) : (
|
| 343 |
-
<>
|
| 344 |
-
<button
|
| 345 |
-
type="button"
|
| 346 |
-
className="cg-btn"
|
| 347 |
-
aria-current={activeId === chart.id ? "true" : undefined}
|
| 348 |
-
onClick={() => {
|
| 349 |
-
onApply(tsChartConfigFrom(chart.config));
|
| 350 |
-
onActiveId(chart.id);
|
| 351 |
-
}}
|
| 352 |
-
>
|
| 353 |
-
{chart.name}
|
| 354 |
-
</button>
|
| 355 |
-
<span className="cg-ts-group">
|
| 356 |
-
<button
|
| 357 |
-
type="button"
|
| 358 |
-
className="cg-btn"
|
| 359 |
-
aria-label={`Rename ${chart.name}`}
|
| 360 |
-
disabled={busy}
|
| 361 |
-
onClick={() => {
|
| 362 |
-
setRenameText(chart.name);
|
| 363 |
-
setDeleting(null);
|
| 364 |
-
setRenaming(chart.id);
|
| 365 |
-
}}
|
| 366 |
-
>
|
| 367 |
-
<MenuIcon name="rename" />
|
| 368 |
-
</button>
|
| 369 |
-
<button
|
| 370 |
-
type="button"
|
| 371 |
-
className="cg-btn cg-btn--danger"
|
| 372 |
-
aria-label={`Delete ${chart.name}`}
|
| 373 |
-
disabled={busy}
|
| 374 |
-
onClick={() => {
|
| 375 |
-
setRenaming(null);
|
| 376 |
-
setDeleting(chart.id);
|
| 377 |
-
}}
|
| 378 |
-
>
|
| 379 |
-
<MenuIcon name="trash" />
|
| 380 |
-
</button>
|
| 381 |
-
</span>
|
| 382 |
-
</>
|
| 383 |
-
)}
|
| 384 |
-
|
| 385 |
-
{deleting === chart.id && (
|
| 386 |
-
<div role="alertdialog" aria-label={`Delete ${chart.name}`}>
|
| 387 |
-
<p>Delete this saved chart? The view on screen is not changed.</p>
|
| 388 |
-
<span className="cg-ts-group">
|
| 389 |
-
<button
|
| 390 |
-
type="button"
|
| 391 |
-
className="cg-btn cg-btn--danger"
|
| 392 |
-
disabled={busy}
|
| 393 |
-
onClick={() => void remove(chart)}
|
| 394 |
-
>
|
| 395 |
-
Confirm delete
|
| 396 |
-
</button>
|
| 397 |
-
<button
|
| 398 |
-
type="button"
|
| 399 |
-
className="cg-btn"
|
| 400 |
-
disabled={busy}
|
| 401 |
-
onClick={() => setDeleting(null)}
|
| 402 |
-
>
|
| 403 |
-
Cancel
|
| 404 |
-
</button>
|
| 405 |
-
</span>
|
| 406 |
-
</div>
|
| 407 |
-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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
web/src/customer-grid/TimeSeriesPanel.tsx
DELETED
|
@@ -1,1706 +0,0 @@
|
|
| 1 |
-
/**
|
| 2 |
-
* TimeSeriesPanel.tsx — owner item 7 (contract C-TS), rebuilt for wave-14 items 16c · 17 · 18.
|
| 3 |
-
*
|
| 4 |
-
* ⚠ **HOST-AGNOSTIC ON PURPOSE — it reads no CustomerGrid state, ever.** RECORD re-mounts this
|
| 5 |
-
* exact component inside the record modal for item 13 (contract C-EMBED) with `pids=[pid]` and
|
| 6 |
-
* `locked`, so every input arrives as a prop. The moment this file imports a grid hook, the
|
| 7 |
-
* record-detail Insights tab stops being possible.
|
| 8 |
-
*
|
| 9 |
-
* All arithmetic and every honest disclosure live in `timeSeriesData.ts`, which
|
| 10 |
-
* `web/verify_timeseries.py` gates under node. This file is layout, fetch orchestration and
|
| 11 |
-
* one chart adapter — deliberately nothing a wrong number could hide in.
|
| 12 |
-
*
|
| 13 |
-
* ── What wave 14 changed, and why ──────────────────────────────────────────────────────────
|
| 14 |
-
*
|
| 15 |
-
* The panel WAS a chip bar over a fixed table: you toggled metrics on and off above the data,
|
| 16 |
-
* and the table was a read-only report of whatever survived. The owner asked for a SHEET —
|
| 17 |
-
* something you build rather than something you filter. So:
|
| 18 |
-
*
|
| 19 |
-
* · the metric chips are GONE. A metric is a ROW, added from a "+ Add metric" row at the
|
| 20 |
-
* bottom the way a spreadsheet grows, and removed from the row itself. The list of what is
|
| 21 |
-
* on screen and the list of what could be are the same list, in the same place.
|
| 22 |
-
* · rows carry the server's WINDOW LABEL as a sublabel (R1/C-TSWIN). Under identical month
|
| 23 |
-
* headings, a year-to-date row and a trailing-90 row are different claims, and nothing on
|
| 24 |
-
* screen used to say which one you were reading.
|
| 25 |
-
* · custom NOTE and FORMULA rows (R2) — the reader's own arithmetic, evaluated per column
|
| 26 |
-
* against the resolved buckets, refusing rather than inventing on every failure.
|
| 27 |
-
* · "Change vs prior" was ONE toggle producing ONE sub-row. It is now four named comparisons
|
| 28 |
-
* (item 18), each of which can refuse for its own stated reason.
|
| 29 |
-
*/
|
| 30 |
-
|
| 31 |
-
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
| 32 |
-
import { fetchTimeseries } from "./apiBridge";
|
| 33 |
-
import type { SurfaceScope } from "./apiBridge";
|
| 34 |
-
import { isStreamlitComponent } from "./hostBridge";
|
| 35 |
-
import { foldNavOnWorkSurface } from "./navFold";
|
| 36 |
-
import {
|
| 37 |
-
DEFAULT_TS_BUCKET,
|
| 38 |
-
DEFAULT_TS_LAST_N,
|
| 39 |
-
TS_DELTA_LABELS,
|
| 40 |
-
buildTsRequest,
|
| 41 |
-
buildTsSheet,
|
| 42 |
-
buildTsSnapshotRow,
|
| 43 |
-
buildTsTable,
|
| 44 |
-
classifyTsField,
|
| 45 |
-
formatTsDelta,
|
| 46 |
-
formatTsValue,
|
| 47 |
-
resolveTsStyle,
|
| 48 |
-
sparklinePoints,
|
| 49 |
-
sparklineSegments,
|
| 50 |
-
tsDisplayNumber,
|
| 51 |
-
tsRefusalReason,
|
| 52 |
-
tsRowToChartModel,
|
| 53 |
-
} from "./timeSeriesData";
|
| 54 |
-
import type {
|
| 55 |
-
TsDeltaSubRow,
|
| 56 |
-
TsColumn,
|
| 57 |
-
TsFormulaEvaluation,
|
| 58 |
-
TsFormulaValue,
|
| 59 |
-
TsPayload,
|
| 60 |
-
TsSheet,
|
| 61 |
-
TsSheetRow,
|
| 62 |
-
TsTableRow,
|
| 63 |
-
} from "./timeSeriesData";
|
| 64 |
-
import {
|
| 65 |
-
TS_BUCKETS,
|
| 66 |
-
TS_DELTA_KINDS,
|
| 67 |
-
TS_MAX_CUSTOM_ROWS,
|
| 68 |
-
TS_MAX_FIELDS,
|
| 69 |
-
TS_ROW_LABEL_MAX,
|
| 70 |
-
TS_MAX_EXPR,
|
| 71 |
-
} from "./types";
|
| 72 |
-
import type {
|
| 73 |
-
DisplaySpec,
|
| 74 |
-
Field,
|
| 75 |
-
TsBucket,
|
| 76 |
-
TsCellStyle,
|
| 77 |
-
TsCustomRow,
|
| 78 |
-
TsDeltaKind,
|
| 79 |
-
} from "./types";
|
| 80 |
-
import { FieldSelectButton } from "./FieldSelect";
|
| 81 |
-
import { Popover } from "../filter-kit";
|
| 82 |
-
import { toVegaLiteSpec } from "../viz/vega/toVegaLiteSpec";
|
| 83 |
-
import VegaLiteChart from "../viz/vega/VegaLiteChart";
|
| 84 |
-
import { API_V1, CREDENTIALS } from "../apiContract";
|
| 85 |
-
import SavedChartNav from "./SavedChartNav";
|
| 86 |
-
import type { TsChartConfig } from "./SavedChartNav";
|
| 87 |
-
|
| 88 |
-
const BUCKET_LABELS: Record<TsBucket, string> = {
|
| 89 |
-
week: "Weekly",
|
| 90 |
-
month: "Monthly",
|
| 91 |
-
quarter: "Quarterly",
|
| 92 |
-
year: "Yearly",
|
| 93 |
-
};
|
| 94 |
-
|
| 95 |
-
/**
|
| 96 |
-
* W47-T31 — the DATABASE key for a surface scope. **THE TWO ARE DIFFERENT STRING SPACES.**
|
| 97 |
-
*
|
| 98 |
-
* ⛔ THIS IS A DEFECT FIX, NOT A CONVENIENCE. `SurfaceScope` is what `CustomerGrid` mounts with
|
| 99 |
-
* ("customer", "product", a `ut_*` key); a DATABASE key is what the semantic layer, the metric
|
| 100 |
-
* catalogue and `session.require()` all take. `semantic.topic_for_grid("customer")` is None
|
| 101 |
-
* while `topic_for_grid("customer_data")` resolves `odoo_customers`, so every door this panel
|
| 102 |
-
* knocked on with a raw scope answered with an EMPTY metric list on both built-in pools and the
|
| 103 |
-
* Time series view offered nothing to plot. Only `ut_*` grids worked, because their scope string
|
| 104 |
-
* happens to equal their grid key.
|
| 105 |
-
*
|
| 106 |
-
* ⚠ "cohort" MAPS TO THE CUSTOMER POOL, and that is read off the server rather than assumed:
|
| 107 |
-
* `routes_records._CUSTOMER_SCOPES = ("", "customer", "cohort")` with the note *"the customer
|
| 108 |
-
* topic's two names, one book, two surfaces (the Cohort page is the customer table over
|
| 109 |
-
* hand-curated sets)"*, and `routes_nav` puts `cohort` in the `customer_data` family. The branch
|
| 110 |
-
* is currently unreachable from the shell anyway (`shell/dbFrame.tsx::gridScopeFor` never returns
|
| 111 |
-
* it), which is why naming it correctly costs nothing and guessing it would have.
|
| 112 |
-
*/
|
| 113 |
-
function databaseForScope(scope: SurfaceScope): string {
|
| 114 |
-
if (scope === "customer" || scope === "cohort") return "customer_data";
|
| 115 |
-
if (scope === "product") return "product_data";
|
| 116 |
-
return scope;
|
| 117 |
-
}
|
| 118 |
-
|
| 119 |
-
/** The rolling spans offered, per bucket. Capped well inside `TS_MAX_LAST_N`. */
|
| 120 |
-
const LAST_N_CHOICES = [6, 12, 24, 36];
|
| 121 |
-
|
| 122 |
-
/** The sparkline's box. Small enough to sit in a table cell, wide enough to have a shape. */
|
| 123 |
-
const SPARK_W = 72;
|
| 124 |
-
const SPARK_H = 18;
|
| 125 |
-
|
| 126 |
-
/**
|
| 127 |
-
* wave17 owner item 7 — the Compare popover's mark: a rising step over a baseline.
|
| 128 |
-
*
|
| 129 |
-
* Private to this file, the way `Toolbar.tsx` keeps its own `Icon*` set: the toolbar's glyphs
|
| 130 |
-
* are not exported, and this is the only surface that means "compare with the prior period".
|
| 131 |
-
* A step rather than an arrow — all four comparisons are period-to-period, and an arrow would
|
| 132 |
-
* claim a direction the control does not have.
|
| 133 |
-
*/
|
| 134 |
-
function IconCompare() {
|
| 135 |
-
const s = {
|
| 136 |
-
stroke: "currentColor",
|
| 137 |
-
strokeWidth: 1.5,
|
| 138 |
-
strokeLinecap: "round" as const,
|
| 139 |
-
strokeLinejoin: "round" as const,
|
| 140 |
-
fill: "none",
|
| 141 |
-
};
|
| 142 |
-
return (
|
| 143 |
-
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden>
|
| 144 |
-
<path d="M2.5 11.5h4v-4h4v-3h3" {...s} />
|
| 145 |
-
<path d="M2.5 13.5h11" {...s} opacity="0.45" />
|
| 146 |
-
</svg>
|
| 147 |
-
);
|
| 148 |
-
}
|
| 149 |
-
|
| 150 |
-
export interface TimeSeriesPanelProps {
|
| 151 |
-
scope: SurfaceScope;
|
| 152 |
-
/** The rows in scope. The server intersects with the caller's book regardless. */
|
| 153 |
-
pids: number[];
|
| 154 |
-
/** Every field the table has — the panel classifies them itself (item 5 / R9). */
|
| 155 |
-
fields: Field[];
|
| 156 |
-
/**
|
| 157 |
-
* wave17 item 5 / R9 — the view's data rows, for SNAPSHOT metrics only.
|
| 158 |
-
*
|
| 159 |
-
* ⚠ Does NOT break this file's host-agnostic rule. The rule is that the panel reads no
|
| 160 |
-
* CustomerGrid STATE; `pids` and `fields` already arrive the same way, and RECORD passes its
|
| 161 |
-
* one record. It must be the SAME population `pids` came from, or the two halves of one sheet
|
| 162 |
-
* would answer different questions with nothing going red — CustomerGrid derives both from
|
| 163 |
-
* `modeDataRows`.
|
| 164 |
-
*/
|
| 165 |
-
rows?: readonly Record<string, unknown>[];
|
| 166 |
-
/**
|
| 167 |
-
* The view's `config.display`; absent keys fall back to the panel's defaults.
|
| 168 |
-
*
|
| 169 |
-
* ⭐ STILL THE VIEW'S, AFTER W47-T31. A saved chart (R7 / C6) is a listed RECORD with its own
|
| 170 |
-
* id and name, not a second home for this state: opening one WRITES its stored keys through
|
| 171 |
-
* `onDisplay` into exactly this spec. So the live display state is where it always was, and
|
| 172 |
-
* the navigator is a source of values for it rather than a rival owner of it.
|
| 173 |
-
*/
|
| 174 |
-
display?: DisplaySpec;
|
| 175 |
-
/** Persist a display change. Absent = the panel is ephemeral (RECORD's embed, v1). */
|
| 176 |
-
onDisplay?: (next: Partial<DisplaySpec>) => void;
|
| 177 |
-
/** Item 13 — the pid set is the caller's and cannot be widened from here. */
|
| 178 |
-
locked?: boolean;
|
| 179 |
-
/**
|
| 180 |
-
* owner item 3 (2026-08-03) — publish the built sheet so the view menu's Export can carry it.
|
| 181 |
-
* Absent = this mount cannot be exported (RECORD's embed), which is the honest default.
|
| 182 |
-
*/
|
| 183 |
-
onSheet?: (sheet: TsSheet) => void;
|
| 184 |
-
/** Opens the host record drawer over a server-scoped contributor set. */
|
| 185 |
-
onOpenContributors?: (pids: number[]) => void;
|
| 186 |
-
}
|
| 187 |
-
|
| 188 |
-
/**
|
| 189 |
-
* wave17 item 5 / owner R9 — **OFFER EVERYTHING, best-effort.**
|
| 190 |
-
*
|
| 191 |
-
* v1 offered `key.startsWith("measure_")`, which was both too narrow and the wrong test. The
|
| 192 |
-
* classification now lives in `timeSeriesData.classifyTsField` (pure, gated under node) and this
|
| 193 |
-
* file only groups the result. A formula FIELD is still refused, for the reason it always was: it
|
| 194 |
-
* has no time dimension of its own, and a formula ROW on this sheet (R2) is a different thing.
|
| 195 |
-
*/
|
| 196 |
-
function classifyFields(fields: Field[]): {
|
| 197 |
-
server: Field[];
|
| 198 |
-
snapshot: Field[];
|
| 199 |
-
refused: { field: Field; why: string }[];
|
| 200 |
-
} {
|
| 201 |
-
const out = {
|
| 202 |
-
server: [] as Field[],
|
| 203 |
-
snapshot: [] as Field[],
|
| 204 |
-
refused: [] as { field: Field; why: string }[],
|
| 205 |
-
};
|
| 206 |
-
for (const f of fields) {
|
| 207 |
-
const cls = classifyTsField(f);
|
| 208 |
-
if (cls === "server") out.server.push(f);
|
| 209 |
-
else if (cls === "snapshot") out.snapshot.push(f);
|
| 210 |
-
else out.refused.push({ field: f, why: tsRefusalReason(f) });
|
| 211 |
-
}
|
| 212 |
-
return out;
|
| 213 |
-
}
|
| 214 |
-
|
| 215 |
-
/** A stable-enough id for a new custom row. `TS_ROW_ID_MAX` is 40; this is 12. */
|
| 216 |
-
function newRowId(existing: readonly TsCustomRow[]): string {
|
| 217 |
-
let n = existing.length + 1;
|
| 218 |
-
const taken = new Set(existing.map((r) => r.id));
|
| 219 |
-
while (taken.has(`tsr_${n}`)) n += 1;
|
| 220 |
-
return `tsr_${n}`;
|
| 221 |
-
}
|
| 222 |
-
|
| 223 |
-
type FormulaDefinition = Record<string, unknown>;
|
| 224 |
-
type FormulaFunctionHelp = {
|
| 225 |
-
name: string;
|
| 226 |
-
minArgs?: number;
|
| 227 |
-
maxArgs?: number;
|
| 228 |
-
example?: string;
|
| 229 |
-
};
|
| 230 |
-
type FormulaContract = {
|
| 231 |
-
contractVersion: number;
|
| 232 |
-
astVersion: number;
|
| 233 |
-
authority: "server";
|
| 234 |
-
reference: { open: string; close: string; pattern: RegExp; example?: string };
|
| 235 |
-
functions: FormulaFunctionHelp[];
|
| 236 |
-
example?: string;
|
| 237 |
-
maxSource: number;
|
| 238 |
-
};
|
| 239 |
-
|
| 240 |
-
function formulaMessage(body: unknown, fallback: string): string {
|
| 241 |
-
if (!body || typeof body !== "object") return fallback;
|
| 242 |
-
const value = body as Record<string, unknown>;
|
| 243 |
-
const detail = value.detail;
|
| 244 |
-
if (detail && typeof detail === "object") {
|
| 245 |
-
const detailValue = detail as Record<string, unknown>;
|
| 246 |
-
const message = detailValue.message;
|
| 247 |
-
if (typeof message === "string" && message) return message;
|
| 248 |
-
const nestedError = detailValue.error;
|
| 249 |
-
if (nestedError && typeof nestedError === "object") {
|
| 250 |
-
const nestedMessage = (nestedError as Record<string, unknown>).message;
|
| 251 |
-
if (typeof nestedMessage === "string" && nestedMessage) return nestedMessage;
|
| 252 |
-
}
|
| 253 |
-
}
|
| 254 |
-
if (typeof detail === "string" && detail) return detail;
|
| 255 |
-
if (typeof value.error === "string" && value.error) return value.error;
|
| 256 |
-
return fallback;
|
| 257 |
-
}
|
| 258 |
-
|
| 259 |
-
function readFormulaContract(body: unknown): FormulaContract | null {
|
| 260 |
-
if (!body || typeof body !== "object") return null;
|
| 261 |
-
const value = body as Record<string, unknown>;
|
| 262 |
-
if (value.authority !== "server") return null;
|
| 263 |
-
if (
|
| 264 |
-
typeof value.contractVersion !== "number" ||
|
| 265 |
-
!Number.isInteger(value.contractVersion) ||
|
| 266 |
-
typeof value.astVersion !== "number" ||
|
| 267 |
-
!Number.isInteger(value.astVersion)
|
| 268 |
-
) return null;
|
| 269 |
-
const grammar = value.grammar;
|
| 270 |
-
const reference =
|
| 271 |
-
grammar && typeof grammar === "object"
|
| 272 |
-
? (grammar as Record<string, unknown>).reference
|
| 273 |
-
: undefined;
|
| 274 |
-
if (!reference || typeof reference !== "object") return null;
|
| 275 |
-
const ref = reference as Record<string, unknown>;
|
| 276 |
-
if (
|
| 277 |
-
ref.open !== "{" ||
|
| 278 |
-
ref.close !== "}" ||
|
| 279 |
-
typeof ref.pattern !== "string" ||
|
| 280 |
-
ref.legacySquareReferenceAccepted !== false
|
| 281 |
-
) return null;
|
| 282 |
-
let referencePattern: RegExp;
|
| 283 |
-
try {
|
| 284 |
-
referencePattern = new RegExp(`^(?:${ref.pattern})$`);
|
| 285 |
-
} catch {
|
| 286 |
-
return null;
|
| 287 |
-
}
|
| 288 |
-
if (!referencePattern.test("{amount}")) return null;
|
| 289 |
-
const limits = value.limits;
|
| 290 |
-
const sourceCharacters =
|
| 291 |
-
limits && typeof limits === "object"
|
| 292 |
-
? (limits as Record<string, unknown>).sourceCharacters
|
| 293 |
-
: undefined;
|
| 294 |
-
if (
|
| 295 |
-
typeof sourceCharacters !== "number" ||
|
| 296 |
-
!Number.isInteger(sourceCharacters) ||
|
| 297 |
-
sourceCharacters < 1
|
| 298 |
-
) return null;
|
| 299 |
-
|
| 300 |
-
const fixtureRows = Array.isArray(value.fixtures) ? value.fixtures : [];
|
| 301 |
-
const examples = new Map<string, string>();
|
| 302 |
-
for (const fixture of fixtureRows) {
|
| 303 |
-
if (!fixture || typeof fixture !== "object") continue;
|
| 304 |
-
const item = fixture as Record<string, unknown>;
|
| 305 |
-
if (typeof item.function === "string" && typeof item.source === "string")
|
| 306 |
-
examples.set(item.function, item.source);
|
| 307 |
-
}
|
| 308 |
-
const functions: FormulaFunctionHelp[] = [];
|
| 309 |
-
for (const item of Array.isArray(value.functions) ? value.functions : []) {
|
| 310 |
-
if (!item || typeof item !== "object") continue;
|
| 311 |
-
const fn = item as Record<string, unknown>;
|
| 312 |
-
if (typeof fn.name !== "string" || !fn.name) continue;
|
| 313 |
-
functions.push({
|
| 314 |
-
name: fn.name,
|
| 315 |
-
minArgs: typeof fn.minArgs === "number" ? fn.minArgs : undefined,
|
| 316 |
-
maxArgs: typeof fn.maxArgs === "number" ? fn.maxArgs : undefined,
|
| 317 |
-
example: examples.get(fn.name),
|
| 318 |
-
});
|
| 319 |
-
}
|
| 320 |
-
const firstExample = fixtureRows.find(
|
| 321 |
-
(fixture): fixture is Record<string, unknown> =>
|
| 322 |
-
!!fixture && typeof fixture === "object" && typeof (fixture as Record<string, unknown>).source === "string"
|
| 323 |
-
);
|
| 324 |
-
return {
|
| 325 |
-
contractVersion: value.contractVersion,
|
| 326 |
-
astVersion: value.astVersion,
|
| 327 |
-
authority: "server",
|
| 328 |
-
reference: {
|
| 329 |
-
open: ref.open,
|
| 330 |
-
close: ref.close,
|
| 331 |
-
pattern: referencePattern,
|
| 332 |
-
example: typeof ref.example === "string" ? ref.example : undefined,
|
| 333 |
-
},
|
| 334 |
-
functions,
|
| 335 |
-
example: typeof firstExample?.source === "string" ? firstExample.source : undefined,
|
| 336 |
-
maxSource: sourceCharacters,
|
| 337 |
-
};
|
| 338 |
-
}
|
| 339 |
-
|
| 340 |
-
/* ⭐⭐ W49-T22 / CONTRACT C7 — THE EMPTY PICKER SAYS WHY, IN ONE PLAIN SENTENCE.
|
| 341 |
-
*
|
| 342 |
-
* R28: Joel Pal, on Royal Imports, opens an Odoo database, opens Time series, and finds a metric
|
| 343 |
-
* control with nothing in it. The control said "Add native metric" and then offered nothing, which
|
| 344 |
-
* reads as a broken screen rather than as an explanation. There are exactly three causes and the
|
| 345 |
-
* SERVER is the only party that can tell them apart, so `GET /query/metrics` now returns a
|
| 346 |
-
* `reason` beside the list and this map turns it into the sentence.
|
| 347 |
-
*
|
| 348 |
-
* ⛔ THE SENTENCES ARE THE CONTRACT, NOT DECORATION. Each names the CAUSE and the SUBJECT (the
|
| 349 |
-
* PRD's refusal rule), none of them is dressed as an error, none carries an icon, and none
|
| 350 |
-
* contains an em or en dash (CLAUDE.md rule 2 — this copy reaches a screen). Rewording one is a
|
| 351 |
-
* contract change, not a copy edit.
|
| 352 |
-
*/
|
| 353 |
-
export type TsMetricEmptyReason = "no_metrics" | "refused" | "no_topic";
|
| 354 |
-
|
| 355 |
-
export const TS_METRIC_EMPTY_COPY: Record<TsMetricEmptyReason, string> = {
|
| 356 |
-
no_metrics: "No metrics are defined for this database yet",
|
| 357 |
-
refused: "Your permissions hide the metrics on this database",
|
| 358 |
-
no_topic: "This database has no time axis to chart",
|
| 359 |
-
};
|
| 360 |
-
|
| 361 |
-
/** The reason for an empty catalogue, or null when it is not yet known.
|
| 362 |
-
*
|
| 363 |
-
* ⛔ `null` IS A REAL ANSWER AND MUST STAY ONE. While the request is in flight, or when it failed
|
| 364 |
-
* for a reason the contract does not name (an abort, a dropped connection), we do NOT know which
|
| 365 |
-
* of the three sentences is true — and printing "No metrics are defined for this database yet"
|
| 366 |
-
* over a network blip would be a false statement about the tenant's model. The picker prints
|
| 367 |
-
* nothing until it knows, which is the only honest fourth state.
|
| 368 |
-
*/
|
| 369 |
-
export function tsMetricEmptyReason(status: number, body: unknown): TsMetricEmptyReason | null {
|
| 370 |
-
// The two refusals that never carry a body: the record wall, and a database no topic declares.
|
| 371 |
-
if (status === 403) return "refused";
|
| 372 |
-
if (status === 404) return "no_topic";
|
| 373 |
-
if (status < 200 || status >= 300) return null;
|
| 374 |
-
const reason = (body as { reason?: unknown } | null | undefined)?.reason;
|
| 375 |
-
return typeof reason === "string" && reason in TS_METRIC_EMPTY_COPY
|
| 376 |
-
? (reason as TsMetricEmptyReason)
|
| 377 |
-
: null;
|
| 378 |
-
}
|
| 379 |
-
|
| 380 |
-
export default function TimeSeriesPanel({
|
| 381 |
-
scope,
|
| 382 |
-
pids,
|
| 383 |
-
fields,
|
| 384 |
-
rows,
|
| 385 |
-
display,
|
| 386 |
-
onDisplay,
|
| 387 |
-
locked,
|
| 388 |
-
onSheet,
|
| 389 |
-
onOpenContributors,
|
| 390 |
-
}: TimeSeriesPanelProps) {
|
| 391 |
-
// ⛔ EVERY DATABASE-KEYED DOOR BELOW TAKES THIS, NEVER `scope`. See `databaseForScope`.
|
| 392 |
-
const database = databaseForScope(scope);
|
| 393 |
-
const classed = useMemo(() => classifyFields(fields), [fields]);
|
| 394 |
-
type MetricCatalogItem = { key: string; label: string; description?: string; format?: string; source?: string; approved: true };
|
| 395 |
-
const [metricCatalog, setMetricCatalog] = useState<MetricCatalogItem[]>([]);
|
| 396 |
-
// C7. `null` until the door answers; see `tsMetricEmptyReason` for why that state has to exist.
|
| 397 |
-
const [metricsReason, setMetricsReason] = useState<TsMetricEmptyReason | null>(null);
|
| 398 |
-
useEffect(() => {
|
| 399 |
-
const controller = new AbortController();
|
| 400 |
-
setMetricsReason(null);
|
| 401 |
-
// ⛔ THE STATUS CODE IS THE SIGNAL AND IT USED TO BE THROWN AWAY. This read
|
| 402 |
-
// `response.ok ? response.json() : { metrics: [] }`, which collapsed a 403 (the permission
|
| 403 |
-
// wall) and a 404 (no semantic topic) into the same empty list the server sends when a
|
| 404 |
-
// database genuinely has no metric declared. Three different truths, one indistinguishable
|
| 405 |
-
// shape, and the picker could only ever say nothing.
|
| 406 |
-
void fetch(`${API_V1}/query/metrics?database=${encodeURIComponent(database)}`, { credentials: CREDENTIALS, signal: controller.signal })
|
| 407 |
-
.then(async (response) => ({ status: response.status, body: response.ok ? await response.json() : { metrics: [] } }))
|
| 408 |
-
.then(({ status, body }) => {
|
| 409 |
-
if (controller.signal.aborted) return;
|
| 410 |
-
const offered = Array.isArray(body?.metrics) ? body.metrics : [];
|
| 411 |
-
const admitted = offered.filter((item: unknown): item is MetricCatalogItem => {
|
| 412 |
-
if (!item || typeof item !== "object") return false;
|
| 413 |
-
const metric = item as Partial<MetricCatalogItem>;
|
| 414 |
-
return metric.approved === true && typeof metric.key === "string" && typeof metric.label === "string";
|
| 415 |
-
});
|
| 416 |
-
setMetricCatalog(admitted);
|
| 417 |
-
setMetricsReason(admitted.length ? null : tsMetricEmptyReason(status, body));
|
| 418 |
-
}).catch(() => { if (!controller.signal.aborted) { setMetricCatalog([]); setMetricsReason(null); } });
|
| 419 |
-
return () => controller.abort();
|
| 420 |
-
}, [database]);
|
| 421 |
-
// The OFFERED list: everything with a way onto the sheet, server-served first so a real series
|
| 422 |
-
// is never buried under a flat one in the picker.
|
| 423 |
-
const eligible = useMemo(
|
| 424 |
-
() => [...classed.server, ...classed.snapshot],
|
| 425 |
-
[classed.server, classed.snapshot]
|
| 426 |
-
);
|
| 427 |
-
const catalogKeys = useMemo(() => new Set(metricCatalog.map((metric) => metric.key)), [metricCatalog]);
|
| 428 |
-
const firstEligible = useMemo(() => eligible.filter((item) => !!item.measure?.key && catalogKeys.has(item.measure.key)), [catalogKeys, eligible]);
|
| 429 |
-
const snapshotKeys = useMemo(
|
| 430 |
-
() => new Set(classed.snapshot.map((f) => f.key)),
|
| 431 |
-
[classed.snapshot]
|
| 432 |
-
);
|
| 433 |
-
|
| 434 |
-
const bucket: TsBucket = (TS_BUCKETS as readonly string[]).includes(display?.tsBucket ?? "")
|
| 435 |
-
? (display!.tsBucket as TsBucket)
|
| 436 |
-
: DEFAULT_TS_BUCKET;
|
| 437 |
-
const lastN =
|
| 438 |
-
typeof display?.tsSpan?.lastN === "number" ? display.tsSpan.lastN : DEFAULT_TS_LAST_N;
|
| 439 |
-
// Preserve a saved explicit range verbatim. `lastN` remains only the control's resolved
|
| 440 |
-
// fallback; replacing an explicit range with it made saved native series answer a different
|
| 441 |
-
// question after reload.
|
| 442 |
-
const span = useMemo(() => display?.tsSpan ?? { lastN }, [display?.tsSpan, lastN]);
|
| 443 |
-
const nativeMetrics = useMemo(() => display?.tsMetrics ?? [], [display?.tsMetrics]);
|
| 444 |
-
const selected = useMemo(() => {
|
| 445 |
-
const want = display?.tsFields ?? [];
|
| 446 |
-
const live = want.filter((k) => eligible.some((f) => f.key === k));
|
| 447 |
-
// A view whose stored fields have all been deleted falls back to the first eligible
|
| 448 |
-
// metric rather than to an empty table, which would read as "no data" when the truth is
|
| 449 |
-
// "no fields chosen".
|
| 450 |
-
return live.length ? live : firstEligible.slice(0, 1).map((f) => f.key);
|
| 451 |
-
}, [display?.tsFields, eligible, firstEligible]);
|
| 452 |
-
|
| 453 |
-
/**
|
| 454 |
-
* wave17 item 5 — the selection SPLIT by where its answer comes from.
|
| 455 |
-
*
|
| 456 |
-
* ⚠ Only `wired` reaches the server. Sending a snapshot key would be answered with
|
| 457 |
-
* `not_a_measure_field` and rendered as a refusal footnote — telling the reader a field failed
|
| 458 |
-
* when the panel chose, deliberately, to compute it here.
|
| 459 |
-
*/
|
| 460 |
-
const wired = useMemo(
|
| 461 |
-
() => selected.filter((k) => !snapshotKeys.has(k)),
|
| 462 |
-
[selected, snapshotKeys]
|
| 463 |
-
);
|
| 464 |
-
const snapshotSelected = useMemo(
|
| 465 |
-
() => selected.filter((k) => snapshotKeys.has(k)),
|
| 466 |
-
[selected, snapshotKeys]
|
| 467 |
-
);
|
| 468 |
-
|
| 469 |
-
const customRows = useMemo(() => display?.tsRows ?? [], [display?.tsRows]);
|
| 470 |
-
type LaterSeriesOption = { aggregation: "sum" | "avg" | "min" | "max" | "count" | "count_distinct"; dateField: string };
|
| 471 |
-
const dateFields = useMemo(() => fields.filter((field) => field.type === "date"), [fields]);
|
| 472 |
-
const [laterSeries, setLaterSeries] = useState<Record<string, LaterSeriesOption>>({});
|
| 473 |
-
const [seriesValidationError, setSeriesValidationError] = useState("");
|
| 474 |
-
const [formulaContract, setFormulaContract] = useState<FormulaContract | null>(null);
|
| 475 |
-
const [formulaContractError, setFormulaContractError] = useState("");
|
| 476 |
-
const [formulaEvaluation, setFormulaEvaluation] = useState<TsFormulaEvaluation>();
|
| 477 |
-
const formulaReqRef = useRef(0);
|
| 478 |
-
useEffect(() => {
|
| 479 |
-
const controller = new AbortController();
|
| 480 |
-
void fetch(`${API_V1}/query/formulas/fixtures`, { credentials: CREDENTIALS, signal: controller.signal })
|
| 481 |
-
.then(async (response) => ({ ok: response.ok, body: await response.json().catch(() => ({})) }))
|
| 482 |
-
.then(({ ok, body }) => {
|
| 483 |
-
if (controller.signal.aborted) return;
|
| 484 |
-
const contract = ok ? readFormulaContract(body) : null;
|
| 485 |
-
setFormulaContract(contract);
|
| 486 |
-
setFormulaContractError(
|
| 487 |
-
contract ? "" : formulaMessage(body, "Formula help is unavailable.")
|
| 488 |
-
);
|
| 489 |
-
})
|
| 490 |
-
.catch((error: unknown) => {
|
| 491 |
-
if (controller.signal.aborted || (error instanceof DOMException && error.name === "AbortError")) return;
|
| 492 |
-
setFormulaContract(null);
|
| 493 |
-
setFormulaContractError("Formula help is unavailable.");
|
| 494 |
-
});
|
| 495 |
-
return () => controller.abort();
|
| 496 |
-
}, []);
|
| 497 |
-
const deltaKinds = useMemo(() => display?.tsDeltas ?? [], [display?.tsDeltas]);
|
| 498 |
-
const styles = display?.tsStyles;
|
| 499 |
-
// ⚠ PRESENCE, not truthiness — `tsGridlines` is `false | undefined` and absent means SHOWN.
|
| 500 |
-
// `!display?.tsGridlines` would hide the gridlines on every view that never chose.
|
| 501 |
-
const gridlines = display?.tsGridlines !== false;
|
| 502 |
-
const sparkline = display?.tsSparkline === true;
|
| 503 |
-
|
| 504 |
-
/* ═════════════ W47-T31 / R7 / C6 — SAVED CHARTS, IN A RIGHT-SIDE NAVIGATOR ═════════════
|
| 505 |
-
Owner R7: *"every interface like chart, swap etc. that we need to configure should act like
|
| 506 |
-
route with the right side navigation to choose the specific view we want to see. So its not
|
| 507 |
-
pegged on a per view basis."*
|
| 508 |
-
|
| 509 |
-
⭐ THE PANEL NEEDS NO NEW STATE MACHINE FOR THIS, and that is the whole design. Bucket, span,
|
| 510 |
-
fields, comparisons, styles and both toggles are ALREADY derived from `display` and written
|
| 511 |
-
back through `onDisplay`, so "open that chart" is one `onDisplay(...)` call and "save this
|
| 512 |
-
one" is a read of the values below. A chart is a RECORD on the server (C6), listed beside
|
| 513 |
-
every view rather than stored inside one.
|
| 514 |
-
|
| 515 |
-
⛔ THE RESOLVED VALUES, NOT `display?.*`. A view that never chose a bucket still SHOWS
|
| 516 |
-
Monthly, and saving the raw absent key would produce a chart that reloads as "nothing
|
| 517 |
-
chosen" while its author was looking at a full sheet. */
|
| 518 |
-
const chartConfig: TsChartConfig = useMemo(() => ({
|
| 519 |
-
tsFields: selected.length ? [...selected] : undefined,
|
| 520 |
-
tsMetrics: nativeMetrics.length ? nativeMetrics : undefined,
|
| 521 |
-
tsBucket: bucket,
|
| 522 |
-
tsSpan: span,
|
| 523 |
-
tsDeltas: deltaKinds.length ? [...deltaKinds] : undefined,
|
| 524 |
-
tsStyles: styles,
|
| 525 |
-
// Both toggles keep the host's storage asymmetry: the DEFAULT is stored by deleting the key.
|
| 526 |
-
tsGridlines: gridlines ? undefined : false,
|
| 527 |
-
tsSparkline: sparkline ? true : undefined,
|
| 528 |
-
tsRows: customRows.length ? [...customRows] : undefined,
|
| 529 |
-
}), [bucket, customRows, deltaKinds, gridlines, nativeMetrics, selected, sparkline, span, styles]);
|
| 530 |
-
const [chartNavOpen, setChartNavOpen] = useState(false);
|
| 531 |
-
const [activeChartId, setActiveChartId] = useState<string | null>(null);
|
| 532 |
-
|
| 533 |
-
const [payload, setPayload] = useState<TsPayload | null>(null);
|
| 534 |
-
const [state, setState] = useState<"idle" | "loading" | "error">("idle");
|
| 535 |
-
const [errStatus, setErrStatus] = useState(0);
|
| 536 |
-
const [charted, setCharted] = useState<Set<string>>(new Set());
|
| 537 |
-
// Guards a slow response from overwriting a newer one — the request the user is waiting on
|
| 538 |
-
// is the LAST one they asked for, not the last one to arrive.
|
| 539 |
-
const reqRef = useRef(0);
|
| 540 |
-
|
| 541 |
-
const embedded = isStreamlitComponent();
|
| 542 |
-
const openContributors = useCallback(async (metric: TsTableRow | undefined, to: string) => {
|
| 543 |
-
if (!metric || !onOpenContributors || !pids.length) return;
|
| 544 |
-
const native = metric.field.startsWith("native:")
|
| 545 |
-
? nativeMetrics.find((item) => item.key === metric.field.slice("native:".length)) : undefined;
|
| 546 |
-
const response = await fetch(`${API_V1}/grid/timeseries/contributors?scope=${encodeURIComponent(scope)}`, {
|
| 547 |
-
method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
|
| 548 |
-
body: JSON.stringify({ pids, to, field: native ? undefined : metric.field, metric: native }),
|
| 549 |
-
}).catch(() => null);
|
| 550 |
-
const body = response?.ok ? await response.json().catch(() => ({})) : {};
|
| 551 |
-
const contributors = Array.isArray(body?.pids)
|
| 552 |
-
? body.pids.filter((pid: unknown): pid is number => Number.isInteger(pid)) : [];
|
| 553 |
-
if (contributors.length) onOpenContributors(contributors);
|
| 554 |
-
}, [nativeMetrics, onOpenContributors, pids, scope]);
|
| 555 |
-
|
| 556 |
-
useEffect(() => {
|
| 557 |
-
if (embedded) return;
|
| 558 |
-
if ((!wired.length && !nativeMetrics.length) || !pids.length) {
|
| 559 |
-
setPayload(null);
|
| 560 |
-
setState("idle");
|
| 561 |
-
return;
|
| 562 |
-
}
|
| 563 |
-
const seq = ++reqRef.current;
|
| 564 |
-
setState("loading");
|
| 565 |
-
const body = buildTsRequest({ pids, bucket, span, fields: wired, metrics: nativeMetrics });
|
| 566 |
-
fetchTimeseries(body, scope).then(({ payload: p, status }) => {
|
| 567 |
-
if (seq !== reqRef.current) return;
|
| 568 |
-
if (!p) {
|
| 569 |
-
setPayload(null);
|
| 570 |
-
setErrStatus(status);
|
| 571 |
-
setState("error");
|
| 572 |
-
return;
|
| 573 |
-
}
|
| 574 |
-
setPayload(p);
|
| 575 |
-
setState("idle");
|
| 576 |
-
});
|
| 577 |
-
}, [embedded, scope, pids, bucket, nativeMetrics, span, wired]);
|
| 578 |
-
|
| 579 |
-
const served = useMemo(() => buildTsTable(payload), [payload]);
|
| 580 |
-
/**
|
| 581 |
-
* wave17 item 5 / R9 — the snapshot rows, spliced in AFTER the server's.
|
| 582 |
-
*
|
| 583 |
-
* ⚠ They ride the SERVER's columns. Bucket starts and bucket labels are server math
|
| 584 |
-
* (`_ts_next`/`_ts_label`), and re-deriving them here would be a second copy with no parity
|
| 585 |
-
* gate holding it to the first. The consequence — a snapshot-only sheet has no columns to sit
|
| 586 |
-
* on — is DISCLOSED below rather than papered over; the relaxation that would remove it is a
|
| 587 |
-
* one-line 400→200 on the TS route, requested as an amendment in the wave doc.
|
| 588 |
-
*/
|
| 589 |
-
const table = useMemo(() => {
|
| 590 |
-
if (!snapshotSelected.length || !served.columns.length) return served;
|
| 591 |
-
const byKey = new Map(fields.map((f) => [f.key, f]));
|
| 592 |
-
const extra = snapshotSelected
|
| 593 |
-
.map((k) => byKey.get(k))
|
| 594 |
-
.filter((f): f is Field => !!f)
|
| 595 |
-
.map((f) => buildTsSnapshotRow(f, rows ?? [], served.columns, payload?.meta?.today));
|
| 596 |
-
return { ...served, rows: [...served.rows, ...extra], empty: false };
|
| 597 |
-
}, [served, snapshotSelected, fields, rows, payload?.meta?.today]);
|
| 598 |
-
const formulaRows = useMemo(
|
| 599 |
-
() => customRows.filter((row) => row.kind === "formula"),
|
| 600 |
-
[customRows]
|
| 601 |
-
);
|
| 602 |
-
const formulaPeriodRows = useMemo(
|
| 603 |
-
() =>
|
| 604 |
-
table.columns.map((column, columnIndex) => ({
|
| 605 |
-
id: column.key,
|
| 606 |
-
values: Object.fromEntries(
|
| 607 |
-
[
|
| 608 |
-
...table.rows.map((row) => [row.field, row.cells[columnIndex]?.value ?? null] as const),
|
| 609 |
-
...formulaRows
|
| 610 |
-
.filter((row) => formulaContract?.reference.pattern.test(`{${row.id}}`))
|
| 611 |
-
.map((row) => [row.id, null] as const),
|
| 612 |
-
]
|
| 613 |
-
),
|
| 614 |
-
})),
|
| 615 |
-
[formulaContract, formulaRows, table]
|
| 616 |
-
);
|
| 617 |
-
useEffect(() => {
|
| 618 |
-
const seq = ++formulaReqRef.current;
|
| 619 |
-
if (!formulaRows.length) {
|
| 620 |
-
setFormulaEvaluation(undefined);
|
| 621 |
-
return;
|
| 622 |
-
}
|
| 623 |
-
if (!formulaContract) {
|
| 624 |
-
setFormulaEvaluation(undefined);
|
| 625 |
-
return;
|
| 626 |
-
}
|
| 627 |
-
setFormulaEvaluation(undefined);
|
| 628 |
-
const controller = new AbortController();
|
| 629 |
-
const timer = window.setTimeout(() => {
|
| 630 |
-
void (async () => {
|
| 631 |
-
const parsed = await Promise.all(
|
| 632 |
-
formulaRows.map(async (row) => {
|
| 633 |
-
if (!formulaContract.reference.pattern.test(`{${row.id}}`))
|
| 634 |
-
return {
|
| 635 |
-
id: row.id,
|
| 636 |
-
error: "Formula row keys may contain only letters, numbers, and underscores.",
|
| 637 |
-
};
|
| 638 |
-
const response = await fetch(`${API_V1}/query/formulas/parse`, {
|
| 639 |
-
method: "POST",
|
| 640 |
-
credentials: CREDENTIALS,
|
| 641 |
-
signal: controller.signal,
|
| 642 |
-
headers: { "Content-Type": "application/json" },
|
| 643 |
-
body: JSON.stringify({ source: row.expr ?? "" }),
|
| 644 |
-
});
|
| 645 |
-
const body: unknown = await response.json().catch(() => ({}));
|
| 646 |
-
if (!response.ok || !body || typeof body !== "object")
|
| 647 |
-
return { id: row.id, error: formulaMessage(body, "The server could not parse this formula.") };
|
| 648 |
-
const result = body as Record<string, unknown>;
|
| 649 |
-
const definition = result.definition;
|
| 650 |
-
if (
|
| 651 |
-
result.authority !== "server" ||
|
| 652 |
-
typeof result.contractVersion !== "number" ||
|
| 653 |
-
typeof result.astVersion !== "number" ||
|
| 654 |
-
(formulaContract != null &&
|
| 655 |
-
(result.contractVersion !== formulaContract.contractVersion ||
|
| 656 |
-
result.astVersion !== formulaContract.astVersion)) ||
|
| 657 |
-
!definition ||
|
| 658 |
-
typeof definition !== "object" ||
|
| 659 |
-
Array.isArray(definition)
|
| 660 |
-
)
|
| 661 |
-
return { id: row.id, error: "The server did not return an authoritative formula definition." };
|
| 662 |
-
return {
|
| 663 |
-
id: row.id,
|
| 664 |
-
definition: definition as FormulaDefinition,
|
| 665 |
-
contractVersion: result.contractVersion,
|
| 666 |
-
astVersion: result.astVersion,
|
| 667 |
-
};
|
| 668 |
-
})
|
| 669 |
-
);
|
| 670 |
-
if (controller.signal.aborted || seq !== formulaReqRef.current) return;
|
| 671 |
-
const definitions: Record<string, FormulaDefinition> = {};
|
| 672 |
-
const definitionErrors: Record<string, string> = {};
|
| 673 |
-
for (const result of parsed) {
|
| 674 |
-
if (result.definition) definitions[result.id] = result.definition;
|
| 675 |
-
else definitionErrors[result.id] = result.error ?? "The server could not parse this formula.";
|
| 676 |
-
}
|
| 677 |
-
if (!Object.keys(definitions).length || !formulaPeriodRows.length) {
|
| 678 |
-
setFormulaEvaluation({
|
| 679 |
-
contractVersion: formulaContract?.contractVersion,
|
| 680 |
-
astVersion: formulaContract?.astVersion,
|
| 681 |
-
authority: "server",
|
| 682 |
-
consumer: "timeseries",
|
| 683 |
-
rows: [],
|
| 684 |
-
definitionErrors,
|
| 685 |
-
});
|
| 686 |
-
return;
|
| 687 |
-
}
|
| 688 |
-
const response = await fetch(`${API_V1}/query/formulas/evaluate`, {
|
| 689 |
-
method: "POST",
|
| 690 |
-
credentials: CREDENTIALS,
|
| 691 |
-
signal: controller.signal,
|
| 692 |
-
headers: { "Content-Type": "application/json" },
|
| 693 |
-
body: JSON.stringify({
|
| 694 |
-
consumer: "timeseries",
|
| 695 |
-
definitions,
|
| 696 |
-
rows: formulaPeriodRows,
|
| 697 |
-
today: payload?.meta?.today,
|
| 698 |
-
}),
|
| 699 |
-
});
|
| 700 |
-
const body: unknown = await response.json().catch(() => ({}));
|
| 701 |
-
if (controller.signal.aborted || seq !== formulaReqRef.current) return;
|
| 702 |
-
if (!response.ok || !body || typeof body !== "object") {
|
| 703 |
-
setFormulaEvaluation({
|
| 704 |
-
contractVersion: formulaContract?.contractVersion,
|
| 705 |
-
astVersion: formulaContract?.astVersion,
|
| 706 |
-
authority: "server",
|
| 707 |
-
consumer: "timeseries",
|
| 708 |
-
rows: [],
|
| 709 |
-
definitionErrors,
|
| 710 |
-
transportError: formulaMessage(body, "Formula values could not be evaluated."),
|
| 711 |
-
});
|
| 712 |
-
return;
|
| 713 |
-
}
|
| 714 |
-
const result = body as Record<string, unknown>;
|
| 715 |
-
if (
|
| 716 |
-
result.authority !== "server" ||
|
| 717 |
-
result.consumer !== "timeseries" ||
|
| 718 |
-
typeof result.contractVersion !== "number" ||
|
| 719 |
-
typeof result.astVersion !== "number" ||
|
| 720 |
-
(formulaContract != null &&
|
| 721 |
-
(result.contractVersion !== formulaContract.contractVersion ||
|
| 722 |
-
result.astVersion !== formulaContract.astVersion)) ||
|
| 723 |
-
!Array.isArray(result.rows)
|
| 724 |
-
) {
|
| 725 |
-
setFormulaEvaluation({
|
| 726 |
-
contractVersion: formulaContract?.contractVersion,
|
| 727 |
-
astVersion: formulaContract?.astVersion,
|
| 728 |
-
authority: "server",
|
| 729 |
-
consumer: "timeseries",
|
| 730 |
-
rows: [],
|
| 731 |
-
definitionErrors,
|
| 732 |
-
transportError: "The server returned a formula result without its authority markers.",
|
| 733 |
-
});
|
| 734 |
-
return;
|
| 735 |
-
}
|
| 736 |
-
const evaluatedRows = result.rows.flatMap((item) => {
|
| 737 |
-
if (!item || typeof item !== "object" || Array.isArray(item)) return [];
|
| 738 |
-
const period = item as Record<string, unknown>;
|
| 739 |
-
if (
|
| 740 |
-
(typeof period.id !== "string" && typeof period.id !== "number") ||
|
| 741 |
-
!period.values || typeof period.values !== "object" || Array.isArray(period.values) ||
|
| 742 |
-
!period.errors || typeof period.errors !== "object" || Array.isArray(period.errors)
|
| 743 |
-
) return [];
|
| 744 |
-
return [{
|
| 745 |
-
id: period.id,
|
| 746 |
-
values: period.values as Record<string, unknown>,
|
| 747 |
-
errors: Object.fromEntries(
|
| 748 |
-
Object.entries(period.errors as Record<string, unknown>)
|
| 749 |
-
.filter((entry): entry is [string, string] => typeof entry[1] === "string")
|
| 750 |
-
),
|
| 751 |
-
}];
|
| 752 |
-
});
|
| 753 |
-
setFormulaEvaluation({
|
| 754 |
-
contractVersion: result.contractVersion,
|
| 755 |
-
astVersion: result.astVersion,
|
| 756 |
-
authority: "server",
|
| 757 |
-
consumer: "timeseries",
|
| 758 |
-
rows: evaluatedRows,
|
| 759 |
-
definitionErrors,
|
| 760 |
-
});
|
| 761 |
-
})().catch((error: unknown) => {
|
| 762 |
-
if (
|
| 763 |
-
controller.signal.aborted ||
|
| 764 |
-
seq !== formulaReqRef.current ||
|
| 765 |
-
(error instanceof DOMException && error.name === "AbortError")
|
| 766 |
-
) return;
|
| 767 |
-
setFormulaEvaluation({
|
| 768 |
-
contractVersion: formulaContract?.contractVersion,
|
| 769 |
-
astVersion: formulaContract?.astVersion,
|
| 770 |
-
authority: "server",
|
| 771 |
-
consumer: "timeseries",
|
| 772 |
-
rows: [],
|
| 773 |
-
transportError: "Formula values could not be evaluated.",
|
| 774 |
-
});
|
| 775 |
-
});
|
| 776 |
-
}, 300);
|
| 777 |
-
return () => {
|
| 778 |
-
controller.abort();
|
| 779 |
-
window.clearTimeout(timer);
|
| 780 |
-
};
|
| 781 |
-
}, [formulaContract, formulaPeriodRows, formulaRows, payload?.meta?.today]);
|
| 782 |
-
const sheet: TsSheet = useMemo(
|
| 783 |
-
() =>
|
| 784 |
-
buildTsSheet(table, {
|
| 785 |
-
customRows,
|
| 786 |
-
deltas: deltaKinds,
|
| 787 |
-
bucket,
|
| 788 |
-
today: payload?.meta?.today,
|
| 789 |
-
formulas: formulaEvaluation,
|
| 790 |
-
}),
|
| 791 |
-
[table, customRows, deltaKinds, bucket, payload?.meta?.today, formulaEvaluation]
|
| 792 |
-
);
|
| 793 |
-
const formulaPreviewErrors = useMemo(() => {
|
| 794 |
-
const output: Record<string, string> = {};
|
| 795 |
-
for (const row of formulaRows) {
|
| 796 |
-
const parseError = formulaEvaluation?.definitionErrors?.[row.id];
|
| 797 |
-
if (parseError) {
|
| 798 |
-
output[row.id] = parseError;
|
| 799 |
-
continue;
|
| 800 |
-
}
|
| 801 |
-
if (formulaEvaluation?.transportError) {
|
| 802 |
-
output[row.id] = formulaEvaluation.transportError;
|
| 803 |
-
continue;
|
| 804 |
-
}
|
| 805 |
-
for (const period of formulaEvaluation?.rows ?? []) {
|
| 806 |
-
const error = period.errors?.[row.id];
|
| 807 |
-
if (error) {
|
| 808 |
-
output[row.id] = error.replaceAll("_", " ");
|
| 809 |
-
break;
|
| 810 |
-
}
|
| 811 |
-
}
|
| 812 |
-
}
|
| 813 |
-
return output;
|
| 814 |
-
}, [formulaEvaluation, formulaRows]);
|
| 815 |
-
const formulaPreviewValues = useMemo(() => {
|
| 816 |
-
const output: Record<string, TsFormulaValue | undefined> = {};
|
| 817 |
-
for (const row of sheet.rows) {
|
| 818 |
-
if (row.kind !== "formula") continue;
|
| 819 |
-
output[row.id] = row.cells.find((cell) => cell.value != null)?.value ?? row.cells[0]?.value;
|
| 820 |
-
}
|
| 821 |
-
return output;
|
| 822 |
-
}, [sheet.rows]);
|
| 823 |
-
const formulaReferences = useMemo(() => {
|
| 824 |
-
if (!formulaContract) return [];
|
| 825 |
-
const source = (key: string) =>
|
| 826 |
-
`${formulaContract.reference.open}${key}${formulaContract.reference.close}`;
|
| 827 |
-
return [
|
| 828 |
-
...table.rows
|
| 829 |
-
.filter((row) => formulaContract.reference.pattern.test(source(row.field)))
|
| 830 |
-
.map((row) => ({ key: row.field, label: row.label, source: source(row.field) })),
|
| 831 |
-
...formulaRows
|
| 832 |
-
.filter((row) => formulaContract.reference.pattern.test(source(row.id)))
|
| 833 |
-
.map((row) => ({ key: row.id, label: row.label || row.id, source: source(row.id) })),
|
| 834 |
-
];
|
| 835 |
-
}, [formulaContract, formulaRows, table.rows]);
|
| 836 |
-
|
| 837 |
-
/**
|
| 838 |
-
* ⭐ owner item 3 (2026-08-03) — the sheet is PUBLISHED, not downloaded from here.
|
| 839 |
-
*
|
| 840 |
-
* This panel used to carry its own "Export CSV" button. It was the only view in the product
|
| 841 |
-
* with a second export door, and the only one offering a single format, while every other
|
| 842 |
-
* view exports from the "…" menu in the rail with four. So the button is gone and the sheet
|
| 843 |
-
* goes UP instead: the owner of the view menu builds the file, and the time-series view
|
| 844 |
-
* exports its SHEET rather than the customer rows underneath it.
|
| 845 |
-
*
|
| 846 |
-
* ⚠ A PROP, WHICH IS WHAT KEEPS THIS FILE HOST-AGNOSTIC. The rule at the top of this file is
|
| 847 |
-
* that the panel reads no CustomerGrid state — a callback the caller supplies is the same
|
| 848 |
-
* shape `onDisplay` already is. RECORD's embed passes neither and simply cannot export, which
|
| 849 |
-
* is correct: there is no view menu in a record modal.
|
| 850 |
-
*
|
| 851 |
-
* Effect rather than a render-time call: publishing during render would set state in another
|
| 852 |
-
* component mid-render. `sheet` is a `useMemo`, so this fires on a real change, not per frame.
|
| 853 |
-
*/
|
| 854 |
-
useEffect(() => {
|
| 855 |
-
onSheet?.(sheet);
|
| 856 |
-
}, [sheet, onSheet]);
|
| 857 |
-
|
| 858 |
-
const toggleChart = useCallback((key: string) => {
|
| 859 |
-
setCharted((prev) => {
|
| 860 |
-
const next = new Set(prev);
|
| 861 |
-
if (next.has(key)) next.delete(key);
|
| 862 |
-
else next.add(key);
|
| 863 |
-
return next;
|
| 864 |
-
});
|
| 865 |
-
}, []);
|
| 866 |
-
|
| 867 |
-
// ── display writers. Each one DELETES its key for the default rather than storing a second
|
| 868 |
-
// spelling of it — the `kanbanClamp` law, which `tsGridlines` and `tsSparkline` inherit
|
| 869 |
-
// exactly (the host accepts only the literal `false` / literal `true`).
|
| 870 |
-
const validateSeries = useCallback(async (keys: string[], options: Record<string, LaterSeriesOption>): Promise<boolean> => {
|
| 871 |
-
if (!keys.length) return false;
|
| 872 |
-
const byKey = new Map(fields.map((field) => [field.key, field]));
|
| 873 |
-
const first = byKey.get(keys[0]);
|
| 874 |
-
if (!first?.measure?.key || !catalogKeys.has(first.measure.key)) {
|
| 875 |
-
setSeriesValidationError("The first series must be an approved Metric from this database.");
|
| 876 |
-
return false;
|
| 877 |
-
}
|
| 878 |
-
const series: Array<Record<string, unknown>> = [{ kind: "metric", key: first.measure.key }];
|
| 879 |
-
for (const key of keys.slice(1)) {
|
| 880 |
-
const field = byKey.get(key);
|
| 881 |
-
if (!field) continue;
|
| 882 |
-
if (field.measure?.key && catalogKeys.has(field.measure.key)) series.push({ kind: "metric", key: field.measure.key });
|
| 883 |
-
else {
|
| 884 |
-
const option = options[key];
|
| 885 |
-
if (!option?.dateField) {
|
| 886 |
-
setSeriesValidationError(`${field.label} needs an aggregation and date field.`);
|
| 887 |
-
return false;
|
| 888 |
-
}
|
| 889 |
-
series.push({ kind: "field", key, aggregation: option.aggregation, dateField: option.dateField });
|
| 890 |
-
}
|
| 891 |
-
}
|
| 892 |
-
try {
|
| 893 |
-
const response = await fetch(`${API_V1}/query/timeseries/validate`, { method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ database, series }) });
|
| 894 |
-
const body = await response.json().catch(() => ({}));
|
| 895 |
-
if (!response.ok) {
|
| 896 |
-
setSeriesValidationError(String(body?.detail?.message ?? body?.error ?? "These series cannot be saved."));
|
| 897 |
-
return false;
|
| 898 |
-
}
|
| 899 |
-
setSeriesValidationError("");
|
| 900 |
-
return true;
|
| 901 |
-
} catch {
|
| 902 |
-
setSeriesValidationError("Series validation is unavailable. Nothing was saved.");
|
| 903 |
-
return false;
|
| 904 |
-
}
|
| 905 |
-
}, [catalogKeys, database, fields]);
|
| 906 |
-
const setMetrics = async (keys: string[], options = laterSeries) => {
|
| 907 |
-
// Never persist an EMPTY metric list: it would read back as "no data" on the next open.
|
| 908 |
-
if (!keys.length) return;
|
| 909 |
-
if (!await validateSeries(keys, options)) return;
|
| 910 |
-
onDisplay?.({ tsFields: keys.slice(0, TS_MAX_FIELDS) });
|
| 911 |
-
};
|
| 912 |
-
const setRows = (rows: TsCustomRow[]) =>
|
| 913 |
-
onDisplay?.({ tsRows: rows.length ? rows.slice(0, TS_MAX_CUSTOM_ROWS) : undefined });
|
| 914 |
-
const toggleDelta = (kind: TsDeltaKind) => {
|
| 915 |
-
const next = deltaKinds.includes(kind)
|
| 916 |
-
? deltaKinds.filter((k) => k !== kind)
|
| 917 |
-
: [...deltaKinds, kind];
|
| 918 |
-
onDisplay?.({ tsDeltas: next.length ? next : undefined });
|
| 919 |
-
};
|
| 920 |
-
const setStyle = (rowId: string, patch: TsCellStyle) => {
|
| 921 |
-
const next: Record<string, TsCellStyle> = { ...(styles ?? {}) };
|
| 922 |
-
const merged = { ...resolveTsStyle(styles, rowId), ...patch };
|
| 923 |
-
// A style that reduces to nothing is DELETED, never stored as `{}`: an empty object is the
|
| 924 |
-
// absent state's second spelling, and 200 of them would evict real emphasis under the cap
|
| 925 |
-
// (GRID's C-TYPES2 asymmetry #1, mirrored here so a save round-trips unchanged).
|
| 926 |
-
const kept: TsCellStyle = {};
|
| 927 |
-
if (merged.bold) kept.bold = true;
|
| 928 |
-
if (merged.line) kept.line = true;
|
| 929 |
-
if (kept.bold || kept.line) next[rowId] = kept;
|
| 930 |
-
else delete next[rowId];
|
| 931 |
-
onDisplay?.({ tsStyles: Object.keys(next).length ? next : undefined });
|
| 932 |
-
};
|
| 933 |
-
|
| 934 |
-
// ── the Streamlit embed. C-TS: an honest placeholder, and above all it must not crash the
|
| 935 |
-
// component — the grid still runs inside app.py and a throw here would take the page.
|
| 936 |
-
if (embedded) {
|
| 937 |
-
return (
|
| 938 |
-
<div className="cg-mode-empty" onPointerDown={foldNavOnWorkSurface}>
|
| 939 |
-
The time-series view runs in the web app. Open Loopable in a browser tab to see it.
|
| 940 |
-
</div>
|
| 941 |
-
);
|
| 942 |
-
}
|
| 943 |
-
|
| 944 |
-
if (!eligible.length) {
|
| 945 |
-
return (
|
| 946 |
-
<div className="cg-mode-empty" onPointerDown={foldNavOnWorkSurface}>
|
| 947 |
-
This table has no number fields to plot. A time series needs either a metric with a
|
| 948 |
-
period, or a numeric column to snapshot. Add one from a column menu, then pick it here.
|
| 949 |
-
</div>
|
| 950 |
-
);
|
| 951 |
-
}
|
| 952 |
-
|
| 953 |
-
const unused = (selected.length ? eligible : firstEligible).filter((f) => !selected.includes(f.key));
|
| 954 |
-
const colCount = sheet.columns.length + 2 + (sparkline ? 1 : 0);
|
| 955 |
-
/* wave17 item 5 / R9 — the honest edge, while the TS route still 400s a request with no
|
| 956 |
-
measure field in it. Snapshot rows are painted under the SERVER's bucket columns, so with
|
| 957 |
-
no measure metric on the sheet there is nowhere to put them. Said in words, with the fix,
|
| 958 |
-
rather than rendering an empty table that looks broken. */
|
| 959 |
-
const snapshotsUnplaced =
|
| 960 |
-
snapshotSelected.length > 0 && sheet.columns.length === 0 && state !== "loading";
|
| 961 |
-
|
| 962 |
-
return (
|
| 963 |
-
/* `position: relative` is INLINE because `.cg-ts` has none and this ticket may not touch
|
| 964 |
-
a stylesheet. It anchors the shared `.cg-workspace-drawer` (absolute) to the Time series
|
| 965 |
-
panel rather than to whatever positioned ancestor happens to be above it, and changes
|
| 966 |
-
no layout: an absolutely positioned child leaves the flex column entirely. */
|
| 967 |
-
<div className="cg-ts" onPointerDown={foldNavOnWorkSurface} style={{ position: "relative" }}>
|
| 968 |
-
{formulaContractError && <div className="cg-ts-note" role="alert">{formulaContractError}</div>}
|
| 969 |
-
{Object.entries(formulaPreviewErrors).some(([, error]) => error) && <div className="cg-ts-note" role="alert">{Object.entries(formulaPreviewErrors).filter(([, error]) => error).map(([id, error]) => <span key={id}>{error}</span>)}</div>}
|
| 970 |
-
{seriesValidationError && <div className="cg-ts-note" role="alert">{seriesValidationError}</div>}
|
| 971 |
-
<div className="cg-ts-bar">
|
| 972 |
-
<label className="cg-ts-ctl" aria-label="Time bucket">
|
| 973 |
-
<select
|
| 974 |
-
className="cg-select"
|
| 975 |
-
value={bucket}
|
| 976 |
-
onChange={(e) => onDisplay?.({ tsBucket: e.target.value as TsBucket })}
|
| 977 |
-
disabled={!onDisplay}
|
| 978 |
-
>
|
| 979 |
-
{TS_BUCKETS.map((b) => (
|
| 980 |
-
<option key={b} value={b}>
|
| 981 |
-
{BUCKET_LABELS[b]}
|
| 982 |
-
</option>
|
| 983 |
-
))}
|
| 984 |
-
</select>
|
| 985 |
-
</label>
|
| 986 |
-
<label className="cg-ts-ctl">
|
| 987 |
-
<span className="cg-ts-ctl-k">Span</span>
|
| 988 |
-
<select
|
| 989 |
-
className="cg-select"
|
| 990 |
-
value={String(lastN)}
|
| 991 |
-
onChange={(e) => onDisplay?.({ tsSpan: { lastN: Number(e.target.value) } })}
|
| 992 |
-
disabled={!onDisplay}
|
| 993 |
-
>
|
| 994 |
-
{LAST_N_CHOICES.map((n) => (
|
| 995 |
-
<option key={n} value={n}>
|
| 996 |
-
Last {n}
|
| 997 |
-
</option>
|
| 998 |
-
))}
|
| 999 |
-
</select>
|
| 1000 |
-
</label>
|
| 1001 |
-
{/* C7 / R28. An empty catalogue is an EXPLANATION, not a failure: muted ink, no icon,
|
| 1002 |
-
no alert role, and the control it replaces rather than a banner over the panel. The
|
| 1003 |
-
select is not merely disabled, because a disabled dropdown still promises a list. */}
|
| 1004 |
-
{metricCatalog.length === 0 && metricsReason ? (
|
| 1005 |
-
<div className="cg-ts-ctl">
|
| 1006 |
-
<span className="cg-ts-ctl-k">Native metric</span>
|
| 1007 |
-
<span className="cg-ts-note">{TS_METRIC_EMPTY_COPY[metricsReason]}</span>
|
| 1008 |
-
</div>
|
| 1009 |
-
) : (
|
| 1010 |
-
<label className="cg-ts-ctl">
|
| 1011 |
-
<span className="cg-ts-ctl-k">Native metric</span>
|
| 1012 |
-
<select className="cg-select" value="" disabled={!onDisplay} onChange={(event) => {
|
| 1013 |
-
const metric = metricCatalog.find((item) => item.key === event.target.value);
|
| 1014 |
-
if (!metric) return;
|
| 1015 |
-
const current = display?.tsMetrics ?? [];
|
| 1016 |
-
if (!current.some((item) => item.key === metric.key))
|
| 1017 |
-
onDisplay?.({ tsMetrics: [...current, { key: metric.key, label: metric.label }].slice(0, TS_MAX_FIELDS) });
|
| 1018 |
-
}}>
|
| 1019 |
-
<option value="">Add native metric</option>
|
| 1020 |
-
{metricCatalog.filter((metric) => !(display?.tsMetrics ?? []).some((item) => item.key === metric.key)).map((metric) => <option key={metric.key} value={metric.key}>{metric.label}</option>)}
|
| 1021 |
-
</select>
|
| 1022 |
-
</label>
|
| 1023 |
-
)}
|
| 1024 |
-
|
| 1025 |
-
{/* Item 18 — four named comparisons where there used to be one unnamed toggle.
|
| 1026 |
-
"Change vs prior" could not say WHICH prior, and there are four honest answers.
|
| 1027 |
-
|
| 1028 |
-
wave17 owner item 7 — those four sat OPEN on the bar as a labelled strip, which made
|
| 1029 |
-
this panel's most consequential control look like nothing else in the product. It is
|
| 1030 |
-
a `Popover` now: the same component Filter / Sort / Group mount, so "the same" is
|
| 1031 |
-
achieved by BEING the same rather than by resembling it (the component's own note).
|
| 1032 |
-
The count rides the label in the `Filter · 2` grammar, and `active` lights the button
|
| 1033 |
-
while any comparison is on — the strip used to be the only way to know. */}
|
| 1034 |
-
<Popover
|
| 1035 |
-
label={deltaKinds.length ? `Compare · ${deltaKinds.length}` : "Compare"}
|
| 1036 |
-
icon={<IconCompare />}
|
| 1037 |
-
active={deltaKinds.length > 0}
|
| 1038 |
-
>
|
| 1039 |
-
{() => (
|
| 1040 |
-
<div className="cg-pop-body">
|
| 1041 |
-
<div className="cg-pop-title">Compare each period with</div>
|
| 1042 |
-
<div className="cg-pop-note">
|
| 1043 |
-
Each choice adds a sub-row under every metric. A comparison that cannot be
|
| 1044 |
-
answered for a metric says so in the footnotes rather than printing a number.
|
| 1045 |
-
</div>
|
| 1046 |
-
{TS_DELTA_KINDS.map((kind) => (
|
| 1047 |
-
<label key={kind} className="cg-check-row">
|
| 1048 |
-
<input
|
| 1049 |
-
type="checkbox"
|
| 1050 |
-
checked={deltaKinds.includes(kind)}
|
| 1051 |
-
disabled={!onDisplay}
|
| 1052 |
-
onChange={() => toggleDelta(kind)}
|
| 1053 |
-
/>
|
| 1054 |
-
<span className="cg-check-label">{TS_DELTA_LABELS[kind]}</span>
|
| 1055 |
-
</label>
|
| 1056 |
-
))}
|
| 1057 |
-
</div>
|
| 1058 |
-
)}
|
| 1059 |
-
</Popover>
|
| 1060 |
-
|
| 1061 |
-
<span className="cg-ts-group">
|
| 1062 |
-
<button
|
| 1063 |
-
type="button"
|
| 1064 |
-
className={"cg-ts-tog" + (gridlines ? " is-on" : "")}
|
| 1065 |
-
aria-pressed={gridlines}
|
| 1066 |
-
disabled={!onDisplay}
|
| 1067 |
-
// The literal `false` is the ONLY storable opt-out; the default is stored by
|
| 1068 |
-
// DELETING the key. Writing `true` would be a second spelling the host drops,
|
| 1069 |
-
// and the toggle would look broken.
|
| 1070 |
-
onClick={() => onDisplay?.({ tsGridlines: gridlines ? false : undefined })}
|
| 1071 |
-
>
|
| 1072 |
-
Gridlines
|
| 1073 |
-
</button>
|
| 1074 |
-
<button
|
| 1075 |
-
type="button"
|
| 1076 |
-
className={"cg-ts-tog" + (sparkline ? " is-on" : "")}
|
| 1077 |
-
aria-pressed={sparkline}
|
| 1078 |
-
disabled={!onDisplay}
|
| 1079 |
-
onClick={() => onDisplay?.({ tsSparkline: sparkline ? undefined : true })}
|
| 1080 |
-
>
|
| 1081 |
-
Trend
|
| 1082 |
-
</button>
|
| 1083 |
-
</span>
|
| 1084 |
-
|
| 1085 |
-
{/* W47-T31 — the navigator's door.
|
| 1086 |
-
|
| 1087 |
-
⭐ GUARDED ON `onDisplay`, WHICH IS THE PREDICATE THAT ACTUALLY MATTERS: applying a
|
| 1088 |
-
saved chart IS an `onDisplay` call, so a mount that cannot write cannot open one and
|
| 1089 |
-
must not offer a button that lies.
|
| 1090 |
-
|
| 1091 |
-
⚠ BOTH SHIPPED MOUNTS PASS IT, and it is easy to read the props and assume only one
|
| 1092 |
-
does, so it is worth saying plainly. `CustomerGrid.tsx` passes the VIEW's
|
| 1093 |
-
`config.display` and persists;
|
| 1094 |
-
`RecordDetail.tsx`'s Insights embed passes its OWN local `tsDisplay` state and keeps
|
| 1095 |
-
every control on this bar live (its own note says so). The navigator therefore appears
|
| 1096 |
-
in both, which is right rather than accidental: R7 says a saved chart is "not pegged
|
| 1097 |
-
on a per view basis", and the record embed is not even a view. What the record embed
|
| 1098 |
-
gets is a chart it can apply for the length of the modal, drawn from the same listed
|
| 1099 |
-
records the grid sees. No new prop, so `CustomerGrid.tsx` stays outside this fence. */}
|
| 1100 |
-
{onDisplay && (
|
| 1101 |
-
<span className="cg-ts-group">
|
| 1102 |
-
<button
|
| 1103 |
-
type="button"
|
| 1104 |
-
className={"cg-ts-tog" + (chartNavOpen ? " is-on" : "")}
|
| 1105 |
-
aria-pressed={chartNavOpen}
|
| 1106 |
-
aria-expanded={chartNavOpen}
|
| 1107 |
-
onClick={() => setChartNavOpen((open) => !open)}
|
| 1108 |
-
>
|
| 1109 |
-
Saved charts
|
| 1110 |
-
</button>
|
| 1111 |
-
</span>
|
| 1112 |
-
)}
|
| 1113 |
-
|
| 1114 |
-
{/* ⛔ NO EXPORT BUTTON HERE (owner item 3, 2026-08-03). Export lives in the view's "…"
|
| 1115 |
-
menu, on every view, in four formats — and from a time-series view it now carries
|
| 1116 |
-
THIS SHEET rather than the rows beneath it (see `onSheet` above). A second door on
|
| 1117 |
-
one surface is how "where do I export from?" stops having an answer. */}
|
| 1118 |
-
<span className="cg-ts-pool">
|
| 1119 |
-
{locked
|
| 1120 |
-
? "This record"
|
| 1121 |
-
: `${sheet.pool.toLocaleString()} ${sheet.pool === 1 ? "customer" : "customers"}`}
|
| 1122 |
-
</span>
|
| 1123 |
-
</div>
|
| 1124 |
-
|
| 1125 |
-
{onDisplay && chartNavOpen && (
|
| 1126 |
-
<SavedChartNav
|
| 1127 |
-
database={database}
|
| 1128 |
-
current={chartConfig}
|
| 1129 |
-
/* ⛔ THE WHOLE CONFIG, ALWAYS ALL EIGHT KEYS. `SavedChartNav.tsChartConfigFrom` emits
|
| 1130 |
-
`undefined` for every key the saved chart does not carry, and the host merges with
|
| 1131 |
-
`{ ...spec, ...next }` before persisting through `JSON.stringify` — so an absent key
|
| 1132 |
-
DELETES the stored one. Forwarding only the keys present would leave a comparison or
|
| 1133 |
-
a trend line from the previously opened chart switched on underneath this one. */
|
| 1134 |
-
onApply={(config) => onDisplay?.(config)}
|
| 1135 |
-
activeId={activeChartId}
|
| 1136 |
-
onActiveId={setActiveChartId}
|
| 1137 |
-
onClose={() => setChartNavOpen(false)}
|
| 1138 |
-
/>
|
| 1139 |
-
)}
|
| 1140 |
-
|
| 1141 |
-
{selected.slice(1).some((key) => !fields.find((field) => field.key === key)?.measure?.key) && <div className="cg-ts-series-options" aria-label="Later series settings">{selected.slice(1).map((key) => {
|
| 1142 |
-
const field = fields.find((candidate) => candidate.key === key);
|
| 1143 |
-
if (!field || field.measure?.key) return null;
|
| 1144 |
-
const option = laterSeries[key] ?? { aggregation: "sum" as const, dateField: dateFields[0]?.key ?? "" };
|
| 1145 |
-
const commit = (next: LaterSeriesOption) => { const options = { ...laterSeries, [key]: next }; setLaterSeries(options); void setMetrics(selected, options); };
|
| 1146 |
-
return <div className="cg-date-holidays" key={key}><strong>{field.label}</strong><label>Aggregation<select className="cg-select" value={option.aggregation} onChange={(event) => commit({ ...option, aggregation: event.target.value as LaterSeriesOption["aggregation"] })}>{["sum", "avg", "min", "max", "count", "count_distinct"].map((aggregation) => <option key={aggregation} value={aggregation}>{aggregation.replace("_", " ")}</option>)}</select></label><label>Date field<select className="cg-select" value={option.dateField} onChange={(event) => commit({ ...option, dateField: event.target.value })}><option value="">Choose a date field</option>{dateFields.map((dateField) => <option key={dateField.key} value={dateField.key}>{dateField.label}</option>)}</select></label></div>;
|
| 1147 |
-
})}</div>}
|
| 1148 |
-
|
| 1149 |
-
{state === "error" && (
|
| 1150 |
-
<div className="cg-ts-note cg-ts-error">
|
| 1151 |
-
{errStatus === 400
|
| 1152 |
-
? "That span is too wide to bucket. Choose a shorter span or a larger period."
|
| 1153 |
-
: errStatus === 403
|
| 1154 |
-
? "None of these records are in your book."
|
| 1155 |
-
: "The time series could not be loaded. Nothing is shown rather than a guess."}
|
| 1156 |
-
</div>
|
| 1157 |
-
)}
|
| 1158 |
-
|
| 1159 |
-
{snapshotsUnplaced && (
|
| 1160 |
-
<div className="cg-ts-note">
|
| 1161 |
-
{snapshotSelected.length === 1 ? "That column has" : "Those columns have"} no period of
|
| 1162 |
-
its own, so {snapshotSelected.length === 1 ? "it is" : "they are"} shown as a snapshot
|
| 1163 |
-
across the periods on the sheet — and this sheet has no periods yet. Add one metric with
|
| 1164 |
-
a period and {snapshotSelected.length === 1 ? "it" : "they"} will appear beside it.
|
| 1165 |
-
</div>
|
| 1166 |
-
)}
|
| 1167 |
-
|
| 1168 |
-
{/* wave17 item 5 / R9 — "offered is the ruling, undisclosed is not", and its converse: a
|
| 1169 |
-
field that CANNOT be plotted is NAMED here rather than quietly missing from the picker.
|
| 1170 |
-
A reader who can see "Status" in the table and cannot find it in this list otherwise has
|
| 1171 |
-
no way to tell a refusal from an oversight.
|
| 1172 |
-
|
| 1173 |
-
⛔ COLLAPSED, AFTER THE OWNER READ IT AS BROKEN MARKUP (2026-08-03). R9's disclosure was
|
| 1174 |
-
shipped as a bare strip of every refused label — struck through, unheaded, at the small
|
| 1175 |
-
end of the type scale. On the customer table that is ~25 names, and 25 crossed-out words
|
| 1176 |
-
in a row under a toolbar do not read as "these columns have no period"; they read as a
|
| 1177 |
-
stylesheet that failed to load. The strip said WHAT but never WHY IT WAS THERE.
|
| 1178 |
-
|
| 1179 |
-
A `<details>` fixes exactly that and nothing else: the disclosure is still complete and
|
| 1180 |
-
still one click from the panel, but it now leads with a SENTENCE that says what the list
|
| 1181 |
-
is, and it is shut until asked. Native rather than a Popover — no state, keyboard and
|
| 1182 |
-
screen-reader behaviour for free, and it degrades to an open list if CSS never arrives,
|
| 1183 |
-
which is the failure this element is being fixed for. */}
|
| 1184 |
-
{classed.refused.length > 0 && (
|
| 1185 |
-
<details className="cg-ts-refused">
|
| 1186 |
-
<summary className="cg-ts-refsum">
|
| 1187 |
-
{classed.refused.length === 1
|
| 1188 |
-
? "1 column has no period of its own"
|
| 1189 |
-
: `${classed.refused.length} columns have no period of their own`}
|
| 1190 |
-
</summary>
|
| 1191 |
-
<div className="cg-ts-reflist">
|
| 1192 |
-
{classed.refused.map(({ field, why }) => (
|
| 1193 |
-
<span key={field.key} className="cg-ts-refchip" title={why}>
|
| 1194 |
-
{field.label}
|
| 1195 |
-
</span>
|
| 1196 |
-
))}
|
| 1197 |
-
</div>
|
| 1198 |
-
</details>
|
| 1199 |
-
)}
|
| 1200 |
-
|
| 1201 |
-
{/* wave17 GRID — item 3 / R6. Only the LOADING note becomes a spinner; the refusal notes
|
| 1202 |
-
above it keep their words, because "could not be loaded" is an answer and R6 is about
|
| 1203 |
-
the wait. A spinner in place of a refusal would spin forever. */}
|
| 1204 |
-
{state === "loading" && !payload && (
|
| 1205 |
-
<div className="cg-ts-note">
|
| 1206 |
-
<span className="lp-spin" role="status" aria-label="Loading" />
|
| 1207 |
-
</div>
|
| 1208 |
-
)}
|
| 1209 |
-
|
| 1210 |
-
{payload && (
|
| 1211 |
-
<div className="cg-ts-scroll">
|
| 1212 |
-
<table className={"cg-ts-table" + (gridlines ? "" : " is-nogrid")}>
|
| 1213 |
-
<thead>
|
| 1214 |
-
<tr>
|
| 1215 |
-
<th className="cg-ts-stick">Metric</th>
|
| 1216 |
-
{sheet.columns.map((c) => (
|
| 1217 |
-
<th key={c.key} className={c.partial ? "is-partial" : undefined}>
|
| 1218 |
-
{c.label}
|
| 1219 |
-
{c.partial && <span className="cg-ts-partial"> · partial</span>}
|
| 1220 |
-
</th>
|
| 1221 |
-
))}
|
| 1222 |
-
<th className="cg-ts-total">Total</th>
|
| 1223 |
-
{sparkline && <th className="cg-ts-sparkhead">Trend</th>}
|
| 1224 |
-
</tr>
|
| 1225 |
-
</thead>
|
| 1226 |
-
<tbody>
|
| 1227 |
-
{sheet.rows.map((row) => (
|
| 1228 |
-
<TsRowBlock
|
| 1229 |
-
key={row.id}
|
| 1230 |
-
row={row}
|
| 1231 |
-
sheet={sheet}
|
| 1232 |
-
style={resolveTsStyle(styles, row.id)}
|
| 1233 |
-
styles={styles}
|
| 1234 |
-
sparkline={sparkline}
|
| 1235 |
-
charted={charted.has(row.id)}
|
| 1236 |
-
editable={!!onDisplay}
|
| 1237 |
-
metricRow={table.rows.find((r) => r.field === row.id)}
|
| 1238 |
-
formulaReferences={formulaReferences}
|
| 1239 |
-
formulaFunctions={formulaContract?.functions ?? []}
|
| 1240 |
-
formulaExample={formulaContract?.example ?? formulaContract?.reference.example}
|
| 1241 |
-
formulaMaxSource={formulaContract?.maxSource}
|
| 1242 |
-
formulaPreviewError={formulaPreviewErrors[row.id]}
|
| 1243 |
-
formulaPreviewValue={formulaPreviewValues[row.id]}
|
| 1244 |
-
onToggleChart={() => toggleChart(row.id)}
|
| 1245 |
-
onOpenCell={(col) => void openContributors(table.rows.find((r) => r.field === row.id), col.to)}
|
| 1246 |
-
onStyle={(patch) => setStyle(row.id, patch)}
|
| 1247 |
-
onRemove={() => {
|
| 1248 |
-
if (row.kind === "metric")
|
| 1249 |
-
setMetrics(selected.filter((k) => k !== row.id));
|
| 1250 |
-
else setRows(customRows.filter((r) => r.id !== row.id));
|
| 1251 |
-
}}
|
| 1252 |
-
onEditRow={(patch) =>
|
| 1253 |
-
setRows(customRows.map((r) => (r.id === row.id ? { ...r, ...patch } : r)))
|
| 1254 |
-
}
|
| 1255 |
-
/>
|
| 1256 |
-
))}
|
| 1257 |
-
{/* Item 17 — the sheet GROWS from its bottom edge, the way a spreadsheet does.
|
| 1258 |
-
This row is both the list of what could be added and the control that adds
|
| 1259 |
-
it; a picker somewhere else would be a second inventory to keep in sync. */}
|
| 1260 |
-
{onDisplay && (
|
| 1261 |
-
<tr className="cg-ts-addrow">
|
| 1262 |
-
<th className="cg-ts-stick" colSpan={colCount}>
|
| 1263 |
-
<span className="cg-ts-addbar">
|
| 1264 |
-
{/* C-FLDSEL (item 20) — the type mark travels with the name. `value` is
|
| 1265 |
-
deliberately left UNSET: this control never displays a choice, it
|
| 1266 |
-
only makes one, so the placeholder IS its resting state (which is
|
| 1267 |
-
also the scar the contract names — a native <select> with no value
|
| 1268 |
-
paints its first option and claims a choice nobody made). */}
|
| 1269 |
-
<FieldSelectButton
|
| 1270 |
-
fields={unused}
|
| 1271 |
-
value={undefined}
|
| 1272 |
-
onChange={(key) => {
|
| 1273 |
-
const field = fields.find((candidate) => candidate.key === key);
|
| 1274 |
-
const options = !field?.measure?.key && selected.length
|
| 1275 |
-
? { ...laterSeries, [key]: { aggregation: "sum" as const, dateField: dateFields[0]?.key ?? "" } }
|
| 1276 |
-
: laterSeries;
|
| 1277 |
-
setLaterSeries(options);
|
| 1278 |
-
void setMetrics([...selected, key], options);
|
| 1279 |
-
}}
|
| 1280 |
-
className="cg-select cg-ts-addsel"
|
| 1281 |
-
ariaLabel="Add a metric row"
|
| 1282 |
-
disabled={!unused.length || selected.length >= TS_MAX_FIELDS}
|
| 1283 |
-
placeholder={
|
| 1284 |
-
!unused.length
|
| 1285 |
-
? "Every metric is on the sheet"
|
| 1286 |
-
: selected.length >= TS_MAX_FIELDS
|
| 1287 |
-
? `At the ${TS_MAX_FIELDS}-metric limit`
|
| 1288 |
-
: "+ Add metric"
|
| 1289 |
-
}
|
| 1290 |
-
/>
|
| 1291 |
-
<button
|
| 1292 |
-
type="button"
|
| 1293 |
-
className="cg-ts-tog"
|
| 1294 |
-
disabled={customRows.length >= TS_MAX_CUSTOM_ROWS}
|
| 1295 |
-
onClick={() =>
|
| 1296 |
-
setRows([
|
| 1297 |
-
...customRows,
|
| 1298 |
-
{ id: newRowId(customRows), kind: "note", label: "" },
|
| 1299 |
-
])
|
| 1300 |
-
}
|
| 1301 |
-
>
|
| 1302 |
-
+ Note
|
| 1303 |
-
</button>
|
| 1304 |
-
<button
|
| 1305 |
-
type="button"
|
| 1306 |
-
className="cg-ts-tog"
|
| 1307 |
-
disabled={customRows.length >= TS_MAX_CUSTOM_ROWS}
|
| 1308 |
-
onClick={() =>
|
| 1309 |
-
setRows([
|
| 1310 |
-
...customRows,
|
| 1311 |
-
{ id: newRowId(customRows), kind: "formula", label: "", expr: "" },
|
| 1312 |
-
])
|
| 1313 |
-
}
|
| 1314 |
-
>
|
| 1315 |
-
+ Formula
|
| 1316 |
-
</button>
|
| 1317 |
-
</span>
|
| 1318 |
-
</th>
|
| 1319 |
-
</tr>
|
| 1320 |
-
)}
|
| 1321 |
-
</tbody>
|
| 1322 |
-
</table>
|
| 1323 |
-
</div>
|
| 1324 |
-
)}
|
| 1325 |
-
|
| 1326 |
-
{payload && sheet.empty && (
|
| 1327 |
-
<div className="cg-ts-note">No metrics returned a series for this span.</div>
|
| 1328 |
-
)}
|
| 1329 |
-
|
| 1330 |
-
{sheet.notes.length > 0 && (
|
| 1331 |
-
<ul className="cg-ts-notes">
|
| 1332 |
-
{sheet.notes.map((n) => (
|
| 1333 |
-
<li key={n}>{n}</li>
|
| 1334 |
-
))}
|
| 1335 |
-
</ul>
|
| 1336 |
-
)}
|
| 1337 |
-
</div>
|
| 1338 |
-
);
|
| 1339 |
-
}
|
| 1340 |
-
|
| 1341 |
-
/** A row's own controls: emphasis, then removal. Hover-revealed, always in the tab order. */
|
| 1342 |
-
function RowTools({
|
| 1343 |
-
style,
|
| 1344 |
-
editable,
|
| 1345 |
-
onStyle,
|
| 1346 |
-
onRemove,
|
| 1347 |
-
label,
|
| 1348 |
-
}: {
|
| 1349 |
-
style: TsCellStyle;
|
| 1350 |
-
editable: boolean;
|
| 1351 |
-
onStyle: (patch: TsCellStyle) => void;
|
| 1352 |
-
onRemove: () => void;
|
| 1353 |
-
label: string;
|
| 1354 |
-
}) {
|
| 1355 |
-
if (!editable) return null;
|
| 1356 |
-
return (
|
| 1357 |
-
<span className="cg-ts-rowtools">
|
| 1358 |
-
<button
|
| 1359 |
-
type="button"
|
| 1360 |
-
className={"cg-ts-rowtool" + (style.bold ? " is-on" : "")}
|
| 1361 |
-
aria-pressed={!!style.bold}
|
| 1362 |
-
aria-label={`Bold ${label}`}
|
| 1363 |
-
title="Bold"
|
| 1364 |
-
onClick={() => onStyle({ bold: style.bold ? undefined : true })}
|
| 1365 |
-
>
|
| 1366 |
-
B
|
| 1367 |
-
</button>
|
| 1368 |
-
<button
|
| 1369 |
-
type="button"
|
| 1370 |
-
className={"cg-ts-rowtool" + (style.line ? " is-on" : "")}
|
| 1371 |
-
aria-pressed={!!style.line}
|
| 1372 |
-
aria-label={`Rule above ${label}`}
|
| 1373 |
-
title="Rule above"
|
| 1374 |
-
onClick={() => onStyle({ line: style.line ? undefined : true })}
|
| 1375 |
-
>
|
| 1376 |
-
―
|
| 1377 |
-
</button>
|
| 1378 |
-
<button
|
| 1379 |
-
type="button"
|
| 1380 |
-
className="cg-ts-rowtool"
|
| 1381 |
-
aria-label={`Remove ${label}`}
|
| 1382 |
-
title="Remove row"
|
| 1383 |
-
onClick={onRemove}
|
| 1384 |
-
>
|
| 1385 |
-
×
|
| 1386 |
-
</button>
|
| 1387 |
-
</span>
|
| 1388 |
-
);
|
| 1389 |
-
}
|
| 1390 |
-
|
| 1391 |
-
/**
|
| 1392 |
-
* One sheet row: its values, its delta sub-rows, and an optional line chart.
|
| 1393 |
-
*
|
| 1394 |
-
* The chart is built from `tsRowToChartModel`, NOT from `viz/chartData.buildChartData` — see
|
| 1395 |
-
* that function's note. `buildChartData` caps at 12 buckets, which for a time series means
|
| 1396 |
-
* silently deleting periods.
|
| 1397 |
-
*/
|
| 1398 |
-
function TsRowBlock({
|
| 1399 |
-
row,
|
| 1400 |
-
sheet,
|
| 1401 |
-
style,
|
| 1402 |
-
styles,
|
| 1403 |
-
sparkline,
|
| 1404 |
-
charted,
|
| 1405 |
-
editable,
|
| 1406 |
-
metricRow,
|
| 1407 |
-
formulaReferences,
|
| 1408 |
-
formulaFunctions,
|
| 1409 |
-
formulaExample,
|
| 1410 |
-
formulaMaxSource,
|
| 1411 |
-
formulaPreviewError,
|
| 1412 |
-
formulaPreviewValue,
|
| 1413 |
-
onToggleChart,
|
| 1414 |
-
onOpenCell,
|
| 1415 |
-
onStyle,
|
| 1416 |
-
onRemove,
|
| 1417 |
-
onEditRow,
|
| 1418 |
-
}: {
|
| 1419 |
-
row: TsSheetRow;
|
| 1420 |
-
sheet: TsSheet;
|
| 1421 |
-
style: TsCellStyle;
|
| 1422 |
-
styles: Record<string, TsCellStyle> | undefined;
|
| 1423 |
-
sparkline: boolean;
|
| 1424 |
-
charted: boolean;
|
| 1425 |
-
editable: boolean;
|
| 1426 |
-
metricRow: TsTableRow | undefined;
|
| 1427 |
-
formulaReferences: { key: string; label: string; source: string }[];
|
| 1428 |
-
formulaFunctions: FormulaFunctionHelp[];
|
| 1429 |
-
formulaExample?: string;
|
| 1430 |
-
formulaMaxSource?: number;
|
| 1431 |
-
formulaPreviewError?: string;
|
| 1432 |
-
formulaPreviewValue: TsFormulaValue | undefined;
|
| 1433 |
-
onToggleChart: () => void;
|
| 1434 |
-
onOpenCell: (column: TsColumn) => void;
|
| 1435 |
-
onStyle: (patch: TsCellStyle) => void;
|
| 1436 |
-
onRemove: () => void;
|
| 1437 |
-
onEditRow: (patch: Partial<TsCustomRow>) => void;
|
| 1438 |
-
}) {
|
| 1439 |
-
const spec = useMemo(() => {
|
| 1440 |
-
if (!charted || !metricRow) return null;
|
| 1441 |
-
const model = tsRowToChartModel(metricRow, sheet.columns);
|
| 1442 |
-
if (!model.points.length) return null;
|
| 1443 |
-
return toVegaLiteSpec({
|
| 1444 |
-
spec: { id: row.id, kind: "line", agg: (row.agg ?? "sum") as never },
|
| 1445 |
-
model,
|
| 1446 |
-
yTitle: row.label,
|
| 1447 |
-
formatValue: (n) => n.toLocaleString(undefined, { maximumFractionDigits: 2 }),
|
| 1448 |
-
});
|
| 1449 |
-
}, [charted, metricRow, sheet.columns, row.id, row.agg, row.label]);
|
| 1450 |
-
|
| 1451 |
-
const colCount = sheet.columns.length + 2 + (sparkline ? 1 : 0);
|
| 1452 |
-
const rowCls =
|
| 1453 |
-
(style.line ? "is-ruled" : "") + (style.bold ? " is-bold" : "") || undefined;
|
| 1454 |
-
|
| 1455 |
-
// A NOTE row is a label across the sheet — a section heading in a financial model, not a
|
| 1456 |
-
// series with empty cells. Spanning it is what stops twelve blank cells from reading as
|
| 1457 |
-
// twelve unanswerable ones ("—" already means something else here).
|
| 1458 |
-
if (row.kind === "note") {
|
| 1459 |
-
return (
|
| 1460 |
-
<tr className={"cg-ts-noterow " + (rowCls ?? "")}>
|
| 1461 |
-
<th className="cg-ts-stick" colSpan={colCount}>
|
| 1462 |
-
<span className="cg-ts-rowhead">
|
| 1463 |
-
{editable ? (
|
| 1464 |
-
<input
|
| 1465 |
-
className="cg-ts-rowinput"
|
| 1466 |
-
value={row.label}
|
| 1467 |
-
maxLength={TS_ROW_LABEL_MAX}
|
| 1468 |
-
placeholder="Note: type a heading for this section"
|
| 1469 |
-
aria-label="Note row label"
|
| 1470 |
-
onChange={(e) => onEditRow({ label: e.target.value })}
|
| 1471 |
-
/>
|
| 1472 |
-
) : (
|
| 1473 |
-
<span className="cg-ts-rowlabel">{row.label}</span>
|
| 1474 |
-
)}
|
| 1475 |
-
<RowTools
|
| 1476 |
-
style={style}
|
| 1477 |
-
editable={editable}
|
| 1478 |
-
onStyle={onStyle}
|
| 1479 |
-
onRemove={onRemove}
|
| 1480 |
-
label={row.label || "note row"}
|
| 1481 |
-
/>
|
| 1482 |
-
</span>
|
| 1483 |
-
</th>
|
| 1484 |
-
</tr>
|
| 1485 |
-
);
|
| 1486 |
-
}
|
| 1487 |
-
|
| 1488 |
-
return (
|
| 1489 |
-
<>
|
| 1490 |
-
<tr className={rowCls}>
|
| 1491 |
-
<th scope="row" className="cg-ts-stick">
|
| 1492 |
-
<span className="cg-ts-rowhead">
|
| 1493 |
-
<span className="cg-ts-rowmain">
|
| 1494 |
-
{row.kind === "formula" ? (
|
| 1495 |
-
editable ? (
|
| 1496 |
-
<input
|
| 1497 |
-
className="cg-ts-rowinput"
|
| 1498 |
-
value={row.label}
|
| 1499 |
-
maxLength={TS_ROW_LABEL_MAX}
|
| 1500 |
-
placeholder="Formula row name"
|
| 1501 |
-
aria-label="Formula row label"
|
| 1502 |
-
onChange={(e) => onEditRow({ label: e.target.value })}
|
| 1503 |
-
/>
|
| 1504 |
-
) : (
|
| 1505 |
-
<span className="cg-ts-rowlabel">{row.label}</span>
|
| 1506 |
-
)
|
| 1507 |
-
) : (
|
| 1508 |
-
<button
|
| 1509 |
-
type="button"
|
| 1510 |
-
className="cg-ts-rowbtn"
|
| 1511 |
-
onClick={onToggleChart}
|
| 1512 |
-
aria-pressed={charted}
|
| 1513 |
-
title={charted ? "Show as a row of numbers" : "Show as a line"}
|
| 1514 |
-
>
|
| 1515 |
-
{row.label}
|
| 1516 |
-
</button>
|
| 1517 |
-
)}
|
| 1518 |
-
{/* R1 — the metric's OWN window. Two rows under the same month headings can be
|
| 1519 |
-
a cumulative year-to-date and a trailing 90 days; without this line they
|
| 1520 |
-
look like the same kind of number. */}
|
| 1521 |
-
{row.sublabel && <span className="cg-ts-rowsub">{row.sublabel}</span>}
|
| 1522 |
-
{row.kind === "formula" &&
|
| 1523 |
-
(editable ? (
|
| 1524 |
-
<input
|
| 1525 |
-
className="cg-ts-rowinput cg-ts-rowexpr"
|
| 1526 |
-
list={`cg-formula-help-${row.id}`}
|
| 1527 |
-
value={row.expr ?? ""}
|
| 1528 |
-
maxLength={formulaMaxSource ?? TS_MAX_EXPR}
|
| 1529 |
-
spellCheck={false}
|
| 1530 |
-
placeholder={formulaExample ?? "Enter a formula"}
|
| 1531 |
-
aria-label="Formula"
|
| 1532 |
-
onChange={(e) => onEditRow({ expr: e.target.value })}
|
| 1533 |
-
/>
|
| 1534 |
-
) : (
|
| 1535 |
-
<span className="cg-ts-rowsub">{row.expr}</span>
|
| 1536 |
-
))}
|
| 1537 |
-
{row.kind === "formula" && editable && <>
|
| 1538 |
-
<datalist id={`cg-formula-help-${row.id}`}>
|
| 1539 |
-
{formulaReferences.map((reference) => (
|
| 1540 |
-
<option key={reference.key} value={reference.source}>{reference.label}</option>
|
| 1541 |
-
))}
|
| 1542 |
-
{formulaFunctions.filter((fn) => fn.example).map((fn) => (
|
| 1543 |
-
<option key={fn.name} value={fn.example}>{fn.name}</option>
|
| 1544 |
-
))}
|
| 1545 |
-
</datalist>
|
| 1546 |
-
<details className="cg-formula-help">
|
| 1547 |
-
<summary>Function help</summary>
|
| 1548 |
-
{formulaFunctions.length ? (
|
| 1549 |
-
<ul>
|
| 1550 |
-
{formulaFunctions.map((fn) => (
|
| 1551 |
-
<li key={fn.name}>
|
| 1552 |
-
<strong>{fn.name}</strong>
|
| 1553 |
-
{fn.example ? <code>{fn.example}</code> : null}
|
| 1554 |
-
</li>
|
| 1555 |
-
))}
|
| 1556 |
-
</ul>
|
| 1557 |
-
) : (
|
| 1558 |
-
<span>Formula help comes from the server.</span>
|
| 1559 |
-
)}
|
| 1560 |
-
</details>
|
| 1561 |
-
{formulaPreviewError && <span className="cg-ts-rowsub" role="alert">{formulaPreviewError}</span>}
|
| 1562 |
-
{formulaPreviewValue !== undefined && (
|
| 1563 |
-
<span className="cg-ts-rowsub" aria-label="Formula preview">
|
| 1564 |
-
Preview: {formulaPreviewValue == null ? "Blank" : formatTsValue(formulaPreviewValue, tsDisplayNumber)}
|
| 1565 |
-
</span>
|
| 1566 |
-
)}
|
| 1567 |
-
</>}
|
| 1568 |
-
</span>
|
| 1569 |
-
<RowTools
|
| 1570 |
-
style={style}
|
| 1571 |
-
editable={editable}
|
| 1572 |
-
onStyle={onStyle}
|
| 1573 |
-
onRemove={onRemove}
|
| 1574 |
-
label={row.label || "row"}
|
| 1575 |
-
/>
|
| 1576 |
-
</span>
|
| 1577 |
-
</th>
|
| 1578 |
-
{row.cells.map((c, i) => {
|
| 1579 |
-
const col = sheet.columns[i];
|
| 1580 |
-
const cellStyle = resolveTsStyle(styles, row.id, col?.key);
|
| 1581 |
-
return (
|
| 1582 |
-
<td
|
| 1583 |
-
key={col?.key ?? i}
|
| 1584 |
-
className={
|
| 1585 |
-
(c.partial ? "is-partial" : "") + (cellStyle.bold ? " is-bold" : "") || undefined
|
| 1586 |
-
}
|
| 1587 |
-
>
|
| 1588 |
-
{/* item 6 — `tsDisplayNumber`, never an inline toLocaleString: the CSV calls the
|
| 1589 |
-
same function, and that is the only thing making "the file matches the sheet"
|
| 1590 |
-
a property rather than a coincidence. */}
|
| 1591 |
-
{row.kind === "metric" && c.value != null ? (
|
| 1592 |
-
<button type="button" className="cg-ts-cellbtn" onClick={() => col && onOpenCell(col)} title="Show contributing records">
|
| 1593 |
-
{formatTsValue(c.value, tsDisplayNumber)}
|
| 1594 |
-
</button>
|
| 1595 |
-
) : formatTsValue(c.value, tsDisplayNumber)}
|
| 1596 |
-
</td>
|
| 1597 |
-
);
|
| 1598 |
-
})}
|
| 1599 |
-
<td className="cg-ts-total">
|
| 1600 |
-
{/* An avg/min/max row has NO total — the cell stays empty rather than carrying an
|
| 1601 |
-
average of averages. See timeSeriesData's header note (2). Formula and note rows
|
| 1602 |
-
carry none either: an arbitrary expression is not additive across periods. */}
|
| 1603 |
-
{row.total == null ? "" : tsDisplayNumber(row.total)}
|
| 1604 |
-
</td>
|
| 1605 |
-
{sparkline && (
|
| 1606 |
-
<td className="cg-ts-spark">
|
| 1607 |
-
<Sparkline
|
| 1608 |
-
values={row.cells.map((c) => typeof c.value === "number" ? c.value : null)}
|
| 1609 |
-
label={row.label}
|
| 1610 |
-
/>
|
| 1611 |
-
</td>
|
| 1612 |
-
)}
|
| 1613 |
-
</tr>
|
| 1614 |
-
{row.deltas.map((d) => (
|
| 1615 |
-
<TsDeltaRow key={d.kind} delta={d} sparkline={sparkline} />
|
| 1616 |
-
))}
|
| 1617 |
-
{charted && (
|
| 1618 |
-
<tr className="cg-ts-chartrow">
|
| 1619 |
-
<td colSpan={colCount}>
|
| 1620 |
-
{spec ? (
|
| 1621 |
-
<VegaLiteChart spec={spec} label={`${row.label} over time`} />
|
| 1622 |
-
) : (
|
| 1623 |
-
<div className="cg-ts-note">
|
| 1624 |
-
Nothing to plot: every period for this metric is unanswered.
|
| 1625 |
-
</div>
|
| 1626 |
-
)}
|
| 1627 |
-
</td>
|
| 1628 |
-
</tr>
|
| 1629 |
-
)}
|
| 1630 |
-
</>
|
| 1631 |
-
);
|
| 1632 |
-
}
|
| 1633 |
-
|
| 1634 |
-
/**
|
| 1635 |
-
* One comparison sub-row.
|
| 1636 |
-
*
|
| 1637 |
-
* ONE typography for all four (item 18's "standardized type"): the same 2xs size, the sign
|
| 1638 |
-
* carried by a `-deep` tint, refusals as "—". A comparison that cannot be answered AT ALL
|
| 1639 |
-
* (no year in the span; year-to-date growth asked of a trailing-90 row) renders its dashes and
|
| 1640 |
-
* the sheet's footnotes say why once — the alternative is a column of dashes indistinguishable
|
| 1641 |
-
* from missing data.
|
| 1642 |
-
*/
|
| 1643 |
-
function TsDeltaRow({
|
| 1644 |
-
delta,
|
| 1645 |
-
sparkline,
|
| 1646 |
-
}: {
|
| 1647 |
-
delta: TsDeltaSubRow;
|
| 1648 |
-
sparkline: boolean;
|
| 1649 |
-
}) {
|
| 1650 |
-
return (
|
| 1651 |
-
<tr className="cg-ts-delta">
|
| 1652 |
-
<th scope="row" className="cg-ts-stick">
|
| 1653 |
-
{delta.label}
|
| 1654 |
-
</th>
|
| 1655 |
-
{delta.values.map((v, i) => (
|
| 1656 |
-
<td key={i} className={v == null ? undefined : v >= 0 ? "is-up" : "is-down"}>
|
| 1657 |
-
{delta.percent
|
| 1658 |
-
? formatTsDelta(v)
|
| 1659 |
-
: v == null
|
| 1660 |
-
? "—"
|
| 1661 |
-
: `${v > 0 ? "+" : ""}${tsDisplayNumber(v)}`}
|
| 1662 |
-
</td>
|
| 1663 |
-
))}
|
| 1664 |
-
<td className="cg-ts-total" />
|
| 1665 |
-
{sparkline && <td className="cg-ts-spark" />}
|
| 1666 |
-
</tr>
|
| 1667 |
-
);
|
| 1668 |
-
}
|
| 1669 |
-
|
| 1670 |
-
/**
|
| 1671 |
-
* The trend column: a hand-rolled polyline, no library.
|
| 1672 |
-
*
|
| 1673 |
-
* ⚠ Gaps BREAK the line rather than being bridged. A stroke drawn straight across an
|
| 1674 |
-
* unanswerable period asserts a value for it — the same lie the table refuses one cell to the
|
| 1675 |
-
* left, at 72 pixels wide.
|
| 1676 |
-
*/
|
| 1677 |
-
function Sparkline({ values, label }: { values: (number | null)[]; label: string }) {
|
| 1678 |
-
const segments = useMemo(
|
| 1679 |
-
() => sparklineSegments(values, SPARK_W, SPARK_H),
|
| 1680 |
-
[values]
|
| 1681 |
-
);
|
| 1682 |
-
if (!segments.length) return <span className="cg-ts-sparkempty">—</span>;
|
| 1683 |
-
const answered = values.filter((v) => v != null).length;
|
| 1684 |
-
return (
|
| 1685 |
-
<svg
|
| 1686 |
-
className="cg-ts-sparksvg"
|
| 1687 |
-
width={SPARK_W}
|
| 1688 |
-
height={SPARK_H}
|
| 1689 |
-
viewBox={`0 0 ${SPARK_W} ${SPARK_H}`}
|
| 1690 |
-
role="img"
|
| 1691 |
-
aria-label={`${label}: trend over ${answered} of ${values.length} periods`}
|
| 1692 |
-
>
|
| 1693 |
-
{segments.map((s, i) => (
|
| 1694 |
-
<polyline
|
| 1695 |
-
key={i}
|
| 1696 |
-
points={sparklinePoints(s)}
|
| 1697 |
-
fill="none"
|
| 1698 |
-
stroke="currentColor"
|
| 1699 |
-
strokeWidth="1.25"
|
| 1700 |
-
strokeLinejoin="round"
|
| 1701 |
-
strokeLinecap="round"
|
| 1702 |
-
/>
|
| 1703 |
-
))}
|
| 1704 |
-
</svg>
|
| 1705 |
-
);
|
| 1706 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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