Compare commits

...
5 Commits
Author SHA1 Message Date
asepharyana 9ea9a4291c feat: scheduler tangkap company name dari top-changes (n=750) — gratis, isi yang kosong saja
CI / go test + web typecheck (push) Canceled after 0s
CI / build + deploy (Nix) — flowsight (push) Canceled after 0s
2026-09-16 16:54:27 +07:00
asepharyana 41325ba574 feat: tangkap company name dari snapshot top-changes (n=750, gratis) + SetCompanyNames fill-blank 2026-09-16 16:53:50 +07:00
asepharyana 6d3c17d19d fix: PDF export kini Unicode — ganti core font Helvetica (latin1 → '?') dengan DejaVuSans ter-embed
CI / go test + web typecheck (push) Canceled after 0s
CI / build + deploy (Nix) — flowsight (push) Canceled after 0s
2026-09-16 16:48:27 +07:00
asepharyana ae0d5d813f feat(ui): watchlist empty-state + chat error styling + hint
CI / go test + web typecheck (push) Canceled after 0s
CI / build + deploy (Nix) — flowsight (push) Canceled after 0s
- WatchlistDrawer: shows helpful hint ('Ketik kode saham lalu Add') when empty
- ChatSidebar: errors in text-destructive, empty state explains how chat works
- styled-components/timestamp formatting and company-name display already in previous commit
2026-09-16 15:39:33 +07:00
asepharyana ffdc0fd9e8 feat(ui): polish pass — theme-aware charts, brand nav, search & date formatting
- Dashboard foreign-flow chart line now uses the CSS --primary token (hsl) so it matches light/dark instead of a hardcoded blue; Portfolio bar chart gets themed bars with rounded corners + alpha steps
- Nav: logo mark (📈 in primary tile), active item left accent bar, active-state matching for sub-routes (/report/:ticker now highlights Report... actually Dashboard/Screener etc)
- TickerSearch: cleaner searchbox with magnifier icon + 'Buka' button, aria-label
- Login page: centered branded header (logo + FlowSight), vertically centered card
- Sorotan cards + Screener show company name under ticker when available
- Routines run history + Alerts event/alert lists: formatted dates (16 Sep 07:30), status badges (ok/error), credits-used display
- Dashboard hero/misc spacing polish
2026-09-16 15:33:18 +07:00
10 changed files with 213 additions and 52 deletions

No files matched your search

