Repository Public MIT
1// @vitest-environment node2/**3 * =============================================================================4 * SP BOUCHER | SOFTWARE & RESEARCH5 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project : VQuant9 * File : server/next/search.test.ts10 * Module : server11 * Repository : https://git.spboucher.ai/vquant12 * Project Website : https://vquant.spboucher.ai13 * Created : 2026-11-2014 * Last Modified : 2026-11-2015 *16 * Author : Simon-Pierre Boucher17 * Position : Professor of Finance18 * Institution : Université du Québec en Outaouais (UQO)19 * Organization : SP Boucher20 * Website : https://spboucher.ai21 * Git : https://git.spboucher.ai22 *23 * Preferred Contact: contact@spboucher.ai24 * Development : dev@spboucher.ai25 * Support : support@spboucher.ai26 * Security/Admin : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * SPDX Identifier : MIT35 * License : MIT License36 * License File : LICENSE37 *38 * Do not embed credentials, private keys, access tokens,39 * certificates or confidential personal information.40 *41 * =============================================================================42 * END OF SP BOUCHER SOURCE HEADER43 * =============================================================================44 */4546/**47 * Universal search (contract §3). The market-data provider is replaced by controllable functions; conversations48 * and objects are real rows in a temporary database.49 */50import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";51import { bootTestApp, type TestApp } from "./testkit";5253const fmp = vi.hoisted(() => ({54 searchCompanies: vi.fn(),55 searchName: vi.fn(),56 searchByISIN: vi.fn(),57}));58vi.mock("../services/fmpService", () => fmp);5960let t: TestApp;6162const APPLE = { symbol: "AAPL", name: "Apple Inc.", currency: "USD", stockExchange: "NASDAQ Global Select", exchangeShortName: "NASDAQ" };63const APLE = { symbol: "APLE", name: "Apple Hospitality REIT, Inc.", currency: "USD", stockExchange: "New York Stock Exchange", exchangeShortName: "NYSE" };64const BTC = { symbol: "BTCUSD", name: "Bitcoin USD", currency: "USD", stockExchange: "CCC", exchangeShortName: "CRYPTO" };6566const search = (user: string | null, query: string) => t.api(user, "GET", `/api/v2/search?${query}`);67const put = (user: string, kind: string, id: string, data: unknown) => t.api(user, "PUT", `/api/v2/objects/${kind}/${id}`, { data, baseRev: 0 });68const session = (id: string, owner: string, title: string, updatedAtSec: number, messages = "[]") =>69 t.db.prepare("INSERT INTO conversation_sessions (id, session_id, title, messages, owner, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(`row-${id}`, id, title, messages, owner, updatedAtSec, updatedAtSec);7071beforeAll(async () => {72 t = await bootTestApp();73 session("s-a1", "alice", "Apple valuation with a DCF", 1_763_000_000);74 session("s-a2", "alice", "Marge brute des épiciers", 1_763_000_100);75 session("s-a3", "alice", "100% equity or 60/40?", 1_763_000_200);76 session("s-a4", "alice", "Rates outlook", 1_763_000_300, JSON.stringify([{ question: "q", answer: "apple is mentioned only in the body" }]));77 session("s-b1", "bob", "Apple short thesis (Bob)", 1_763_000_400);78 await put("alice", "project", "p-apple", { title: "Apple fair value", question: "Is the multiple justified?", items: [] });79 await put("alice", "note", "n-apple", { title: "Reading list", body: "Remember the Apple 10-K footnotes on services." });80 await put("alice", "note", "n-other", { title: "Études de marché", body: "Rien à voir." });81 await put("alice", "watchlist", "w-tech", { name: "Tech leaders", symbols: ["AAPL", "MSFT"] });82 await put("alice", "portfolio", "pf-core", { name: "Core holdings", baseCurrency: "USD", positions: [{ symbol: "AAPL", quantity: 5 }] });83 await put("alice", "chart", "c-aapl", { symbol: "AAPL", interval: "1d", compare: ["MSFT"] });84 await put("bob", "project", "p-bob", { title: "Apple supplier map (Bob)", items: [] });85 await put("bob", "note", "n-bob", { title: "Bob's apple note", body: "apple apple apple" });86 await put("bob", "watchlist", "w-bob", { name: "Bob's list", symbols: ["AAPL"] });87});88afterAll(async () => {89 await t.close();90});91beforeEach(() => {92 fmp.searchCompanies.mockReset().mockResolvedValue([]);93 fmp.searchName.mockReset().mockResolvedValue([]);94 fmp.searchByISIN.mockReset().mockResolvedValue([]);95});9697describe("symbols", () => {98 it("merges ticker and name search, without duplicates, ticker matches first", async () => {99 fmp.searchCompanies.mockResolvedValue([APPLE]);100 fmp.searchName.mockResolvedValue([APLE, APPLE, BTC]);101 const r = await search("alice", "q=aapl&types=symbol");102 expect(r.status).toBe(200);103 expect(fmp.searchCompanies).toHaveBeenCalledWith("aapl", expect.any(Number));104 expect(fmp.searchName).toHaveBeenCalledWith("aapl");105 expect(fmp.searchByISIN).not.toHaveBeenCalled();106 expect(r.body.results.map((x: any) => x.id)).toEqual(["AAPL", "APLE", "BTCUSD"]);107 expect(r.body.results[0]).toEqual({ type: "symbol", id: "AAPL", title: "AAPL", subtitle: "Apple Inc. · NASDAQ · USD", symbol: "AAPL", exchange: "NASDAQ", score: 1 });108 // the asset class is stated only when the venue tells it109 expect(r.body.results[0]).not.toHaveProperty("assetClass");110 expect(r.body.results[2]).toMatchObject({ exchange: "CRYPTO", assetClass: "crypto" });111 expect(r.body).not.toHaveProperty("unavailable");112 });113114 it("sends a query shaped like an ISIN to the ISIN lookup", async () => {115 fmp.searchByISIN.mockResolvedValue([APPLE]);116 const r = await search("alice", "q=us0378331005&types=symbol");117 expect(fmp.searchByISIN).toHaveBeenCalledWith("US0378331005");118 expect(fmp.searchCompanies).not.toHaveBeenCalled();119 expect(fmp.searchName).not.toHaveBeenCalled();120 expect(r.body.results).toHaveLength(1);121 expect(r.body.results[0]).toMatchObject({ type: "symbol", symbol: "AAPL", score: 1 });122 // eleven characters, or no check digit: not an ISIN123 await search("alice", "q=US037833100&types=symbol");124 await search("alice", "q=US037833100X&types=symbol");125 expect(fmp.searchByISIN).toHaveBeenCalledTimes(1);126 expect(fmp.searchCompanies).toHaveBeenCalledTimes(2);127 });128129 it("keeps what one endpoint returns when the other fails", async () => {130 fmp.searchCompanies.mockRejectedValue(new Error("FMP 500"));131 fmp.searchName.mockResolvedValue([APLE]);132 const r = await search("alice", "q=apple&types=symbol");133 expect(r.body.results.map((x: any) => x.id)).toEqual(["APLE"]);134 expect(r.body).not.toHaveProperty("unavailable");135 });136137 it("returns the person's own results and says so when the provider is down", async () => {138 fmp.searchCompanies.mockRejectedValue(new Error("FMP_API_KEY not configured"));139 fmp.searchName.mockRejectedValue(new Error("FMP_API_KEY not configured"));140 const r = await search("alice", "q=apple");141 expect(r.status).toBe(200);142 expect(r.body.unavailable).toEqual(["symbol"]);143 expect(r.body.results.some((x: any) => x.type === "symbol")).toBe(false);144 expect(r.body.results.map((x: any) => x.id)).toContain("p-apple");145 expect(JSON.stringify(r.body)).not.toContain("FMP_API_KEY");146 });147148 it("gives up on a slow provider after 2.5 s and returns the rest", async () => {149 fmp.searchCompanies.mockReturnValue(new Promise(() => undefined));150 fmp.searchName.mockReturnValue(new Promise(() => undefined));151 const started = Date.now();152 const r = await search("alice", "q=apple");153 const took = Date.now() - started;154 expect(took).toBeGreaterThanOrEqual(2400);155 expect(took).toBeLessThan(4000);156 expect(r.status).toBe(200);157 expect(r.body.unavailable).toEqual(["symbol"]);158 expect(r.body.results.map((x: any) => x.id)).toContain("s-a1");159 }, 10_000);160161 it("does not call the provider when symbols are not asked for, or there is nothing to look up", async () => {162 await search("alice", "q=apple&types=project,note");163 await search("alice", "q=");164 await search("alice", "q=%20%20");165 await search("alice", "q=%2B&types=symbol");166 expect(fmp.searchCompanies).not.toHaveBeenCalled();167 expect(fmp.searchName).not.toHaveBeenCalled();168 });169});170171describe("the person's own material", () => {172 it("finds conversations by title, projects, notes, watchlists, portfolios and charts", async () => {173 const r = await search("alice", "q=apple&limit=50");174 const by = Object.fromEntries(r.body.results.map((x: any) => [`${x.type}:${x.id}`, x]));175 expect(by["conversation:s-a1"]).toMatchObject({ title: "Apple valuation with a DCF", subtitle: "2025-11-13" });176 expect(by["project:p-apple"]).toMatchObject({ title: "Apple fair value", subtitle: "Is the multiple justified?" });177 expect(by["note:n-apple"]).toMatchObject({ title: "Reading list" }); // matched in the body178 // titles only for conversations: a mention inside the messages is not a hit179 expect(by["conversation:s-a4"]).toBeUndefined();180 expect(by["note:n-other"]).toBeUndefined();181 // a title match outranks a body match182 expect(by["project:p-apple"].score).toBeGreaterThan(by["note:n-apple"].score);183184 const sym = (await search("alice", "q=aapl&limit=50")).body.results;185 const kinds = sym.map((x: any) => `${x.type}:${x.id}`);186 expect(kinds).toContain("watchlist:w-tech");187 expect(kinds).toContain("portfolio:pf-core");188 expect(kinds).toContain("chart:c-aapl");189 expect(sym.find((x: any) => x.type === "chart")).toMatchObject({ title: "AAPL", symbol: "AAPL", subtitle: "1d" });190 expect(sym.find((x: any) => x.type === "portfolio")).toMatchObject({ title: "Core holdings", subtitle: "1 position" });191 });192193 it("ignores accents and case", async () => {194 const r = await search("alice", "q=ETUDES");195 expect(r.body.results.map((x: any) => x.id)).toContain("n-other");196 const fr = await search("alice", `q=${encodeURIComponent("épiciers")}&types=conversation`);197 expect(fr.body.results.map((x: any) => x.id)).toEqual(["s-a2"]);198 });199200 it("treats % and _ in the query as text, not as wildcards", async () => {201 expect((await search("alice", "q=%25&types=conversation")).body.results.map((x: any) => x.id)).toEqual(["s-a3"]);202 expect((await search("alice", "q=_&types=conversation")).body.results).toEqual([]);203 expect((await search("alice", `q=${encodeURIComponent("' OR 1=1 --")}&types=conversation`)).body.results).toEqual([]);204 });205206 it("never returns another person's conversations or objects", async () => {207 fmp.searchCompanies.mockResolvedValue([APPLE]);208 const alice = await search("alice", "q=apple&limit=50");209 expect(JSON.stringify(alice.body)).not.toContain("Bob");210 expect(alice.body.results.every((x: any) => !["s-b1", "p-bob", "n-bob", "w-bob"].includes(x.id))).toBe(true);211212 const bob = await search("bob", "q=apple&limit=50");213 const ids = bob.body.results.filter((x: any) => x.type !== "symbol" && x.type !== "action").map((x: any) => x.id).sort();214 expect(ids).toEqual(["n-bob", "p-bob", "s-b1"]);215 const bobAapl = await search("bob", "q=aapl&limit=50&types=watchlist,portfolio,chart,project,note,conversation");216 expect(bobAapl.body.results.map((x: any) => x.id)).toEqual(["w-bob"]);217218 // a person with nothing gets nothing personal, whatever the query219 for (const q of ["apple", "a", "e", "%25"]) {220 const carol = await search("carol", `q=${q}&limit=50&types=conversation,project,note,watchlist,portfolio,chart`);221 expect(carol.body.results).toEqual([]);222 }223 });224});225226describe("actions", () => {227 it("finds navigation targets and engines by title or keyword", async () => {228 const quant = (await search("alice", "q=quant&types=action")).body.results;229 expect(quant[0]).toMatchObject({ type: "action", id: "nav:quant", title: "Quant Lab" });230 const garch = (await search("alice", "q=garch&types=action")).body.results;231 expect(garch.map((x: any) => x.id)).toEqual(["engine:volatility_lab"]);232 expect((await search("alice", "q=portefeuille&types=action")).body.results.map((x: any) => x.id)).toContain("nav:portfolio");233 expect((await search("alice", "q=terminal&types=action")).body.results[0].id).toBe("nav:terminal");234 expect((await search("alice", "q=zzzzzz&types=action")).body.results).toEqual([]);235 });236237 it("lists the navigation targets for an empty query", async () => {238 const r = await search("alice", "q=");239 expect(r.body.results.length).toBeGreaterThan(5);240 expect(r.body.results.every((x: any) => x.type === "action" && x.id.startsWith("nav:"))).toBe(true);241 });242});243244describe("request", () => {245 it("ranks by score, exact symbol first, and honours limit", async () => {246 fmp.searchCompanies.mockResolvedValue([APPLE]);247 fmp.searchName.mockResolvedValue([APLE]);248 const r = await search("alice", "q=aapl&limit=50");249 expect(r.body.results[0]).toMatchObject({ type: "symbol", id: "AAPL", score: 1 });250 const scores = r.body.results.map((x: any) => x.score);251 expect(scores).toEqual([...scores].sort((a, b) => b - a));252 expect(scores.every((s: number) => s > 0 && s <= 1)).toBe(true);253 expect((await search("alice", "q=aapl&limit=2")).body.results).toHaveLength(2);254 expect((await search("alice", "q=a&limit=9999")).body.results.length).toBeLessThanOrEqual(50);255 });256257 it("filters by type and refuses an unknown one", async () => {258 fmp.searchCompanies.mockResolvedValue([APPLE]);259 const r = await search("alice", "q=apple&types=note,project");260 expect(new Set(r.body.results.map((x: any) => x.type))).toEqual(new Set(["note", "project"]));261 expect((await search("alice", "q=apple&types=note,passwords")).status).toBe(400);262 // accepted types that have no source yet answer nothing rather than failing263 expect((await search("alice", "q=apple&types=report,indicator")).body.results).toEqual([]);264 });265266 it("is refused when not signed in", async () => {267 expect((await search(null, "q=apple")).status).toBe(401);268 });269});270