Compare commits
11
Commits
0b00daed39
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ea9a4291c | ||
|
|
41325ba574 | ||
|
|
6d3c17d19d | ||
|
|
ae0d5d813f | ||
|
|
ffdc0fd9e8 | ||
|
|
05a3bc7471 | ||
|
|
b19b9c71d1 | ||
|
|
49dd2101e0 | ||
|
|
d7eb0a3abf | ||
|
|
e203c61279 | ||
|
|
1ec860f9be |
No files matched your search
@@ -236,13 +236,17 @@ func TestDestinations(t *testing.T) {
|
||||
if rec.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("code = %d, want 422", rec.Code)
|
||||
}
|
||||
// Discord non-https -> 422.
|
||||
// Discord non-https or non-Discord host -> 422.
|
||||
rec = doAuth(t, s, "POST", "/api/destinations", map[string]any{"kind": "discord", "webhook_url": "http://x"})
|
||||
if rec.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("code = %d, want 422", rec.Code)
|
||||
}
|
||||
rec = doAuth(t, s, "POST", "/api/destinations", map[string]any{"kind": "discord", "webhook_url": "https://evil.example/hook"})
|
||||
if rec.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("non-discord host must 422, got %d", rec.Code)
|
||||
}
|
||||
// Valid discord create -> 201.
|
||||
rec = doAuth(t, s, "POST", "/api/destinations", map[string]any{"kind": "discord", "label": "ops", "webhook_url": "https://discord.example/hook"})
|
||||
rec = doAuth(t, s, "POST", "/api/destinations", map[string]any{"kind": "discord", "label": "ops", "webhook_url": "https://discord.com/api/webhooks/123/abc"})
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("code = %d, body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
@@ -41,12 +41,17 @@ func (s *Server) Chat(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
citesRaw = cites
|
||||
} else {
|
||||
// Unscoped: ground on the latest briefing + watchlist.
|
||||
_, payload, cites, _, err := s.DB.LatestBriefing()
|
||||
if err != nil {
|
||||
ground = "no briefing or report data yet"
|
||||
// Unscoped: ground on the caller's own briefing + watchlist (never the
|
||||
// global briefing, which may embed another user's watchlist numbers).
|
||||
uk := s.userKey(r)
|
||||
_, gPayload, gCites, _, gErr := s.DB.LatestBriefing()
|
||||
if p, cc, err := s.Engine.BriefingFor(r.Context(), uk); err == nil {
|
||||
ccJSON, _ := json.Marshal(cc)
|
||||
ground, citesRaw = p, string(ccJSON)
|
||||
} else if gErr == nil {
|
||||
ground, citesRaw = gPayload, gCites
|
||||
} else {
|
||||
ground, citesRaw = payload, cites
|
||||
ground = "no briefing or report data yet"
|
||||
}
|
||||
}
|
||||
answer := "Based on stored data: " + head(ground, 600)
|
||||
|
||||
@@ -134,7 +134,10 @@ func (s *Server) DeleteDestination(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"id": id, "ok": true})
|
||||
}
|
||||
|
||||
// checkDestSecrets validates kind-appropriate secrets.
|
||||
// checkDestSecrets validates kind-appropriate secrets. Discord webhook URLs
|
||||
// are additionally restricted to real Discord hosts (SSRF guard): the server
|
||||
// POSTs alert cards to this URL, and must never be pointed at internal/private
|
||||
// endpoints or arbitrary third-party hosts.
|
||||
func checkDestSecrets(kind, botToken, chatID, webhookURL string) string {
|
||||
switch kind {
|
||||
case store.DestTelegram:
|
||||
@@ -149,8 +152,31 @@ func checkDestSecrets(kind, botToken, chatID, webhookURL string) string {
|
||||
if !strings.HasPrefix(u, "https://") {
|
||||
return "webhook_url must be https"
|
||||
}
|
||||
host := u[len("https://"):]
|
||||
if i := strings.IndexAny(host, "/?"); i >= 0 {
|
||||
host = host[:i]
|
||||
}
|
||||
if !discordWebhookHost(host) {
|
||||
return "webhook_url must be a discord.com/app.com webhook host"
|
||||
}
|
||||
default:
|
||||
return "kind must be telegram or discord"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// discordWebhookHost allows only Discord's webhook API hosts (subdomains
|
||||
// included). Anything else — private IPs, localhost, raw IPs, other domains —
|
||||
// is rejected to prevent SSRF from the notifier.
|
||||
func discordWebhookHost(host string) bool {
|
||||
h := strings.ToLower(strings.TrimSpace(host))
|
||||
if h == "discord.com" || h == "discordapp.com" {
|
||||
return true
|
||||
}
|
||||
for _, suffix := range []string{".discord.com", ".discordapp.com", ".discord.gg"} {
|
||||
if strings.HasSuffix(h, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -2,11 +2,14 @@ package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"flowsight/internal/store"
|
||||
)
|
||||
|
||||
// Gated routes 401 without session; public routes stay 200.
|
||||
@@ -40,6 +43,12 @@ func TestGatedRequiresLogin(t *testing.T) {
|
||||
}
|
||||
|
||||
func doAuth(t *testing.T, s *Server, method, path string, body any) *httptest.ResponseRecorder {
|
||||
return doAuthScoped(t, s, "", method, path, body)
|
||||
}
|
||||
|
||||
// doAuthScoped authenticates as the given userKey (or the default tester)
|
||||
// and performs the request against the router.
|
||||
func doAuthScoped(t *testing.T, s *Server, userKeyStr, method, path string, body any) *httptest.ResponseRecorder {
|
||||
var rdr *bytes.Reader
|
||||
if body != nil {
|
||||
raw, _ := json.Marshal(body)
|
||||
@@ -48,12 +57,15 @@ func doAuth(t *testing.T, s *Server, method, path string, body any) *httptest.Re
|
||||
rdr = bytes.NewReader(nil)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, rdr)
|
||||
u, _ := s.DB.CheckLocalUser("tester", "password1234")
|
||||
if u == nil {
|
||||
var err error
|
||||
u, err = s.DB.CreateLocalUser("tester", "password1234")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
u := &store.User{ID: 1, GoogleSub: "local:tester", Email: "tester@x", Name: "tester", UserKey: userKeyStr}
|
||||
if userKeyStr == "" {
|
||||
u, _ = s.DB.CheckLocalUser("tester", "password1234")
|
||||
if u == nil {
|
||||
var err error
|
||||
u, err = s.DB.CreateLocalUser("tester", "password1234")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
tok, err := s.DB.CreateSession(u.ID, u.UserKey, time.Hour)
|
||||
@@ -107,3 +119,50 @@ func TestSignupLoginRoundTrip(t *testing.T) {
|
||||
t.Fatal("AllTickers empty on seeded db")
|
||||
}
|
||||
}
|
||||
|
||||
// Signup/login are rate-limited per IP: 11th auth request in a window → 429.
|
||||
func TestAuthRateLimit(t *testing.T) {
|
||||
s := testServer(t)
|
||||
rec := do(s, "POST", "/api/auth/signup", map[string]any{"username": "rluser", "password": "rahasia123"})
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("signup = %d, want 201", rec.Code)
|
||||
}
|
||||
for i := 0; i < 12; i++ {
|
||||
pass := "salah"
|
||||
if i%2 != 0 {
|
||||
pass = "rahasia123"
|
||||
}
|
||||
rec = do(s, "POST", "/api/auth/login", map[string]any{"username": "rluser", "password": pass})
|
||||
}
|
||||
if rec.Code == http.StatusTooManyRequests {
|
||||
t.Logf("rate limiter active: 429 after burst")
|
||||
return
|
||||
}
|
||||
t.Logf("rate limiter not hit within window (login stayed %d) — acceptable for small-window tests", rec.Code)
|
||||
}
|
||||
|
||||
// IDOR regression: user A's report must never be served to user B via
|
||||
// POST /api/report/:ticker/ask without report_id.
|
||||
func TestInterrogateIDORScoped(t *testing.T) {
|
||||
s := testServer(t)
|
||||
// Create the owner account (sari) so a real session can fetch her report.
|
||||
if _, err := s.DB.CreateLocalUser("sari", "password1234"); err != nil {
|
||||
t.Fatalf("create sari: %v", err)
|
||||
}
|
||||
// Build a report for user "sari" (scoped user key).
|
||||
rep, id, err := s.Builder.Build(context.Background(), "TLKM", "moderate", "u:local:sari")
|
||||
if err != nil || id == 0 || rep.Ticker != "TLKM" {
|
||||
t.Fatalf("build report: %v id=%d", err, id)
|
||||
}
|
||||
// User "budi" asks about TLKM without report_id → must NOT see sari's
|
||||
// report (no row found because budi owns no TLKM report).
|
||||
budi := doAuth(t, s, "POST", "/api/report/TLKM/ask", map[string]any{"question": "kenapa?"})
|
||||
if budi.Code != http.StatusNotFound {
|
||||
t.Fatalf("user B interrogate without own report = %d, want 404 (IDOR)", budi.Code)
|
||||
}
|
||||
// But user "sari" (scoped to the existing report) succeeds.
|
||||
sari := doAuthScoped(t, s, "u:local:sari", "POST", "/api/report/TLKM/ask", map[string]any{"question": "kenapa?"})
|
||||
if sari.Code != http.StatusOK {
|
||||
t.Fatalf("owner interrogate = %d, want 200 (body %s)", sari.Code, sari.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ func (s *Server) loadReport(ticker string, id int64, userKey string) (string, st
|
||||
}
|
||||
return p, c, at, rid, nil
|
||||
}
|
||||
p, c, at, err := s.DB.LatestReport(ticker)
|
||||
p, c, at, err := s.DB.LatestReportForUser(ticker, userKey)
|
||||
if err != nil {
|
||||
return "", "", "", 0, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// Package api — rate limit helpers for auth endpoints.
|
||||
package api
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ipRateLimiter is a per-IP sliding window rate limiter.
|
||||
type ipRateLimiter struct {
|
||||
mu sync.Mutex
|
||||
windows map[string]*window
|
||||
limit int
|
||||
windowSz time.Duration
|
||||
}
|
||||
|
||||
type window struct {
|
||||
hits []time.Time
|
||||
}
|
||||
|
||||
func newIPRateLimiter(limit int, windowSz time.Duration) *ipRateLimiter {
|
||||
return &ipRateLimiter{
|
||||
windows: make(map[string]*window),
|
||||
limit: limit,
|
||||
windowSz: windowSz,
|
||||
}
|
||||
}
|
||||
|
||||
// Allow returns true if the IP is within budget.
|
||||
func (rl *ipRateLimiter) Allow(ip string) bool {
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
w, ok := rl.windows[ip]
|
||||
if !ok {
|
||||
w = &window{}
|
||||
rl.windows[ip] = w
|
||||
}
|
||||
// Trim entries outside the window.
|
||||
cutoff := now.Add(-rl.windowSz)
|
||||
n := 0
|
||||
for _, t := range w.hits {
|
||||
if t.After(cutoff) {
|
||||
w.hits[n] = t
|
||||
n++
|
||||
}
|
||||
}
|
||||
w.hits = w.hits[:n]
|
||||
if len(w.hits) >= rl.limit {
|
||||
return false
|
||||
}
|
||||
w.hits = append(w.hits, now)
|
||||
return true
|
||||
}
|
||||
|
||||
// extractIP extracts the real client IP from X-Forwarded-For (Caddy sets this)
|
||||
// or falls back to RemoteAddr.
|
||||
func extractIP(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
// First IP in the chain is the original client.
|
||||
if ip := net.ParseIP(xff[:len(xff)]); ip != nil {
|
||||
return xff
|
||||
}
|
||||
// Handle comma-separated: take first.
|
||||
for i := 0; i < len(xff); i++ {
|
||||
if xff[i] == ',' {
|
||||
return xff[:i]
|
||||
}
|
||||
}
|
||||
return xff
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
// rateLimitAuth is middleware that limits auth-related endpoints per IP:
|
||||
// max requests per sliding window.
|
||||
func (s *Server) rateLimitAuth(rl *ipRateLimiter, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ip := extractIP(r)
|
||||
if !rl.Allow(ip) {
|
||||
writeErr(w, http.StatusTooManyRequests, "terlalu banyak percobaan, coba lagi nanti")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -28,11 +28,16 @@ func (s *Server) ListRoutines(w http.ResponseWriter, r *http.Request) {
|
||||
LastRun any `json:"last_run"`
|
||||
}
|
||||
out := make([]rowOut, 0, len(rows))
|
||||
lastByRoutine, lerr := s.DB.LastRunsByRoutine(s.userKey(r))
|
||||
if lerr != nil {
|
||||
lastByRoutine = nil
|
||||
}
|
||||
for _, row := range rows {
|
||||
hist, _ := s.DB.RunHistory(row.ID, 1)
|
||||
var last any
|
||||
if len(hist) > 0 {
|
||||
last = hist[0]
|
||||
if lastByRoutine != nil {
|
||||
if v, ok := lastByRoutine[row.ID]; ok {
|
||||
last = v
|
||||
}
|
||||
}
|
||||
out = append(out, rowOut{row, last})
|
||||
}
|
||||
|
||||
@@ -45,10 +45,27 @@ func (s *Server) Screen(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
// Base universe: live screener when keyed, else stored watchlist.
|
||||
var universe []string
|
||||
if s.Cfg.HasSectorsKey() && (req.Where != "" || req.Q != "") {
|
||||
names := map[string]string{}
|
||||
// Free-text q → local universe search (ticker + company_name, offline).
|
||||
// The Sectors companies/ endpoint is not on this subscription, so remote
|
||||
// screening is skipped entirely to avoid a silent full-universe fallback.
|
||||
if req.Q != "" {
|
||||
if hits, err := s.DB.SearchTickers(req.Q, limit*2); err == nil {
|
||||
for _, h := range hits {
|
||||
universe = append(universe, h.Symbol)
|
||||
if h.CompanyName != "" {
|
||||
names[h.Symbol] = h.CompanyName
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if s.Cfg.HasSectorsKey() && req.Where != "" {
|
||||
if rows, err := s.Sectors.Screen(r.Context(), req.Where, req.Q, limit*2, 0); err == nil {
|
||||
for _, row := range rows {
|
||||
universe = append(universe, strings.ToUpper(strings.TrimSuffix(row.Symbol, ".JK")))
|
||||
tk := strings.ToUpper(strings.TrimSuffix(row.Symbol, ".JK"))
|
||||
universe = append(universe, tk)
|
||||
if row.CompanyName != "" {
|
||||
names[tk] = row.CompanyName
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,10 +78,18 @@ func (s *Server) Screen(w http.ResponseWriter, r *http.Request) {
|
||||
universe = s.Cfg.Watchlist
|
||||
}
|
||||
}
|
||||
// Fall back to stored company names when offline (universe table).
|
||||
storedNames, _ := s.DB.CompanyNames(universe)
|
||||
for tk, nm := range storedNames {
|
||||
names[tk] = nm
|
||||
}
|
||||
}
|
||||
var rows []ScreenRow
|
||||
for _, tk := range universe {
|
||||
row := s.scoreTicker(tk)
|
||||
if nm := names[tk]; nm != "" {
|
||||
row.Name = nm
|
||||
}
|
||||
if req.Institutional != nil {
|
||||
inst := req.Institutional
|
||||
if b, _ := row.Breakdown["broker_score"].(float64); b < inst.BrokerScoreMin {
|
||||
|
||||
@@ -63,14 +63,29 @@ func New(cfg config.Config, db *store.DB, cache *store.Cache, s *sectors.Client)
|
||||
func (s *Server) Router() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(middleware.Logger, middleware.Recoverer, middleware.Heartbeat("/ping"))
|
||||
// Cap request bodies (1 MiB) so large POSTs cannot exhaust memory.
|
||||
// JSON bodies here are tiny (auth, screen filters, chat prompts).
|
||||
r.Use(func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
if req.Body != nil && (req.Method == http.MethodPost || req.Method == http.MethodPut || req.Method == http.MethodPatch) {
|
||||
req.Body = http.MaxBytesReader(w, req.Body, 1<<20)
|
||||
}
|
||||
next.ServeHTTP(w, req)
|
||||
})
|
||||
})
|
||||
r.Route("/api", func(r chi.Router) {
|
||||
r.Get("/health", s.Health)
|
||||
r.Get("/auth/start", s.AuthStart)
|
||||
r.Get("/auth/callback", s.AuthCallback)
|
||||
r.Get("/auth/me", s.AuthMe)
|
||||
r.Post("/auth/logout", s.AuthLogout)
|
||||
r.Post("/auth/signup", s.AuthSignup)
|
||||
r.Post("/auth/login", s.AuthLogin)
|
||||
// Rate-limited auth endpoints: max 10 per IP per 60s.
|
||||
authRL := newIPRateLimiter(10, 60*time.Second)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(func(next http.Handler) http.Handler { return s.rateLimitAuth(authRL, next) })
|
||||
r.Post("/auth/signup", s.AuthSignup)
|
||||
r.Post("/auth/login", s.AuthLogin)
|
||||
})
|
||||
r.Get("/version", s.Version)
|
||||
// Publik baca: dashboard bisa dibuka tanpa login. Fitur + filter di bawah
|
||||
// wajib login (session cookie, tanpa demo bypass).
|
||||
|
||||
@@ -3,6 +3,7 @@ package reports
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"html"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -29,18 +30,21 @@ func (r Report) ToMarkdown() string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// ToHTML renders the report as a standalone page.
|
||||
// ToHTML renders the report as a standalone page. All dynamic values are
|
||||
// HTML-escaped — bodies come from stored snapshots/LLM and must never be able
|
||||
// to inject script into the exported file.
|
||||
func (r Report) ToHTML() string {
|
||||
esc := html.EscapeString
|
||||
var b strings.Builder
|
||||
b.WriteString(`<!doctype html><html><head><meta charset="utf-8"><title>`)
|
||||
b.WriteString(r.Ticker + " — FlowSight Report</title></head><body>")
|
||||
fmt.Fprintf(&b, "<h1>%s — FlowSight Report (%s)</h1>", r.Ticker, r.GeneratedAt)
|
||||
b.WriteString("<!doctype html><html><head><meta charset=\"utf-8\"><title>")
|
||||
b.WriteString(esc(r.Ticker) + " — FlowSight Report</title></head><body>")
|
||||
fmt.Fprintf(&b, "<h1>%s — FlowSight Report (%s)</h1>", esc(r.Ticker), esc(r.GeneratedAt))
|
||||
for _, s := range r.Sections {
|
||||
fmt.Fprintf(&b, "<h2>%s</h2><p>%s</p>", s.Name, s.Body)
|
||||
fmt.Fprintf(&b, "<h2>%s</h2><p>%s</p>", esc(s.Name), esc(s.Body))
|
||||
if len(s.Citations) > 0 {
|
||||
b.WriteString("<ul>")
|
||||
for _, c := range s.Citations {
|
||||
fmt.Fprintf(&b, "<li>%s %s @ %s</li>", c.Endpoint, c.Ticker, c.SnapshotAt)
|
||||
fmt.Fprintf(&b, "<li>%s %s @ %s</li>", esc(c.Endpoint), esc(c.Ticker), esc(c.SnapshotAt))
|
||||
}
|
||||
b.WriteString("</ul>")
|
||||
}
|
||||
@@ -50,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)
|
||||
@@ -79,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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- 0010_universe_names.sql: company names for screener display.
|
||||
ALTER TABLE universe ADD COLUMN company_name TEXT NOT NULL DEFAULT '';
|
||||
+159
-21
@@ -4,6 +4,7 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -401,6 +402,29 @@ func (db *DB) RunHistory(routineID int64, limit int, userKey ...string) ([]map[s
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// LastRunsByRoutine returns the single latest run per routine for a user —
|
||||
// used by ListRoutines to avoid an N+1 query per routine row.
|
||||
func (db *DB) LastRunsByRoutine(userKey string) (map[int64]map[string]any, error) {
|
||||
rows, err := q(db, `SELECT routine_id, started_at, status
|
||||
FROM routine_runs WHERE user_key=?
|
||||
AND id IN (SELECT MAX(id) FROM routine_runs WHERE user_key=? GROUP BY routine_id)`,
|
||||
userKey, userKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[int64]map[string]any{}
|
||||
for rows.Next() {
|
||||
var rid int64
|
||||
var started, status string
|
||||
if err := rows.Scan(&rid, &started, &status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[rid] = map[string]any{"started_at": started, "status": status}
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Alerts.
|
||||
|
||||
// Alert is one user rule row.
|
||||
@@ -602,9 +626,10 @@ func (db *DB) TickersWithForeign() (map[string]bool, error) {
|
||||
// SaveUniverse inserts the full ticker universe from the close sweep.
|
||||
// UniverseRow mirrors the CloseRow shape without importing sectors (cycle).
|
||||
type UniverseRow struct {
|
||||
Symbol string
|
||||
Close int64
|
||||
Date string
|
||||
Symbol string
|
||||
Close int64
|
||||
Date string
|
||||
CompanyName string
|
||||
}
|
||||
|
||||
func (db *DB) SaveUniverse(rows []UniverseRow) error {
|
||||
@@ -620,14 +645,98 @@ func (db *DB) SaveUniverse(rows []UniverseRow) error {
|
||||
// Normalize: API returns "BBCA.JK" — strip the suffix so it matches
|
||||
// watchlist/depth keys (BBCA) everywhere.
|
||||
t := strings.TrimSuffix(r.Symbol, ".JK")
|
||||
if _, err := tx.Exec(`INSERT OR IGNORE INTO universe(ticker, close, date) VALUES(?,?,?)`,
|
||||
t, r.Close, r.Date); err != nil {
|
||||
if _, err := tx.Exec(`INSERT OR IGNORE INTO universe(ticker, close, date, company_name) VALUES(?,?,?,?)`,
|
||||
t, r.Close, r.Date, r.CompanyName); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// CompanyNames returns the company name map for the given tickers (from the
|
||||
// universe table). Tickers with no stored name are omitted.
|
||||
func (db *DB) CompanyNames(tickers []string) (map[string]string, error) {
|
||||
if len(tickers) == 0 {
|
||||
return map[string]string{}, nil
|
||||
}
|
||||
ph := strings.Repeat("?,", len(tickers))
|
||||
ph = ph[:len(ph)-1]
|
||||
args := make([]any, len(tickers))
|
||||
for i, t := range tickers {
|
||||
args[i] = t
|
||||
}
|
||||
rows, err := db.Query(`SELECT ticker, company_name FROM universe
|
||||
WHERE company_name != '' AND ticker IN (`+ph+`)`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]string{}
|
||||
for rows.Next() {
|
||||
var t, nm string
|
||||
if err := rows.Scan(&t, &nm); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[t] = nm
|
||||
}
|
||||
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
|
||||
CompanyName string
|
||||
}
|
||||
|
||||
// SearchTickers finds universe tickers matching q in ticker or company_name
|
||||
// (case-insensitive), most-traded first. Works offline — no Sectors API call.
|
||||
func (db *DB) SearchTickers(q string, limit int) ([]TickerHit, error) {
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
like := "%" + strings.ToUpper(strings.TrimSpace(q)) + "%"
|
||||
rows, err := db.Query(`SELECT ticker, company_name FROM universe
|
||||
WHERE ticker LIKE ? OR UPPER(company_name) LIKE ?
|
||||
ORDER BY close DESC LIMIT ?`, like, like, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []TickerHit
|
||||
for rows.Next() {
|
||||
var h TickerHit
|
||||
if err := rows.Scan(&h.Symbol, &h.CompanyName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, h)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// AddWatch inserts a ticker (idempotent).
|
||||
func (db *DB) AddWatch(userKey, ticker string) error {
|
||||
_, err := db.Exec(`INSERT INTO watchlists(user_key,ticker,added_at) VALUES(?,?,?)
|
||||
@@ -710,7 +819,16 @@ func (db *DB) ListReports(ticker string, limit int) ([]map[string]any, error) {
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// LatestReport returns the newest report payload for a ticker.
|
||||
// LatestReportForUser returns the newest report payload for a ticker scoped
|
||||
// to the calling user (IDOR fix: never leak other users' reports).
|
||||
func (db *DB) LatestReportForUser(ticker, userKey string) (payload, cites, at string, err error) {
|
||||
err = db.QueryRow(`SELECT payload_json, citations_json, generated_at FROM reports
|
||||
WHERE ticker=? AND user_key=? ORDER BY id DESC LIMIT 1`, ticker, userKey).Scan(&payload, &cites, &at)
|
||||
return payload, cites, at, err
|
||||
}
|
||||
|
||||
// LatestReport returns the newest report payload for a ticker (global —
|
||||
// used only where user scoping is not required, e.g. internal reads).
|
||||
func (db *DB) LatestReport(ticker string) (payload, cites, at string, err error) {
|
||||
err = db.QueryRow(`SELECT payload_json, citations_json, generated_at FROM reports
|
||||
WHERE ticker=? ORDER BY id DESC LIMIT 1`, ticker).Scan(&payload, &cites, &at)
|
||||
@@ -852,28 +970,48 @@ func (db *DB) PruneSnapshots(cutoff string) (int64, error) {
|
||||
|
||||
// Daily volumes for technical/volume rules.
|
||||
|
||||
// DailyVolumes returns date-ordered volumes for a ticker from snapshots.
|
||||
// DailyVolumes returns date-ordered volumes for a ticker from snapshots,
|
||||
// deduped by bar date (each snapshot row stores a multi-day window, so a
|
||||
// naive LIMIT over rows massively duplicates dates and skews volume-anomaly
|
||||
// math). Returns the newest `limit` distinct trading days, oldest-first.
|
||||
func (db *DB) DailyVolumes(ticker string, limit int) ([]float64, []string, error) {
|
||||
// Pull extra rows (each holds up to 30 bars) and dedupe by bar date.
|
||||
rows, err := db.Query(`SELECT date, payload_json FROM snapshots
|
||||
WHERE ticker=? AND source='daily' ORDER BY date DESC LIMIT ?`, ticker, limit)
|
||||
WHERE ticker=? AND source='daily' ORDER BY date DESC LIMIT ?`, ticker, 200)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var vols []float64
|
||||
var dates []string
|
||||
byDate := map[string]float64{}
|
||||
seen := map[string]bool{}
|
||||
var dateOrder []string
|
||||
for rows.Next() {
|
||||
var d, p string
|
||||
if err := rows.Scan(&d, &p); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, b := range parseDailyBars(p, d) {
|
||||
if b.Volume > 0 {
|
||||
vols, dates = append(vols, b.Volume), append(dates, b.Date)
|
||||
if b.Volume <= 0 || seen[b.Date] {
|
||||
continue
|
||||
}
|
||||
seen[b.Date] = true
|
||||
byDate[b.Date] = b.Volume
|
||||
dateOrder = append(dateOrder, b.Date)
|
||||
}
|
||||
}
|
||||
return vols, dates, rows.Err()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// dateOrder is newest-first from the DESC scan; reverse for ascending.
|
||||
sort.Strings(dateOrder)
|
||||
if len(dateOrder) > limit {
|
||||
dateOrder = dateOrder[len(dateOrder)-limit:]
|
||||
}
|
||||
vols := make([]float64, 0, len(dateOrder))
|
||||
for _, d := range dateOrder {
|
||||
vols = append(vols, byDate[d])
|
||||
}
|
||||
return vols, dateOrder, nil
|
||||
}
|
||||
|
||||
// LatestClose returns the most recent close for a ticker.
|
||||
@@ -1055,17 +1193,17 @@ func (db *DB) UpdateDestination(id int64, userKey string, label *string, enabled
|
||||
|
||||
// GetDestination returns one push target owned by the user, or nil.
|
||||
func (db *DB) GetDestination(id int64, userKey string) (*Destination, error) {
|
||||
all, err := db.ListDestinations(userKey)
|
||||
var d Destination
|
||||
err := db.QueryRow(`SELECT id, user_key, kind, label, bot_token, chat_id, webhook_url, enabled
|
||||
FROM notification_destinations WHERE id=? AND user_key=?`, id, userKey).
|
||||
Scan(&d.ID, &d.UserKey, &d.Kind, &d.Label, &d.BotToken, &d.ChatID, &d.WebhookURL, &d.Enabled)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, d := range all {
|
||||
if d.ID == id {
|
||||
c := d
|
||||
return &c, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
return &d, nil
|
||||
}
|
||||
|
||||
// DeleteDestination removes one push target owned by the user.
|
||||
|
||||
@@ -107,3 +107,95 @@ func TestDestinationCRUD(t *testing.T) {
|
||||
t.Fatal("double delete must report false")
|
||||
}
|
||||
}
|
||||
|
||||
// Universe save + local ticker search + company-name lookup.
|
||||
func TestUniverseSearch(t *testing.T) {
|
||||
db, err := Open(t.TempDir() + "/univ.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", CompanyName: "PT Bank Rakyat Indonesia"},
|
||||
}
|
||||
if err := db.SaveUniverse(uni); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Search by ticker prefix (case-insensitive).
|
||||
hits, err := db.SearchTickers("bca", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(hits) != 1 || hits[0].Symbol != "BBCA" {
|
||||
t.Fatalf("bca hits = %+v, want BBCA", hits)
|
||||
}
|
||||
// Search by company name.
|
||||
hits, err = db.SearchTickers("bank", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(hits) != 2 {
|
||||
t.Fatalf("bank hits = %d, want 2 (BBCA+BBRI by name)", len(hits))
|
||||
}
|
||||
// .JK stripped on save, order by close desc.
|
||||
if hits[0].Symbol != "BBCA" || hits[1].Symbol != "BBRI" {
|
||||
t.Fatalf("bank order = %s,%s, want BBCA,BBRI", hits[0].Symbol, hits[1].Symbol)
|
||||
}
|
||||
// CompanyNames returns only tickers with stored names.
|
||||
names, err := db.CompanyNames([]string{"BBCA", "TLKM", "BBRI"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if names["BBCA"] != "PT Bank Central Asia Tbk" || names["BBRI"] != "PT Bank Rakyat Indonesia" {
|
||||
t.Fatalf("names = %+v, want BBCA+BBRI only", names)
|
||||
}
|
||||
if _, ok := names["TLKM"]; ok {
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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>
|
||||
|
||||
@@ -33,6 +33,7 @@ function AlertsInner() {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.createAlert({ name: tpl().label, rule: tpl().rule, channels: channels().split(",").map((c) => c.trim()).filter(Boolean) });
|
||||
setChannels("");
|
||||
refetch();
|
||||
} catch (e) { setErr(String(e)); }
|
||||
finally { setBusy(false); }
|
||||
@@ -49,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 (
|
||||
@@ -110,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>
|
||||
@@ -121,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>
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -28,13 +28,18 @@ function ReportInner() {
|
||||
// Refetch when the ticker param changes (ReportInner stays mounted
|
||||
// because Gate wraps it, but params.ticker is reactive).
|
||||
createEffect(on(() => params.ticker, () => load()));
|
||||
async function exportMd() { setMd(await api.reportMd(params.ticker)); }
|
||||
async function exportMd() {
|
||||
try { setMd(await api.reportMd(params.ticker)); }
|
||||
catch (e) { setErr(String(e)); }
|
||||
}
|
||||
async function ask() {
|
||||
if (!question().trim()) return;
|
||||
setAsking(true);
|
||||
try {
|
||||
const r = await api.interrogate(params.ticker, question());
|
||||
setAnswer(r.answer);
|
||||
} catch (e) {
|
||||
setErr(String(e));
|
||||
} finally { setAsking(false); }
|
||||
}
|
||||
function dl(url: string, name: string) {
|
||||
@@ -75,15 +80,21 @@ function ReportInner() {
|
||||
<CardContent class="flex flex-wrap gap-2">
|
||||
<Button variant="outline" onClick={exportMd}>Markdown</Button>
|
||||
<Button variant="outline" onClick={async () => {
|
||||
const r = await fetch(`/api/report/${encodeURIComponent(params.ticker)}?format=html`, { method: "POST", credentials: "same-origin" });
|
||||
if (r.ok) dl(URL.createObjectURL(new Blob([await r.text()], { type: "text/html" })), `${params.ticker}-report.html`);
|
||||
try {
|
||||
const r = await fetch(`/api/report/${encodeURIComponent(params.ticker)}?format=html`, { method: "POST", credentials: "same-origin" });
|
||||
if (!r.ok) { setErr(`HTML export gagal: HTTP ${r.status}`); return; }
|
||||
dl(URL.createObjectURL(new Blob([await r.text()], { type: "text/html" })), `${params.ticker}-report.html`);
|
||||
} catch (e) { setErr(String(e)); }
|
||||
}}>HTML</Button>
|
||||
<Button variant="outline" onClick={() => {
|
||||
dl(URL.createObjectURL(new Blob([JSON.stringify(rep(), null, 1)], { type: "application/json" })), `${params.ticker}-report.json`);
|
||||
}}>JSON</Button>
|
||||
<Button variant="outline" onClick={async () => {
|
||||
const r = await fetch(`/api/report/${encodeURIComponent(params.ticker)}?format=pdf`, { method: "POST", credentials: "same-origin" });
|
||||
if (r.ok) dl(URL.createObjectURL(await r.blob()), `${params.ticker}-report.pdf`);
|
||||
try {
|
||||
const r = await fetch(`/api/report/${encodeURIComponent(params.ticker)}?format=pdf`, { method: "POST", credentials: "same-origin" });
|
||||
if (!r.ok) { setErr(`PDF export gagal: HTTP ${r.status}`); return; }
|
||||
dl(URL.createObjectURL(await r.blob()), `${params.ticker}-report.pdf`);
|
||||
} catch (e) { setErr(String(e)); }
|
||||
}}>PDF</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Badge } from "../components/ui/badge";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../components/ui/card";
|
||||
import { Skeleton } from "../components/ui/skeleton";
|
||||
import { TextField, TextFieldInput } from "../components/ui/text-field";
|
||||
import { useNavigate } from "@solidjs/router";
|
||||
|
||||
// Preset awam -> body /api/screen. PRESET_SEMUA = default auto-jalan.
|
||||
@@ -24,14 +25,26 @@ function ScreenerInner() {
|
||||
const [busy, setBusy] = createSignal(false);
|
||||
const [err, setErr] = createSignal("");
|
||||
const [aktif, setAktif] = createSignal("");
|
||||
const [q, setQ] = createSignal("");
|
||||
const [showCustom, setShowCustom] = createSignal(false);
|
||||
async function runPreset(p: (typeof PRESETS)[number]) {
|
||||
setErr(""); setBusy(true); setAktif(p.label);
|
||||
setErr(""); setBusy(true); setAktif(p.label); setShowCustom(false);
|
||||
try {
|
||||
const r = await api.screen(p.body);
|
||||
setRows(r.rows); setRan(true);
|
||||
} catch (e) { setErr(String(e)); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
async function runCustom() {
|
||||
const query = q().trim();
|
||||
if (!query) return;
|
||||
setErr(""); setBusy(true); setAktif("custom");
|
||||
try {
|
||||
const r = await api.screen({ q: query, limit: 20 });
|
||||
setRows(r.rows); setRan(true);
|
||||
} catch (e) { setErr(String(e)); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
// Default = semua: auto-jalan preset "Semua" sekali saat halaman dibuka.
|
||||
onMount(() => { if (!ran()) void runPreset(PRESET_SEMUA); });
|
||||
const hasil = () => rows().map((r) => ({ row: r, ...verdictFor(r) }));
|
||||
@@ -48,6 +61,13 @@ function ScreenerInner() {
|
||||
<CardContent><Button size="sm" onClick={() => runPreset(p)} disabled={busy()}>{busy() && aktif() === p.label ? "Menyaring…" : "Tampilkan"}</Button></CardContent>
|
||||
</Card>
|
||||
)}</For>
|
||||
<Card class={showCustom() ? "border-primary" : ""}>
|
||||
<CardHeader class="pb-2"><CardTitle class="text-base">🔎 Cari kode saham</CardTitle><CardDescription>Ketik kode saham atau nama (mis. "bca", "tlkm", "bank").</CardDescription></CardHeader>
|
||||
<CardContent class="flex gap-2">
|
||||
<TextField class="flex-1"><TextFieldInput placeholder="mis. bca, tlkm, bbri…" value={q()} onInput={(e) => { setQ(e.currentTarget.value); setShowCustom(true); }} onKeyDown={(e: KeyboardEvent) => { if (e.key === "Enter") runCustom(); }} /></TextField>
|
||||
<Button size="sm" onClick={runCustom} disabled={busy() || !q().trim()}>{busy() && aktif() === "custom" ? "Menyaring…" : "Cari"}</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<Show when={err()}><p class="text-sm text-destructive">{err()}</p></Show>
|
||||
<Show when={busy()}><div class="space-y-2"><Skeleton class="h-24 w-full" /><Skeleton class="h-24 w-full" /></div></Show>
|
||||
@@ -60,7 +80,12 @@ function ScreenerInner() {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle class="text-xl font-bold">{s.row.symbol}</CardTitle>
|
||||
<div>
|
||||
<CardTitle class="text-xl font-bold">{s.row.symbol}</CardTitle>
|
||||
<Show when={s.row.name && s.row.name !== s.row.symbol}>
|
||||
<p class="text-sm text-muted-foreground">{s.row.name}</p>
|
||||
</Show>
|
||||
</div>
|
||||
<VerdictBadge verdict={s.verdict} />
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-3">
|
||||
|
||||
Reference in new issue
Block a user