+13 -17
View File
@@ -54,25 +54,31 @@ func (r Report) ToHTML() string {
}
// ToPDF renders the report server-side (pure Go, no system deps).
// Font: DejaVuSans (Unicode) instead of core Helvetica so Indonesian text
// (Em-dash, quotes, Rp, accents) renders correctly — latin1() was turning
// every non-Latin rune into '?'.
func (r Report) ToPDF() ([]byte, error) {
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.SetFontLocation("/usr/share/fonts/truetype/dejavu/")
pdf.AddUTF8Font("DejaVu", "", "DejaVuSans.ttf")
pdf.AddUTF8Font("DejaVu", "B", "DejaVuSans-Bold.ttf")
pdf.AddPage()
pdf.SetFont("Helvetica", "B", 16)
pdf.SetFont("DejaVu", "B", 14)
pdf.Cell(0, 10, r.Ticker+" — FlowSight Report")
pdf.Ln(12)
pdf.SetFont("Helvetica", "", 10)
pdf.SetFont("DejaVu", "", 10)
pdf.Cell(0, 6, "Generated "+r.GeneratedAt)
pdf.Ln(8)
for _, s := range r.Sections {
pdf.SetFont("Helvetica", "B", 12)
pdf.SetFont("DejaVu", "B", 12)
pdf.Cell(0, 8, s.Name)
pdf.Ln(8)
pdf.SetFont("Helvetica", "", 10)
pdf.MultiCell(0, 5, latin1(s.Body), "", "", false)
pdf.SetFont("DejaVu", "", 10)
pdf.MultiCell(0, 5, s.Body, "", "", false)
if len(s.Citations) > 0 {
pdf.SetFont("Helvetica", "I", 8)
pdf.SetFont("DejaVu", "", 8)
for _, c := range s.Citations {
pdf.MultiCell(0, 4, latin1(c.Endpoint+" "+c.Ticker+" @ "+c.SnapshotAt), "", "", false)
pdf.MultiCell(0, 4, c.Endpoint+" "+c.Ticker+" @ "+c.SnapshotAt, "", "", false)
}
}
pdf.Ln(4)
@@ -83,13 +89,3 @@ func (r Report) ToPDF() ([]byte, error) {
}
return buf.Bytes(), nil
}
// latin1 drops non-latin runes gofpdf core fonts cannot render.
func latin1(s string) string {
return strings.Map(func(r rune) rune {
if r > 255 {
return '?'
}
return r
}, s)
}
+21 -2
View File
@@ -12,6 +12,7 @@ import (
"log"
"net/url"
"strconv"
"strings"
"time"
"github.com/robfig/cron/v3"
@@ -295,13 +296,31 @@ func (s *Scheduler) universe(ctx context.Context) error {
}
// market pulls top-changes (1 class x 2 periods), most-traded, idx-total,
// brokers/top — the cheap context block of the cycle.
// brokers/top — the cheap context block of the cycle. The top-changes call
// also enriches universe company names (MoverRow.Name) at no extra credit —
// n_stock is free; cost is classes×periods only.
func (s *Scheduler) market(ctx context.Context) error {
if g, l, err := s.Sectors.TopChanges(ctx,
[]string{"top_gainers"}, []string{"1d", "7d"}, "", 5); err == nil {
[]string{"top_gainers"}, []string{"1d", "7d"}, "", 750); err == nil {
if raw, err := json.Marshal(map[string]any{"top_gainers": g, "top_losers": l}); err == nil {
_ = s.DB.SaveSnapshot("IDX", time.Now().Format("2006-01-02"), "top-changes", string(raw))
}
// Capture company names from whatever mover rows came back.
names := map[string]string{}
collect := func(rows map[string][]sectors.MoverRow) {
for _, rs := range rows {
for _, r := range rs {
if r.Name != "" {
names[strings.TrimSuffix(r.Symbol, ".JK")] = r.Name
}
}
}
}
collect(g)
collect(l)
if err := s.DB.SetCompanyNames(names); err != nil {
log.Printf("scheduler: set company names: %v", err)
}
} else {
return err
}
+24
View File
@@ -682,6 +682,30 @@ func (db *DB) CompanyNames(tickers []string) (map[string]string, error) {
return out, rows.Err()
}
// SetCompanyNames bulk-upserts company_name for tickers (from top-changes
// snapshots). Only non-empty names are written; existing names win (skip
// blank overwrite) so a later richer source doesn't clobber a good one.
func (db *DB) SetCompanyNames(names map[string]string) error {
if len(names) == 0 {
return nil
}
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
for t, nm := range names {
nm = strings.TrimSpace(nm)
if nm == "" || strings.EqualFold(nm, t) {
continue
}
if _, err := tx.Exec(`UPDATE universe SET company_name = ? WHERE ticker = ? AND company_name = ''`, nm, t); err != nil {
return err
}
}
return tx.Commit()
}
// TickerHit is one local search result over the universe table.
type TickerHit struct {
Symbol string
+44
View File
@@ -155,3 +155,47 @@ func TestUniverseSearch(t *testing.T) {
t.Fatal("TLKM has no name, must be omitted")
}
}
// SetCompanyNames fills blank names; never overwrites existing ones; skips
// blanks and ticker-equal names.
func TestSetCompanyNames(t *testing.T) {
db, err := Open(t.TempDir() + "/names.db")
if err != nil {
t.Fatal(err)
}
defer db.Close()
uni := []UniverseRow{
{Symbol: "BBCA.JK", Close: 100, Date: "2026-09-16", CompanyName: "PT Bank Central Asia Tbk"},
{Symbol: "TLKM.JK", Close: 90, Date: "2026-09-16"},
{Symbol: "BBRI.JK", Close: 80, Date: "2026-09-16"},
}
if err := db.SaveUniverse(uni); err != nil {
t.Fatal(err)
}
// Fill TLKM + BBRI; BBCA already has a name (must NOT be clobbered);
// "UNVR" would be a new row (INSERT OR IGNORE means it's skipped).
err = db.SetCompanyNames(map[string]string{
"TLKM": "PT Telkom Indonesia (Persero) Tbk",
"BBRI": "PT Bank Rakyat Indonesia (Persero) Tbk",
"BBCA": "SHOULD NOT OVERWRITE",
"UNVR": "PT Unilever Indonesia Tbk",
"EMTK": "PT Elang Mahkota Teknologi Tbk", // no universe row -> no-op
"BLAH": "BLAH", // ticker-equal -> skip
})
if err != nil {
t.Fatal(err)
}
names, err := db.CompanyNames([]string{"BBCA", "TLKM", "BBRI", "UNVR"})
if err != nil {
t.Fatal(err)
}
if names["BBCA"] != "PT Bank Central Asia Tbk" {
t.Fatalf("BBCA clobbered: %q", names["BBCA"])
}
if names["TLKM"] != "PT Telkom Indonesia (Persero) Tbk" || names["BBRI"] != "PT Bank Rakyat Indonesia (Persero) Tbk" {
t.Fatalf("names = %+v, want TLKM+BBRI filled", names)
}
if _, ok := names["UNVR"]; ok {
t.Fatal("UNVR not in universe must be absent")
}
}
+18 -9
View File
@@ -36,7 +36,9 @@ export function WatchlistDrawer() {
</div>
<Show when={err()}><p class="text-xs text-destructive">{err()}</p></Show>
<ul class="flex flex-wrap gap-1.5">
<For each={wl()?.watchlist || []}>{(t) => <li class="flex items-center gap-1"><a href={`/report/${encodeURIComponent(t)}`}><Badge variant="secondary">{t}</Badge></a> <button class="text-xs text-muted-foreground hover:text-foreground" aria-label={`Hapus ${t} dari watchlist`} onClick={() => del(t)}>×</button></li>}</For>
<Show when={(wl()?.watchlist || []).length} fallback={<li class="text-xs text-muted-foreground">Ketik kode saham lalu Add — mis. BBCA, TLKM, BBRI.</li>}>
<For each={wl()?.watchlist || []}>{(t) => <li class="flex items-center gap-1"><a href={`/report/${encodeURIComponent(t)}`}><Badge variant="secondary">{t}</Badge></a> <button class="text-xs text-muted-foreground hover:text-foreground" aria-label={`Hapus ${t} dari watchlist`} onClick={() => del(t)}>×</button></li>}</For>
</Show>
</ul>
</CardContent>
</Card>
@@ -45,7 +47,7 @@ export function WatchlistDrawer() {
export function ChatSidebar() {
const [msg, setMsg] = createSignal("");
const [log, setLog] = createSignal<{ q: string; a: string }[]>([]);
const [log, setLog] = createSignal<{ q: string; a: string; err?: boolean }[]>([]);
async function send() {
const q = msg().trim();
if (!q) return;
@@ -54,18 +56,25 @@ export function ChatSidebar() {
const r = await api.chat(q);
setLog((p) => [...p, { q, a: r.answer }].slice(-10));
} catch (e) {
setLog((p) => [...p, { q, a: String(e) }].slice(-10));
setLog((p) => [...p, { q, a: String(e), err: true }].slice(-10));
}
}
return (
<Card>
<CardHeader class="pb-2"><CardTitle class="text-base">AI Chat</CardTitle></CardHeader>
<CardContent class="space-y-2">
<div class="max-h-64 space-y-2 overflow-y-auto">
<For each={log()}>
{(m) => <div class="text-sm"><p><strong>You:</strong> {m.q}</p><p class="text-muted-foreground">{m.a.slice(0, 500)}</p></div>}
</For>
</div>
<Show when={log().length} fallback={<p class="text-xs text-muted-foreground">Tanya soal watchlist-mu — sistem jawab dari data yang tersimpan (bukan karangan).</p>}>
<div class="max-h-64 space-y-2 overflow-y-auto">
<For each={log()}>
{(m) => (
<div class="text-sm">
<p><strong>You:</strong> {m.q}</p>
<p classList={{ "text-muted-foreground": !m.err, "text-destructive": !!m.err }}>{m.a.slice(0, 500)}</p>
</div>
)}
</For>
</div>
</Show>
<div class="flex gap-2">
<label class="sr-only" for="chat-msg">Tanya AI</label>
<TextField class="flex-1"><TextFieldInput id="chat-msg" placeholder="Ask about your watchlist…" value={msg()} onInput={(e) => setMsg(e.currentTarget.value)} onKeyDown={(e: KeyboardEvent) => { if (e.key === "Enter") send(); }} /></TextField>
@@ -74,4 +83,4 @@ export function ChatSidebar() {
</CardContent>
</Card>
);
}
}
+32 -14
View File
@@ -27,17 +27,24 @@ function Nav(props: { loggedIn: boolean }) {
const loc = useLocation();
// Belum login: hanya Dashboard yg terlihat (fitur lain di-hide).
const items = () => props.loggedIn ? NAV_ALL : NAV_ALL.slice(0, 1);
const isActive = (href: string) => loc.pathname === href || (href !== "/" && loc.pathname.startsWith(href));
return (
<nav class="flex w-56 shrink-0 flex-col gap-1 border-r bg-card p-4 max-lg:hidden">
<div class="mb-4 px-2 text-xl font-bold tracking-tight">
Flow<span class="text-primary">Sight</span>
<div class="mb-5 px-2">
<a href="/" class="flex items-center gap-2 text-xl font-bold tracking-tight">
<span class="grid size-7 place-items-center rounded-lg bg-primary text-sm text-primary-foreground">📈</span>
Flow<span class="text-primary">Sight</span>
</a>
</div>
{items().map((n) => (
<a
href={n.href}
class={`flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground ${loc.pathname === n.href ? "bg-accent text-accent-foreground" : "text-muted-foreground"}`}
class={`relative flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground ${isActive(n.href) ? "bg-accent text-accent-foreground" : "text-muted-foreground"}`}
>
<span>{n.icon}</span> {n.label}
<span class="text-base leading-none">{n.icon}</span> {n.label}
<Show when={isActive(n.href)}>
<span class="absolute left-0 top-1/2 h-5 w-0.5 -translate-y-1/2 rounded-full bg-primary" />
</Show>
</a>
))}
</nav>
@@ -64,18 +71,25 @@ function MobileNav(props: { loggedIn: boolean }) {
function TickerSearch(props: { loggedIn: boolean }) {
const nav = useNavigate();
const [q, setQ] = createSignal("");
const go = () => {
const t = q().toUpperCase().trim();
const go = (t: string) => {
const v = t.toUpperCase().trim();
// Report butuh login: arahkan yg belum login ke /login.
if (t) nav(props.loggedIn ? `/report/${t}` : "/login");
if (v) nav(props.loggedIn ? `/report/${v}` : "/login");
};
return (
<form class="flex max-w-sm flex-1 items-center gap-2" onSubmit={(e) => { e.preventDefault(); go(); }}>
<TextField class="flex-1">
<TextFieldInput placeholder="Ticker → report (e.g. BBCA)" value={q()}
onInput={(e) => setQ(e.currentTarget.value)} />
</TextField>
<Button type="submit" variant="secondary">Open</Button>
<form class="flex max-w-sm flex-1 items-center gap-2" onSubmit={(e) => { e.preventDefault(); go(q()); }}>
<div class="relative flex-1">
<TextFieldInput
placeholder="Cari kode saham…"
value={q()}
aria-label="Cari kode saham"
onInput={(e) => setQ(e.currentTarget.value)}
onKeyDown={(e: KeyboardEvent) => { if (e.key === "Enter") { e.preventDefault(); go(q()); } }}
class="h-9 pr-8"
/>
<span class="pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">🔍</span>
</div>
<Button type="submit" variant="secondary" class="h-9 px-3">Buka</Button>
</form>
);
}
@@ -99,7 +113,11 @@ function LoginPage() {
finally { setBusy(false); }
}
return (
<div class="mx-auto max-w-md py-[8vh]">
<div class="mx-auto flex min-h-[70vh] w-full max-w-md flex-col justify-center py-[6vh]">
<div class="mb-6 flex items-center justify-center gap-2 text-2xl font-bold tracking-tight">
<span class="grid size-9 place-items-center rounded-xl bg-primary text-lg text-primary-foreground">📈</span>
Flow<span class="text-primary">Sight</span>
</div>
<Card>
<CardHeader class="text-center">
<CardTitle class="text-2xl">Masuk ke FlowSight 👋</CardTitle>
+11 -2
View File
@@ -50,6 +50,11 @@ function AlertsInner() {
refetchDests();
} catch (e) { setDerr(String(e)); }
}
const fmtDate = (s: unknown) => {
const t = String(s || "");
const d = new Date(t);
return Number.isNaN(d.getTime()) ? t : d.toLocaleString("id-ID", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });
};
async function toggleDest(id: number, enabled: boolean) { try { await api.updateDestination(id, { enabled: !enabled }); refetchDests(); } catch (e) { setDerr(String(e)); } }
async function delDest(id: number) { try { await api.deleteDestination(id); refetchDests(); } catch (e) { setDerr(String(e)); } }
return (
@@ -111,7 +116,11 @@ function AlertsInner() {
<CardHeader><CardTitle>Notifikasi terpasang</CardTitle></CardHeader>
<CardContent>
<Show when={(alerts()?.alerts || []).length} fallback={<EmptyState icon="🔔" title="Belum ada" hint="Pilih template di atas, sekali klik." />}>
<ul class="space-y-1.5 text-sm"><For each={alerts()?.alerts || []}>{(a) => <li class="flex items-center gap-2">{a.name} <span class="text-muted-foreground">terakhir: {a.last_fired || "belum pernah"}</span><span class="flex-1" /><Button variant="destructive" size="sm" onClick={() => del(a.id)}>Hapus</Button></li>}</For></ul>
<ul class="space-y-1.5 text-sm"><For each={alerts()?.alerts || []}>{(a) => <li class="flex flex-wrap items-center gap-2">
{a.name}
<span class="text-muted-foreground">terakhir: {a.last_fired ? fmtDate(a.last_fired) : "belum pernah"}</span>
<span class="flex-1" /><Button variant="destructive" size="sm" onClick={() => del(a.id)}>Hapus</Button>
</li>}</For></ul>
</Show>
</CardContent>
</Card>
@@ -122,7 +131,7 @@ function AlertsInner() {
</CardHeader>
<CardContent>
<Show when={(events() || []).length} fallback={<p class="text-sm text-muted-foreground">Belum ada kejadian.</p>}>
<ul class="space-y-1.5 text-sm"><For each={events() || []}>{(e) => <li><Badge variant="secondary">{String(e.ticker)}</Badge> {String(e.message)}</li>}</For></ul>
<ul class="space-y-1.5 text-sm"><For each={events() || []}>{(e) => <li class="flex items-start gap-2"><Badge variant="secondary">{String(e.ticker)}</Badge><span class="min-w-0 flex-1">{String(e.message)}</span><span class="shrink-0 text-xs text-muted-foreground">{fmtDate(e.date)}</span></li>}</For></ul>
</Show>
</CardContent>
</Card>
+18 -6
View File
@@ -38,13 +38,20 @@ export default function Dashboard() {
};
const sorotan = () => (screen()?.rows || []).map((r) => ({ row: r, ...verdictFor(r) }));
const closeMap = () => Object.fromEntries((flow()?.closes || []).map((c) => [c.ticker, c]));
// Resolve theme-aware primary color (falls back to blue) so the chart
// matches light/dark instead of a hardcoded hex.
const primaryColor = () => {
const c = getComputedStyle(document.documentElement).getPropertyValue("--primary");
const [h, s, l] = c.trim().split(/[\s,]+/).map(Number);
return Number.isFinite(h) && Number.isFinite(s) && Number.isFinite(l) ? `hsl(${h} ${s}% ${l}%)` : "#3b82f6";
};
const chartData = () => ({
labels: (foreign()?.dates || []) as string[],
datasets: [{
label: `${chartTiker()} — uang asing harian (Rp juta)`,
data: (foreign()?.nets || []) as number[],
borderColor: "#3b82f6",
backgroundColor: "rgba(59,130,246,.15)",
borderColor: primaryColor(),
backgroundColor: "transparent",
fill: true,
tension: 0.25,
}],
@@ -99,10 +106,15 @@ export default function Dashboard() {
return (
<Card class={s.verdict === "Dilirik" ? "border-emerald-500/50" : s.verdict === "Dilepas" ? "border-red-500/50" : ""}>
<CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle class="text-xl font-bold">
{s.row.symbol}
<Show when={cx?.close}><span class="ml-2 font-mono text-sm font-normal text-muted-foreground">{fmtHarga(cx.close)}</span></Show>
</CardTitle>
<div>
<CardTitle class="text-xl font-bold">
{s.row.symbol}
<Show when={cx?.close}><span class="ml-2 font-mono text-sm font-normal text-muted-foreground">{fmtHarga(cx.close)}</span></Show>
</CardTitle>
<Show when={s.row.name && s.row.name !== s.row.symbol}>
<p class="text-xs text-muted-foreground">{s.row.name}</p>
</Show>
</div>
<VerdictBadge verdict={s.verdict} />
</CardHeader>
<CardContent class="space-y-3">
+14 -1
View File
@@ -31,9 +31,22 @@ function PortfolioInner() {
if (top.weight > 0.4) return `${top.ticker} porsinya ${(top.weight * 100).toFixed(0)}% — kebanyakan telur di satu keranjang. Pertimbangkan tambah saham beda sektor.`;
return "Sebarannya sudah lumayan — tidak numpuk di satu tempat. Pertahankan. 👍";
};
const primaryColor = () => {
const c = getComputedStyle(document.documentElement).getPropertyValue("--primary");
const [h, s, l] = c.trim().split(/[\s,]+/).map(Number);
return Number.isFinite(h) && Number.isFinite(s) && Number.isFinite(l) ? `hsl(${h} ${s}% ${l}%)` : "#3b82f6";
};
const chartData = () => ({
labels: conc().map((c) => c.ticker),
datasets: [{ label: "Porsi %", data: conc().map((c) => +(c.weight * 100).toFixed(1)) }],
datasets: [{
label: "Porsi %",
data: conc().map((c) => +(c.weight * 100).toFixed(1)),
backgroundColor: conc().map((_, i) => {
const alphas = ["88", "66", "44", "33", "22"];
return `${primaryColor()}${alphas[i % alphas.length]}`;
}),
borderRadius: 4,
}],
});
return (
<div class="space-y-4">
+18 -1
View File
@@ -30,6 +30,13 @@ function RoutinesInner() {
catch (e) { setErr(String(e)); }
finally { setBusy(false); }
}
const fmtTime = (s: unknown) => {
const t = String(s || "");
if (!t) return "—";
// ISO timestamp → "16 Sep 07:30" (local time).
const d = new Date(t);
return Number.isNaN(d.getTime()) ? t : d.toLocaleString("id-ID", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });
};
async function toggle(id: number, enabled: boolean) {
try { await api.updateRoutine(id, { enabled: !enabled }); refetch(); } catch (e) { setErr(String(e)); }
}
@@ -93,7 +100,17 @@ function RoutinesInner() {
<Button variant="ghost" size="sm" onClick={() => refetchRuns()}>Refresh</Button>
</CardHeader>
<CardContent>
<ul class="space-y-1 text-sm text-muted-foreground"><For each={runs() || []}>{(r) => <li>{String(r.started_at)} — {String(r.status)}</li>}</For></ul>
<ul class="space-y-1 text-sm text-muted-foreground">
<For each={runs() || []}>{(r) => (
<li class="flex items-center justify-between gap-2">
<span class="flex items-center gap-2">
<Badge variant={r.status === "ok" ? "success" : r.status === "error" ? "error" : "secondary"} class="capitalize">{String(r.status)}</Badge>
<span>{fmtTime(r.started_at)}</span>
</span>
<span class="font-mono text-xs">{r.credits_used ? `${String(r.credits_used)} kredit` : `#${String(r.routine_id)}`}</span>
</li>
)}</For>
</ul>
</CardContent>
</Card>
</div>