From 4106b9becd306d56ab3db9be7d1c9f65ca4d4206 Mon Sep 17 00:00:00 2001 From: Arvi23 Date: Wed, 4 Nov 2026 19:16:22 +0200 Subject: [PATCH] Batch 7: English / Romanian switch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - EN/RO switch in the home top bar and in Settings; the choice is a ws_lang cookie, so it's known at page load and sent with every request (D15). - Frontend: static/js/i18n.js with a Romanian dictionary keyed by the English text (~300 strings). Static and dynamically inserted text is translated automatically by a MutationObserver; strings with variables use t(). News, LLM output and chat are marked no-i18n. Numbers, money and dates are locale-aware (fmtN, Intl with ro-RO). - Backend: watchstock/i18n.py (tr, num) and a middleware that sets the request language. Score breakdowns, labels and flags, Today events (with Romanian dates), portfolio flags, warnings and errors are localised. Scores are now computed at serve time, so a language switch applies to cached snapshots. The LLM is told to write in Romanian. - tests/test_i18n.py enforces complete dictionaries (backend tr() literals, frontend t() calls, every string in index.html) and matching placeholders. The UI smoke test audits Romanian pages for leftover English. It caught a MutationObserver infinite loop on identical translations ("P/E") and the logo turning into "WatchAcțiune". - CLAUDE.md: translation rules for future changes. 109 backend tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TW7cJeWrcBW5SJHr4ZKtSH --- CLAUDE.md | 10 +- README.md | 1 + docs/ARCHITECTURE.md | 5 +- docs/DECISIONS.md | 14 ++ docs/HANDOFF.md | 44 +++- pyproject.toml | 3 +- scripts/ui_smoke.js | 42 ++++ static/index.html | 30 ++- static/js/analysis.js | 6 +- static/js/chat.js | 12 +- static/js/core.js | 15 +- static/js/dashboard.js | 74 +++--- static/js/home.js | 8 +- static/js/i18n.js | 391 +++++++++++++++++++++++++++++ static/js/portfolio.js | 56 ++--- static/js/scores.js | 6 +- static/js/search.js | 10 +- static/js/settings.js | 2 +- static/js/today.js | 4 +- tests/conftest.py | 4 +- tests/test_i18n.py | 173 +++++++++++++ uv.lock | 2 +- watchstock/__init__.py | 2 +- watchstock/analysis.py | 20 +- watchstock/app.py | 11 +- watchstock/i18n.py | 152 +++++++++++ watchstock/portfolio.py | 26 +- watchstock/providers/openrouter.py | 3 +- watchstock/routes/portfolio.py | 5 +- watchstock/scoring.py | 152 ++++++++--- watchstock/services.py | 23 +- watchstock/today.py | 56 ++++- 32 files changed, 1165 insertions(+), 197 deletions(-) create mode 100644 static/js/i18n.js create mode 100644 tests/test_i18n.py create mode 100644 watchstock/i18n.py diff --git a/CLAUDE.md b/CLAUDE.md index a24dee5..ff98748 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,7 +51,15 @@ the right Python and dependencies by itself. Nothing needs to be pre-installed. - LLM output is untrusted: render markdown only through `renderMarkdown()` (DOMPurify). Never assign model text to `innerHTML` directly. Escape external text with `esc()`. - Money: use `fmtMoney`/`fmtBig` with `priceCurrency()` for prices and - `statementCurrency()` for statement values. Never hardcode `$`. + `statementCurrency()` for statement values. Never hardcode `$`. Other displayed numbers + go through `fmtN()` (locale-aware); numbers used in CSS stay plain. +- **Every user-visible string is translatable (English / Romanian)**, English text = key: + - Frontend: exact static strings are translated automatically. Just add the English → + Romanian pair to `RO` in `static/js/i18n.js`. Strings with variables use + `t('Saved {ticker}.', { ticker })`. Mark containers of external/LLM text `no-i18n`. + - Backend: `tr("Net margin {pct}", pct=num(x) + "%")` with the pair in `watchstock/i18n.py`. + - `tests/test_i18n.py` fails if a string is missing from either dictionary. Never name a + local variable `t` in frontend code (it shadows the translator). - Keep the UI simple. Every new panel must earn its place for a portfolio owner. ## Workflow diff --git a/README.md b/README.md index b47e3af..2c80550 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ Download the new ZIP and copy your old `data` folder into it (or `git pull`). Reports are saved with their date and model. - **News tab:** recent headlines for the stock. - **Chat:** ask follow-up questions about the loaded company. +- **English / Română:** switch with EN/RO at the top right. The AI writes in the chosen language too. Data is cached for a few hours; the **REFRESH** button next to the ticker fetches it again, and the label beside it shows how old the data is. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1938c04..c83755f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -13,6 +13,7 @@ watchstock/app.py FastAPI app factory, error → 502 mapping, static │ ├── services.py snapshot freshness: cache hit / live fetch / stale fallback ├── scoring.py pure scoring functions → opportunity pillars + safety, with breakdowns + ├── i18n.py English/Romanian: tr(), num(), request language (cookie → ContextVar) ├── symbols.py Yahoo ↔ TradingView ticker translation ├── portfolio.py pure portfolio math: value, P/L, weights, allocation, flags, dividends ├── today.py pure "Today" event builder (earnings, ex-div, moves, ratings, insider buys) @@ -34,6 +35,7 @@ watchstock/app.py FastAPI app factory, error → 502 mapping, static | `css/tailwind.css` | precompiled Tailwind (generated from `tailwind.config.js`; `npm run build:css`) | | `css/app.css` | fonts, theme variables, component styles, markdown (`.prose`) styles | | `vendor/` | pinned Chart.js, marked, DOMPurify, Inter font (`npm run vendor`) | +| `js/i18n.js` | language (cookie `ws_lang`), Romanian dictionary, `t()`, `fmtN()`, auto-translation | | `js/core.js` | `api()`, `esc()`, `renderMarkdown()`, money formatting, DOM handles, toast | | `js/charts.js` | Chart.js helpers | | `js/scores.js` | breakdown popover + safety modal | @@ -60,7 +62,8 @@ UI against `scripts/fake_server.py` in CI. - Profile failure with no saved snapshot → `MarketDataError` → HTTP 502 with a message. - Profile failure with an old snapshot → old one returned with `stale: true` + warning. - News failure → empty news + warning; the rest still works. -4. The latest stored AI report (if any) is attached as `ai_analysis`. +4. Scores are computed from the snapshot at serve time (`services.with_scores`) in the request's + language, and the latest stored AI report (if any) is attached as `ai_analysis`. 5. If there is none, the UI immediately calls `POST /api/stocks/MSFT/analysis`, which runs the LLM on the snapshot and stores the report only if it parsed correctly. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 7bf56d7..75c6365 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -108,3 +108,17 @@ e.g. "33.4 vs industry median 45.0 (-26%)". Otherwise the fixed bands still appl industry lists are US companies, so non-USD stocks get no peers rather than a misleading comparison. Peer lists and peer metrics (one `info` call each) are cached in memory for 24 h and fetched 4 at a time; a failed peer is skipped. Snapshot schema 3. + +## D15 — English/Romanian: English strings are the keys; language in a cookie (2026-11-04) +gettext-style dictionaries (`static/js/i18n.js`, `watchstock/i18n.py`) keyed by the English +text, so the code stays readable and a missing translation shows English instead of breaking. +The frontend translates static and dynamically inserted text automatically (a +MutationObserver matches exact strings; only text with variables needs `t()`). Containers +of external text (news, LLM output, chat) are marked `no-i18n` so a headline like "Hold" +isn't "translated". The language is a `ws_lang` cookie: known synchronously at page load, +and sent with every request, so the backend localises score breakdowns, panel events and +errors and tells the LLM to write in Romanian (JSON keys/enums stay English). Scores are +now computed at serve time from the cached snapshot (cheap, language-aware, and formula +changes apply without refetching). Switching language reloads the page. Numbers and dates +follow the locale (1.234,56 in Romanian). Stored AI reports stay in the language they were +written in. Tests enforce dictionary completeness. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index ce3cf89..7a0ce85 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -92,6 +92,35 @@ Read this first. Update it at the end of every batch or before your context runs - [x] Debt/Equity card shows "0.30x" like the breakdown (Yahoo's raw value is percent) - [x] 96 backend tests; UI smoke checks the peer table and relative P/E +### Batch 7 — English / Romanian *(branch `batch-7-language`, PR #7, stacked on #6)* ✅ +- [x] EN/RO switch in the home top bar and in Settings (`ws_lang` cookie, page reload) (D15) +- [x] Frontend: `static/js/i18n.js` dictionary (~300 strings), automatic translation of static and + inserted text, `t()` for strings with variables, `fmtN()` + locale-aware money/dates +- [x] Backend: `watchstock/i18n.py` (`tr`, `num`), middleware sets the request language; score + breakdowns, labels, flags, Today events (Romanian dates), portfolio flags, warnings and errors + localised; scores computed at serve time; LLM writes reports/thesis checks/chat in Romanian +- [x] `tests/test_i18n.py` enforces complete dictionaries; UI smoke audits Romanian pages for + leftover English. Caught: a MutationObserver infinite loop on identical translations, and + the logo turning into "WatchAcțiune" + +### Batch 8 — History, Tradeville import, highlights, model presets (next) +- **Tradeville import** (owner sent a real export 2026-11-04; NOT in the repo, keep it that way; + build a synthetic fixture). Format: first line `SEP=\t`, then a tab-separated header. Columns: + `simbol` (e.g. `US.APLD`, `US.COHRn`, `US.OUSTc`: strip the `US.` prefix and trailing lowercase + class letters; BVB symbols presumably have no prefix → `.RO`), `sold` = shares, + `costm` = average cost, `ppiata` = market price, `valuta` = currency, `nume` = name, + `isin`, `tsim` = `actiuni` (shares) or `bani` (cash row; skip, maybe show cash). Decimal point + is `.`. Use the ISIN (`yf.Search(isin)`) as a fallback when a ticker doesn't resolve. Preview + before saving; replace vs merge choice. The owner's dad has ~36 US positions. +- **Today panel with ~36 holdings**: currently fetches calendar + ratings + insider per ticker + (3 Yahoo requests each, cached 6 h, 4 in parallel): fine but slow on first load. Consider + calendar-only for the first pass and loading ratings/insider lazily. +- **Portfolio history**: 1-year chart of the current holdings' value (from `Ticker.history`) + vs the S&P 500, plus a daily recorded total going forward. +- **Price highlights**: optional "below X / above Y" per position → highlighted row + a line in + the "Your stocks" panel. No notifications (the owner said no alerts; app isn't open 24/7). +- **Model presets** in Settings (free nemotron default + one or two good paid options). + ### Ideas for later (not planned) - Own price chart (`Ticker.history`) if TradingView ever fails for a market the owner uses (owner confirmed TradingView works, including BVB, on 2026-11-04). @@ -100,10 +129,10 @@ Read this first. Update it at the end of every batch or before your context runs - Portfolio history (value over time) — needs a daily snapshot job. ## Status -Batches 1-6 done. PR #1 merged by the owner; #2-#6 are stacked and CI-green. **Owner action:** -on PR #2 change the base to `main` (Edit next to the title), merge, click "Delete branch"; -GitHub then retargets #3 to `main`, and so on. (Agents may not merge or retarget PRs here.) -The owner's folder `E:\WatchStock\WatchStock` has everything through batch 6. +Batches 1-7 done. PR #1 merged by the owner; #2-#7 stacked, CI-green. **Owner action:** on PR #2 +change the base to `main` (Edit next to the title), merge, click "Delete branch"; GitHub then +retargets #3 to `main`, and so on. (Agents may not merge or retarget PRs here.) +The owner's folder `E:\WatchStock\WatchStock` has everything through batch 7. Next: batch 8. Notes for the next agent: - The sidebar "you own" P/L uses the snapshot price (up to 4 h old); the portfolio table @@ -153,6 +182,13 @@ Batch 6: - [ ] First start after the update creates a "WatchStock" shortcut on the Desktop, and it launches the app - [ ] Opening a stock for the first time is still reasonably fast (peers add up to 5 Yahoo calls, cached a day) +Owner reported 2026-11-04 evening: batch 6 OK (peers make sense, Desktop shortcut works). + +Batch 7: +- [ ] RO button (top right) switches everything to Romanian; EN switches back +- [ ] A new AI report / thesis check / chat answer comes back in Romanian (free model quality varies) +- [ ] Romanian wording reads naturally to the dad (send any odd phrases; they're in static/js/i18n.js) + ## Open questions for the owner - (answered) Dad holds mostly US stocks → currency formatting stays in batch 3, no rush. - (answered) Default model: `nvidia/nemotron-3.5-super-vl:free` for now. diff --git a/pyproject.toml b/pyproject.toml index 7820160..a850c11 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "watchstock" -version = "0.7.0" +version = "0.8.0" description = "Personal stock analysis terminal: Yahoo Finance data, explainable scores, optional LLM analysis." readme = "README.md" requires-python = ">=3.12" @@ -40,3 +40,4 @@ select = ["E", "F", "W", "I", "B", "UP", "SIM"] [tool.ruff.lint.per-file-ignores] "tests/*" = ["E501"] # long literal test data reads better on one line "scripts/fake_server.py" = ["E501"] +"watchstock/i18n.py" = ["E501"] # translation table diff --git a/scripts/ui_smoke.js b/scripts/ui_smoke.js index 0aa6330..ba4e88f 100644 --- a/scripts/ui_smoke.js +++ b/scripts/ui_smoke.js @@ -182,6 +182,48 @@ const check = (name, ok, detail = '') => { if (!ok) failures.push(`${name}${deta await page.waitForTimeout(300); await shot('settings'); + // ---- Romanian: switch via cookie, check translations and that no English UI text is left + const roCtx = await browser.newContext({ viewport: { width: 1440, height: 900 } }); + await roCtx.addCookies([{ name: 'ws_lang', value: 'ro', url: BASE }]); + const ro = await roCtx.newPage(); + ro.on('pageerror', e => errors.push('[ro] ' + e.message)); + await ro.route('**/*', r => (r.request().url().startsWith(BASE) ? r.continue() : r.abort())); + const roText = sel => ro.evaluate(s => document.querySelector(s)?.innerText ?? null, sel); + // English words that must not survive in Romanian outside content areas (.no-i18n) + const EN_WORDS = /\b(Loading|Settings|Refresh|Portfolio|Watchlist|Analyze|Shares|Value|Weight|Today|Liquidity|Stability|Search|History|Market|News|Score|Quality|Valuation|Analyst|Consensus|Fundamentals|Industry|Recommendation|Summary|Dividend|Price|Earnings|Revenue|Margin|Ownership|Insider|position|positions|analysts|upside|ago|days|Click|breakdown|Remove|Edit|Save|Cancel|Average|optional|Company|median|Thesis|owned)\b/; + const leftovers = where => ro.evaluate(src => { + const re = new RegExp(src), out = new Set(); + const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); + let n; + while ((n = w.nextNode())) { + const el = n.parentElement; + if (!el || el.closest('.no-i18n, script, style') || !el.offsetParent) continue; + const v = n.nodeValue.trim(); + if (v && re.test(v)) out.add(v.slice(0, 80)); + } + return [...out]; + }, EN_WORDS.source).then(list => list.forEach(x => failures.push(`[ro ${where}] untranslated: ${x}`))); + await ro.goto(BASE + '/'); + await ro.waitForTimeout(2000); + check('[ro] analyze button', (await roText('#searchBtn')) === 'Analizează', await roText('#searchBtn')); + check('[ro] logo untouched', /^WatchStock$/.test((await roText('#initialView .no-i18n')) + 'Stock')); + check('[ro] portfolio title', /PORTOFOLIUL MEU/.test(await roText('#portfolioSection'))); + check('[ro] decimal comma in indices', /6\.012,30/.test(await roText('#indicesBar')), await roText('#indicesBar')); + check('[ro] today panel in Romanian', /Rezultate financiare în 3 zile/.test(await roText('#todayList')), await roText('#todayList')); + await leftovers('home'); + await ro.evaluate(() => quickSearch('Microsoft Corporation', 'MSFT')); + await ro.waitForTimeout(2000); + await ro.click('.tab-btn[data-target="tab-finance"]'); + await ro.click('[data-score-key="quality"]'); + check('[ro] breakdown from backend', /Marjă netă 36,0%/.test(await roText('#popoverContent')), await roText('#popoverContent')); + await leftovers('finance'); + await ro.evaluate(() => { hideScoreBreakdown(); showScoreExplanation('long_term'); }); + check('[ro] safety modal title', /^Stabilitate: datorii/.test(await roText('#scoreModalTitle')), await roText('#scoreModalTitle')); + await ro.evaluate(() => { closeScoreModal(); openSettings(); }); + await leftovers('settings'); + OUT && await ro.screenshot({ path: `${OUT}/ro_settings.png` }); + await roCtx.close(); + await browser.close(); for (const e of errors) failures.push('page error: ' + e); if (failures.length) { diff --git a/static/index.html b/static/index.html index 2d80943..9ec4769 100644 --- a/static/index.html +++ b/static/index.html @@ -41,12 +41,16 @@
- WatchStock + WatchStock
Loading indices...
+
+ + +
@@ -148,7 +152,7 @@
Loading...
MARKET NEWS
-
+
Loading...
@@ -347,7 +351,7 @@

-
+

@@ -372,7 +376,7 @@

AI Analysis