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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
# U2INVEST Current Product PRD

## 1. Executive Summary

U2INVEST is a three-pillar financial product that combines:

1. Knowledge Academy
2. Trading Lab
3. U2CHAT AI assistant

The current implementation is a Flask-served single-page web app with:

- one primary frontend file: `templates/index.html`
- one primary backend/API file: `web_app.py`
- a LangGraph agent workflow: `agent_graph.py`
- stock/RAG tools: `tools.py`
- a Chroma-backed PDF knowledge pipeline: `vector_store.py`
- a CLI-style agent test entrypoint: `main.py`

This PRD is not a concept document. It is a product-truth document for the current repository. It extracts the actual functions, features, states, gaps, and upgrade paths so the whole UI can be rebuilt without losing product scope.

## 2. Product Vision

Help beginner and intermediate investors learn investing, practice safely, and ask an AI assistant for analysis inside one integrated product.

## 2.1 Commercial Website Vision

U2INVEST should not behave only like an internal demo app or portfolio prototype. As a commercial web product, it should also present itself like a credible business:

- discoverable
- trustworthy
- contactable
- explainable
- legally defensible
- conversion-oriented

That means the final product should include both:

- the product application layer
- the public business/marketing/sales website layer

## 3. Rebuild Objective

Rebuild the entire UI while preserving the full current functional scope, making the product:

- simpler
- calmer
- more premium
- more structurally consistent
- more maintainable
- more trustworthy as a product

The rebuild should not accidentally reduce scope. It should preserve the current breadth of Academy, Lab, and U2CHAT while fixing partial features and surfacing hidden capabilities.

The rebuild should also expand the current landing shell into a proper commercial website experience with public-facing business, sales, trust, and contact functionality.

## 4. Target Users and Core Jobs

### Primary users

- Beginner investors who want structured financial education
- Early-stage self-directed investors who want a safe trading simulator
- Users who want an AI assistant to explain stocks, market concepts, and strategies

### Secondary users

- Recruiters or reviewers evaluating product thinking and technical execution
- Users who want a local finance-learning demo with AI and charts
- Prospective customers evaluating whether to trust or buy the product
- Business partners, media contacts, and inbound collaborators
- Prospective hires or stakeholders evaluating the company and product credibility

### Core jobs to be done

- "Teach me the fundamentals of investing."
- "Let me practice trading without risking money."
- "Help me analyze a stock with live data and research context."
- "Give me a workspace where learning, simulation, and AI analysis connect."
- "Help me understand what this company/product is and whether I should trust it."
- "Give me a clear way to contact the business, book a demo, or start using the product."
- "Show me enough credibility, legal clarity, and product value to convert me into a lead or customer."

## 5. Current System Map

### Product shell

- Flask serves a single-page frontend shell
- SPA-like view switching happens in the browser through `showView()`
- A browser session receives a generated `user_id`

### Core product surfaces

- Landing page
- Knowledge Academy
- Trading Lab
- U2CHAT
- Public business/marketing website layer, currently only minimally represented by the landing page

### AI and data layer

- LLM access is configured through `ChatOpenAI` using a DeepSeek-style OpenAI-compatible API
- LangGraph manages reasoning plus tool routing
- SQLite persists LangGraph checkpoints
- AkShare provides live stock data when available
- Chroma stores local knowledge-base embeddings
- PDFs in `knowledge/` power retrieval

### Deployment layer

- Local Python execution
- Dockerfile
- `docker-compose.yml`
- `.env` configuration

## 6. Detailed Current Feature Inventory

## 6.1 Landing and Global Navigation

### User-facing features

- Fixed top navigation with logo and links to Academy, Lab, and U2CHAT
- Branded landing hero with product tagline
- Three large entry cards for the three product pillars
- In-browser view switching without page reload

### Supporting frontend functions

- `showView(v)`

### Supporting backend functions

- `index()`

### Current status

- Implemented

### Current gaps

- No deep links for major product surfaces
- No browser-history-aware routing
- No route-level loading state
- No persistent "last visited workspace" behavior
- No commercial footer
- No contact information surface
- No social links
- No company/about section
- No trust or proof section
- No demo, signup, or lead-capture CTA flow
- No legal links or disclosures in the public shell

## 6.2 Knowledge Academy

### Current content model

The Academy currently includes 50 hardcoded modules in `ACADEMY_DATA`. Each module includes:

- `id`
- `parent`
- `cat`
- `difficulty`
- `name`
- `video`
- `source`
- `views`
- `completed`
- `ratings`
- `video_intro`
- `outcomes`
- `takeaways`

### User-facing features currently implemented

- Academy landing view
- Grid view of all modules
- Category label on module cards
- Module view counts on cards
- Completion badge on cards
- Lesson overlay panel
- Embedded YouTube lesson video
- Lesson intro copy
- Outcomes list
- Takeaways list
- Completion state CTA
- Comments thread
- Comment replies
- Comment sorting: Top / Newest
- Share modal
- Share actions for WhatsApp, Facebook, X, LinkedIn, email, copy link
- Visual roadmap mode
- Curated roadmap mode: "Designed By U2INVEST"
- Custom roadmap mode: "You to Design"
- Custom roadmap actions:
  - add node
  - drag node
  - connect nodes
  - break link
  - delete node
- Toast notifications
- Confirmation modal for roadmap destructive actions

### Frontend functions powering Academy

- `loadData()`
- `openModule(id)`
- `openShare()`
- `closeShare()`
- `copyLink()`
- `renderComments(list)`
- `replyAt(user, commentId)`
- `replyToReply(user, parentCommentId)`
- `cancelReply()`
- `postComment()`
- `setRoadmapMode(mode)`
- `initRoadmap()`
- `dragstarted(event, d)`
- `dragged(event, d)`
- `dragended(event, d)`
- `renderCustomRoadmap(g, svg)`
- `resetPorts()`
- `openConfirm(title, desc, onOk, onCancel)`
- `openNodeModal()`
- `closeNodeModal()`
- `addCustomNode()`
- `switchAcademy(tab)`
- `closeModule()`
- `renderStatusBox(isDone)`
- `toggleStatus(isDone)`
- `sortComments(type)`
- `showToast(msg)`

### Backend/API functions powering Academy

- `get_academy()`
- `get_course(cid)`
- `post_comment()`
- `like_comment_main()`
- `like_reply_unique()`
- `toggle_complete()`
- `rate_course()`

### What is fully implemented

- Module browsing
- Module overlay experience
- Comment posting and replies
- Completion toggle
- Average rating display
- Curated roadmap rendering
- Custom roadmap editing in current browser session

### What is partial or latent

- `parent` exists in the data model but is not used as the real prerequisite structure in the UI
- `source` exists in the data model but is not surfaced in the UI
- `difficulty` is used in roadmap coloring but not clearly surfaced elsewhere
- `rate_course()` exists in the backend, but there is no visible rating submission UI in the current frontend
- `like_comment_main()` and `like_reply_unique()` exist in the backend, but the frontend references `toggleLike()` and `toggleReplyLike()` handlers that do not exist
- Comment dislike icons are visual only and do not trigger anything
- Share URLs point to `/module/<id>`, but that route is not implemented in Flask

### Known Academy issues to carry into the rebuild plan

- Comment like buttons are visible but broken because the JS handlers are missing
- Rating is display-only in the current UI
- Shared module URLs are not truly deep-linkable
- Comment timestamps are rendered as hardcoded "2 hours ago" / "1 hour ago" strings, not real relative times
- Academy progress, comments, and ratings are stored in runtime memory only
- Academy progress is not per-user durable data
- Academy state is globally mutable on the server
- `get_course(cid)` does not guard missing IDs cleanly before `.copy()`
- Custom roadmap state is not persisted to local storage or backend
- The auto roadmap is a generated visualization, not a precise prerequisite map

### Academy advancement opportunities

- Make progress, comments, ratings, and custom roadmap persistent
- Convert `parent` into a true learning dependency graph
- Add search, filter, and sorting across modules
- Add difficulty badges and progress percentages
- Surface lesson `source` and instructor credibility more clearly
- Add note-taking, bookmarks, and study highlights
- Add quizzes, checkpoints, and completion scoring
- Add user-specific learning plans and recommended next lessons
- Add proper rating submission UI and review aggregation
- Add moderation, abuse control, and comment reporting if community features stay
- Add actual shareable deep links and direct-open module routes

## 6.3 Trading Lab

### Current product concept

The Lab is a paper-trading workspace for A-share-style stock simulation, with a separate beginner guide path.

### User-facing features currently implemented

- Lab gateway with two paths:
  - advanced dashboard
  - beginner guide
- Beginner guide step flow with 3 educational steps
- Stock pool grouped by sectors:
  - Popular
  - Tech
  - Energy
  - Finance
- Quote cards for stocks in the selected sector
- Stock selection for chart/trade context
- K-line chart area
- Trade ticket with symbol, price, shares, and total
- Buy action
- Sell action
- Holdings panel
- History panel container
- Portfolio stats:
  - Total Assets
  - Cash
  - Profit
  - Return
- Reset portfolio
- Refresh dashboard

### Data model and business rules

- Starting cash: $100,000
- Holdings are tracked per symbol
- Trade history is stored on buy/sell
- Buy checks available cash
- Sell checks whether holdings exist and whether the user has enough shares
- Frontend requires minimum `100` shares

### Frontend functions powering Trading Lab

- `loadLabData()`
- `loadSectorStocks()`
- `selectStock(stock)`
- `initKlineChart()`
- `loadKlineData(symbol, days = 60)`
- `calculateTotal()`
- `executeTrade(action)`
- `updatePortfolioUI()`
- `resetPortfolio()`
- `refreshLab()`
- `updateGuideUI()`
- `nextGuideStep()`
- `prevGuideStep()`
- `setLabView(view)`

### Backend/API functions powering Trading Lab

- `get_stock_pool()`
- `get_real_quote()`
- `get_kline_data()`
- `get_portfolio()`
- `execute_trade()`
- `reset_portfolio()`
- `get_market_data()`

### What is fully implemented

- Gateway flow between beginner and advanced entry
- Beginner guide progression
- Sector-based stock list loading
- Quote retrieval with live-data fallback behavior
- K-line retrieval with live-data fallback behavior
- Paper buy/sell execution
- Cash/holdings update logic
- Portfolio reset

### What is partial or latent

- Trade history is stored in backend state but not rendered into the visible `history-list`
- Return stat exists in the UI but is not updated in `updatePortfolioUI()`
- Time-range buttons `60D`, `120D`, `250D` are visible, but `changeTimeRange()` does not exist
- `get_market_data()` exists as a synthetic endpoint but is not used by the current main UI
- `user_portfolio.json` exists in the repo but is not used by the current app

### Known Trading Lab issues to carry into the rebuild plan

- Stock selection uses `event.currentTarget` without passing `event`, so the behavior is fragile
- Portfolio value is calculated from average cost basis, not live mark-to-market pricing
- Profit shown is therefore not true unrealized P&L
- Return shown is currently a placeholder
- History panel is currently a placeholder
- Backend trusts the client-supplied execution price in `/api/lab/trade`
- No watchlist, compare view, or market context around a selected stock
- No order types beyond instant buy/sell
- No slippage, fees, order status, or risk feedback
- Lab state is per-session in memory only and resets on server restart

### Trading Lab advancement opportunities

- Implement live mark-to-market portfolio valuation
- Render complete transaction history with timestamps and realized/unrealized P&L
- Implement `changeTimeRange()` and persist selected chart interval
- Add watchlists and favorite symbols
- Add news and fundamentals side panels for the selected stock
- Add comparison mode across multiple stocks
- Add educational hints tied to user actions
- Add more order types: market, limit, stop, stop-limit
- Add simulated fees, taxes, and slippage
- Add portfolio allocation visualization and performance analytics
- Add saved paper accounts and multiple portfolios
- Make the server authoritative for pricing instead of trusting client price input

## 6.4 U2CHAT

### Current product concept

U2CHAT is a financial assistant that combines:

- LLM reasoning
- tool calling
- local knowledge retrieval
- stock-related quick context selection
- inline chart rendering in chat

### User-facing features currently implemented

- Dedicated chat workspace
- Sidebar with recent sessions
- New chat action
- Session reload from sidebar
- Clear current chat
- Quick stock-select chips by sector
- Selected-stock chip strip
- Prompt input with auto-resize
- Enter to send
- Shift+Enter for newline
- Stop button state during generation
- Assistant/user message bubbles
- Simple markdown-like rendering for headings and bullets
- Inline chart rendering from `json-chart` blocks
- Empty state for no conversation

### Frontend functions powering U2CHAT

- `loadAgentData()`
- `loadAgentStocks()`
- `addStockToChat(stock)`
- `updateSelectedStocks()`
- `removeStock(i)`
- `sendMessage()`
- `updateSendButtonState()`
- `addMessageToUI(role, content, tools = [])`
- `renderChart(containerId, data)`
- `loadChatSessions()`
- `loadChatSession(sessionId)`
- `clearChat()`
- `newChat()`
- `handleAgentKey(e)`
- `autoResize(t)`

### Backend/API functions powering U2CHAT

- `agent_chat()`
- `get_chat_sessions()`
- `get_chat_history()`
- `clear_chat_history()`

### Agent workflow functions

- `AgentState`
- `call_model(state)`
- `route_logic(state)`

### Agent tools

- `get_realtime_quote(symbol)`
- `get_stock_news(symbol)`
- `get_historical_kline(symbol)`
- `get_fundamental_data(symbol)`
- `query_knowledge_base(query)`

### What is fully implemented

- Chat session creation
- Session title generation from the first message
- Session history retrieval while the server is running
- LangGraph-based tool routing
- LLM response generation
- Inline chart rendering from model-generated JSON blocks
- Sector-based quick stock selection
- PDF-based retrieval tool availability

### What is partial or latent

- `agent_chat()` internally iterates `stock_agent_app.stream(...)`, but the frontend does not receive true streaming output; it waits for the final JSON response
- Tool call metadata is collected as `tools_used`, but the frontend does not surface it
- The "stop" button aborts the browser request, but there is no backend cancellation mechanism
- Chat persistence is split:
  - visible session metadata and messages are in memory
  - LangGraph checkpoints are in SQLite
- Quick stock selection adds stock text into the prompt, but does not create structured chat context objects

### Known U2CHAT issues to carry into the rebuild plan

- If the server restarts, the sidebar session list and visible session history are lost
- SQLite checkpoints survive, but the current UI model does not reconnect to them cleanly
- `renderChart()` supports simple line/bar assumptions only
- The system prompt mandates structured English responses, but the UI does not visibly explain the assistant's answer format
- The app stores tool call names and args, not a clear user-facing execution trace
- No citation/source cards are shown for RAG output
- No streaming token UI or stepwise reasoning trace is exposed
- `addMessageToUI()` injects rendered HTML directly, which should be treated carefully in a full rebuild

### U2CHAT advancement opportunities

- Add true streaming responses to the UI
- Add server-side cancellation or job interruption support
- Surface tool usage, tool results, and sources visibly
- Show retrieval sources with document titles and snippets
- Add follow-up suggestions and prompt shortcuts
- Add chart cards, ticker cards, and fundamentals cards as structured UI blocks
- Add conversation search, pinning, renaming, and grouping
- Add better state recovery after refresh and restart
- Add a dedicated research mode, beginner mode, and fast quote mode
- Add file upload and portfolio-aware chat once persistence exists

## 6.5 Shared and Platform Features

### Current shared UX/system features

- Toast notification surface
- Confirmation modal
- Custom-node modal
- Session-based `user_id`
- Environment-variable-based secret key
- Broad CORS enablement
- Dockerfile
- Docker Compose mounts for:
  - `chroma_db`
  - `checkpoints.sqlite`

### AI/knowledge infrastructure features

- PDF discovery across `knowledge/` recursively
- Empty retriever fallback if no PDFs exist
- PDF loading with `PyPDFLoader`
- Content deduplication by MD5 hash
- Metadata enrichment for source tracking
- Chunking with overlap
- Persistent Chroma vector store
- Incremental addition when new files appear
- Retriever configured with `k=5`

### Developer and demo features

- CLI interactive session in `main.py`
- Synthetic market endpoint `get_market_data()`

### Current platform gaps

- No authentication layer
- No persistent database for Academy or Lab user state
- No test suite in the current repo
- No analytics or product instrumentation
- Frontend is monolithic and globally stateful
- Vector-store refresh logic detects new files, but not modified/deleted files robustly

## 6.6 Commercial Website and Business Layer

### Current product reality

The current repo has a landing page, branding, and product-entry navigation, but it does not yet function like a complete commercial business website.

### Current business-site features actually present

- logo and brand mark
- positioning tagline
- top navigation
- high-level entry points into the three product pillars

### Commercial website features required for a professional business product

This section defines the required public-facing website layer that should exist alongside the product application.

### A. Global brand and navigation requirements

- public homepage
- consistent header navigation
- clear primary CTA
- secondary CTA for contact/demo/learn more
- professional footer
- company identity and copyright area
- social links
- legal links
- contact links
- app entry / sign in / get started entry points

### B. Marketing and sales page requirements

- homepage with clear value proposition
- product overview page
- feature overview sections for Academy, Lab, and U2CHAT
- use-case or solution sections
- pricing page or pricing inquiry flow
- demo-request flow
- FAQ page or FAQ section
- about/company page
- contact page
- resources/blog/news section
- optional case studies/testimonials page

### C. Trust and credibility requirements

- social proof or customer logos
- testimonials or endorsements
- team/founder credibility
- explanation of product methodology
- explanation of data sources
- privacy and security positioning
- financial education / not-financial-advice disclaimers where relevant
- risk disclosure for finance-related content and simulation features
- transparent explanation of what is live data vs simulated vs educational

### D. Lead generation and conversion requirements

- contact form
- demo-booking form
- newsletter/signup capture
- waitlist or get-started capture
- strong CTA system across the site
- success / thank-you states after form submission
- lead routing to email/CRM
- downloadable asset or resource capture if content marketing is used

### E. Social and communication requirements

- LinkedIn link
- X/Twitter link if used
- GitHub link if relevant to brand/company presence
- YouTube or media channel link if educational content is part of go-to-market
- business email contact
- optional phone number
- optional business address or registered business location
- press / partnership contact path

### F. Legal, compliance, and policy requirements

- privacy policy
- terms of service
- cookie policy
- disclaimer
- risk disclosure
- acceptable-use policy if user-generated content or AI chat remains public-facing
- accessibility statement
- data and AI usage disclosure

### G. SEO, discoverability, and content requirements

- page titles and meta descriptions
- Open Graph / social preview metadata
- sitemap
- robots configuration
- structured data where useful
- clean semantic headings
- internal linking strategy
- indexable product explainer content
- resource/blog structure if SEO is part of acquisition

### H. Analytics, sales operations, and support requirements

- page analytics
- CTA click tracking
- form conversion tracking
- attribution tracking
- CRM or inbox integration for inbound leads
- contact management flow
- support/help contact path
- error/success instrumentation for forms and CTAs

### I. Finance-product-specific commercial requirements

- clear statement of educational vs advisory scope
- data freshness / source disclaimers
- simulation disclaimers for the Trading Lab
- AI-answer limitations and responsible-use language
- clear explanation of whether the platform gives education, research assistance, or actionable advice

### Current status

- mostly missing

### Known commercial website gaps in the current repo

- no footer with business information
- no contact page or contact form
- no social links
- no about/company page
- no pricing or demo request flow
- no lead-capture forms
- no testimonials, customer proof, or trust content
- no legal pages
- no cookie/privacy consent flow
- no support/help path
- no SEO-oriented public content structure
- no analytics or conversion tracking
- no finance-specific commercial disclaimers in the public website shell

### Commercial website advancement opportunities

- turn the landing page into a true commercial homepage
- create a full footer and public information architecture
- add contact, demo, and get-started flows
- add proof, trust, and authority sections
- add legal/compliance surface suitable for a finance-related product
- add SEO and content marketing structure
- add analytics and CRM integration
- add conversion-focused CTA system across the entire public experience

See `COMMERCIAL_WEBSITE_SITEMAP_AND_PAGE_SPEC.md` for the concrete sitemap, page-by-page public website specification, CTA architecture, footer requirements, form requirements, and lead funnel design.

## 7. Complete Engineering Function Inventory

This section is the full code-level function inventory for rebuild planning.

## 7.1 `web_app.py`

- `index()`: serve the main SPA and initialize `session['user_id']`
- `get_academy()`: return the full Academy module list
- `get_course(cid)`: return a specific course plus computed average rating and comments
- `post_comment()`: create top-level comments or replies
- `like_comment_main()`: increment/decrement comment like count
- `like_reply_unique()`: increment/decrement reply like count
- `toggle_complete()`: set lesson completion state
- `rate_course()`: append a rating and return the updated average
- `get_market_data()`: return synthetic OHLCV-style market data
- `get_stock_pool()`: return grouped stock symbol lists
- `get_real_quote()`: return live or simulated quote data for one or more symbols
- `get_kline_data()`: return live or simulated historical daily K-line data
- `get_portfolio()`: return current user's simulated portfolio
- `execute_trade()`: execute a paper buy or sell
- `reset_portfolio()`: restore paper portfolio to default starting cash
- `agent_chat()`: create/load a chat session, invoke the agent, save the assistant response
- `get_chat_sessions()`: return chat-session list sorted by timestamp
- `get_chat_history()`: return messages for one chat session
- `clear_chat_history()`: clear one session or all sessions for the current user

## 7.2 `agent_graph.py`

- `AgentState`: typed graph state definition for message history
- `call_model(state)`: run the LLM with the system prompt plus tools
- `route_logic(state)`: send the flow either to tool execution or to `END`

### Agent graph behavior

- LLM model: `deepseek-chat`
- Temperature: `0`
- System prompt rules:
  - English only
  - concise headings and bullets
  - no `**bold**` emphasis inside prose
  - emit `json-chart` blocks for stock analysis visuals
  - respond with a structured market-analysis template

## 7.3 `tools.py`

- `get_realtime_quote(symbol)`: fetch latest price, change, high, low
- `get_stock_news(symbol)`: fetch latest headlines
- `get_historical_kline(symbol)`: fetch last 60 daily data points and return JSON string
- `get_fundamental_data(symbol)`: fetch PE, PB, and ROE-style metrics
- `query_knowledge_base(query)`: retrieve relevant PDF text snippets

## 7.4 `vector_store.py`

- `build_vector_db(persist_directory, knowledge_base_path)`: build or load the vector store and return a retriever

### Internal behavior inside `build_vector_db()`

- create empty knowledge directory if missing
- return empty retriever if no PDFs exist
- recursively discover PDFs
- load PDFs
- deduplicate by content hash
- attach source metadata
- split text into chunks
- build or load persistent Chroma DB
- incrementally add documents if new files are detected
- return retriever configured with `k=5`

## 7.5 `main.py`

- `start_interactive_session()`: run a CLI chat session against the LangGraph app

## 7.6 `templates/index.html` frontend functions

### Global shell

- `showView(v)`

### Academy

- `loadData()`
- `openModule(id)`
- `openShare()`
- `closeShare()`
- `copyLink()`
- `renderComments(list)`
- `replyAt(user, commentId)`
- `replyToReply(user, parentCommentId)`
- `cancelReply()`
- `postComment()`
- `setRoadmapMode(mode)`
- `initRoadmap()`
- `dragstarted(event, d)`
- `dragged(event, d)`
- `dragended(event, d)`
- `renderCustomRoadmap(g, svg)`
- `resetPorts()`
- `openConfirm(title, desc, onOk, onCancel)`
- `openNodeModal()`
- `closeNodeModal()`
- `addCustomNode()`
- `switchAcademy(tab)`
- `closeModule()`
- `renderStatusBox(isDone)`
- `toggleStatus(isDone)`
- `sortComments(type)`
- `showToast(msg)`

### Trading Lab

- `loadLabData()`
- `loadSectorStocks()`
- `selectStock(stock)`
- `initKlineChart()`
- `loadKlineData(symbol, days = 60)`
- `calculateTotal()`
- `executeTrade(action)`
- `updatePortfolioUI()`
- `resetPortfolio()`
- `refreshLab()`
- `updateGuideUI()`
- `nextGuideStep()`
- `prevGuideStep()`
- `setLabView(view)`

### U2CHAT

- `loadAgentData()`
- `loadAgentStocks()`
- `addStockToChat(stock)`
- `updateSelectedStocks()`
- `removeStock(i)`
- `sendMessage()`
- `updateSendButtonState()`
- `addMessageToUI(role, content, tools = [])`
- `renderChart(containerId, data)`
- `loadChatSessions()`
- `loadChatSession(sessionId)`
- `clearChat()`
- `newChat()`
- `handleAgentKey(e)`
- `autoResize(t)`

## 7.7 UI handlers currently referenced but missing

- `toggleLike(...)`
- `toggleReplyLike(...)`
- `changeTimeRange(...)`

These missing handlers are currently important product gaps because visible UI controls already depend on them.

## 8. Current Data, Persistence, and State Boundaries

### Browser/session state

- Flask session stores `user_id`

### Academy state

- Module catalog is hardcoded in memory
- Completion flags mutate in server memory
- Ratings mutate in server memory
- Comments mutate in server memory
- Academy state is shared globally in the process, not persisted per user

### Trading Lab state

- Portfolio is stored in a `defaultdict`
- State is keyed by `user_id`
- State is not persisted across server restarts

### Chat state

- Visible session list and session messages are stored in `CHAT_SESSIONS`
- LangGraph thread memory is stored in `checkpoints.sqlite`
- These two sources of truth are not unified

### Knowledge base state

- Vector DB persists in `chroma_db`
- Knowledge documents live in `knowledge/`
- Retriever creation currently happens at import/startup time

### Important persistence implications

- Academy feels persistent only while the process is running
- Lab feels persistent only while the process is running
- U2CHAT appears partially persistent because LangGraph checkpoints survive, but the visible session list does not

## 9. UI Rebuild Product Requirements

The UI rebuild should preserve current scope while correcting the current architecture and interaction quality.

### Preserve these product surfaces

- Landing page
- Public commercial website layer
- Knowledge Academy
- Trading Lab
- U2CHAT
- Lesson overlay
- Share modal
- Roadmap modes
- Beginner guide
- Chat session sidebar

### Preserve these interaction capabilities

- Module browsing
- Lesson detail opening
- Comment/reply posting
- Completion toggling
- Custom roadmap editing
- Stock browsing by sector
- Quote and chart loading
- Paper trade execution
- Chat session creation and reopening
- AI chart rendering in chat
- clear contact and conversion entry paths once added

### Rebuild requirements

- Move away from the current single-file frontend architecture
- Introduce a clean design system with reusable tokens and components
- Make navigation, overlays, and workspaces consistent across the three pillars
- Add a real public business-site information architecture, not only an app shell
- Add proper loading, empty, error, success, and disabled states
- Make the app fully responsive on desktop and mobile
- Add visible keyboard focus states
- Reduce reliance on global mutable frontend state
- Add proper deep-linking strategy for major views and modules
- Preserve D3 and ECharts capabilities while improving presentation
- Keep the UI minimalist, but not scope-reductive

### Commercial website requirements

- Add a professional homepage that can sell the product clearly
- Add a full footer with contact, social, legal, and business links
- Add contact and demo-request flows
- Add visible trust and credibility sections
- Add public-facing about/company context
- Add legal/policy/disclaimer surfaces
- Add conversion-focused CTA hierarchy
- Add SEO-ready page structure and metadata strategy
- Add support/help and business inquiry pathways
- Make the site feel commercially credible, not only visually polished

### Rebuild-specific UX requirements

- The Academy should feel like a premium reading and learning workspace
- The Lab should feel like a calm, trustworthy simulation workspace
- U2CHAT should feel like a premium research assistant workspace
- Shared visual language should be coherent across all three
- The public-facing business website should feel credible enough for sales, partnerships, and commercial trust-building

## 10. Feature and Function Advancement Roadmap

## 10.1 Academy advancements

- Use the existing `parent` field to model real lesson progression
- Add saved user progress and user-specific completion history
- Add rating submission UI and actual review summaries
- Add comment likes, reply likes, and moderation tooling
- Add search, category filters, difficulty filters, and completion filters
- Surface lesson source, instructor, and credibility context
- Add note-taking, bookmarks, highlights, and exportable study plans
- Add quizzes and assessments after lessons
- Add progress dashboards and learning streaks
- Make custom roadmap saveable and shareable

## 10.2 Trading Lab advancements

- Implement fully working chart time ranges
- Render transaction history in the dashboard
- Calculate live portfolio value from current quotes
- Show realized and unrealized P&L separately
- Add watchlists, alerts, and favorite stocks
- Add order types beyond immediate buy/sell
- Add slippage, fees, and tax simulation options
- Add risk metrics and portfolio allocation visuals
- Add contextual educational guidance during trading actions
- Add saved paper accounts and multiple simulation profiles
- Support richer data panels such as news, fundamentals, and peer comparison

## 10.3 U2CHAT advancements

- Stream responses progressively instead of returning one final blob
- Add backend-supported cancellation
- Surface tool execution trace and tool outputs
- Add citations and source cards for knowledge-base answers
- Add structured cards for quotes, fundamentals, and charts
- Add pinned conversations, search, rename, and foldering
- Add suggested prompts and follow-up actions
- Make recent sessions and history durable
- Add beginner/expert assistant modes
- Add portfolio-aware or watchlist-aware analysis once persistence exists

## 10.4 Data and platform advancements

- Unify Academy, Lab, and Chat persistence in one durable store
- Add proper user accounts and auth if the product goes beyond demo use
- Make vector-store refresh detect modified and deleted PDFs
- Move vector initialization away from blocking import-time startup where appropriate
- Add analytics and product telemetry
- Add a test suite for backend logic and core frontend flows
- Add config separation for dev/staging/prod
- Harden secret management and deployment defaults

## 10.5 Frontend architecture advancements

- Break the current monolith into reusable components or modular views
- Move styles and scripts into versioned static assets
- Introduce design tokens and a consistent component library
- Introduce cleaner state boundaries between Academy, Lab, and U2CHAT
- Add proper routing and deep links
- Add safer message rendering and sanitization strategy
- Add better chart wrappers and reusable data cards

## 10.6 Commercial website advancements

- Build a proper homepage with commercial messaging and conversion hierarchy
- Add product overview, about, contact, FAQ, and pricing/demo surfaces
- Add a professional footer with contact, social, legal, and support links
- Add lead capture forms with CRM or email routing
- Add testimonials, credibility markers, and product-proof sections
- Add resource/content marketing structure for SEO and inbound acquisition
- Add business-grade analytics and conversion tracking
- Add finance-specific public disclaimers and risk disclosures
- Add newsletter, waitlist, or demo-booking flows depending on go-to-market model
- Add support/help center and business inquiry routing

## 11. Recommended Rebuild Phases

### Phase 0: Truth-preserving inventory

- Freeze current scope
- Preserve all current product surfaces
- Map implemented, partial, latent, and broken features

### Phase 1: Design system and app shell

- Rebuild the global shell, navigation, typography, surfaces, and spacing system
- Rebuild both the commercial website shell and the product app shell
- Rebuild page layout structure for Academy, Lab, and U2CHAT
- Preserve current backend API contracts

### Phase 2: Feature completion

- Finish missing handlers
- Finish partial Lab panels
- Finish comment likes and ratings UI
- Finish deep links and route behavior
- Add public commercial pages and CTA flows

### Phase 3: Persistence and intelligence

- Unify persistence
- Add true streaming and tool/source display
- Make roadmap, chat, and paper portfolios durable

### Phase 4: Product maturity

- Add richer analysis features
- Add personalization
- Add moderation, analytics, and operational hardening
- Add business analytics, CRM integration, SEO content, and commercial operations support

## 12. Success Criteria for the Rebuild

The rebuild is successful if a user can:

- understand what U2INVEST is as a company/product before entering the app
- understand the three product pillars immediately
- move between Academy, Lab, and U2CHAT without cognitive friction
- use every currently visible control without hitting dead or partial functionality
- complete Academy learning flows and see trustworthy progress
- use the Lab as a coherent paper-trading workspace
- use U2CHAT as a believable research assistant with visible evidence and structure
- find contact, social, legal, and trust information easily
- submit a business inquiry, contact request, or demo request cleanly
- recover state more reliably across refreshes and restarts

The rebuild is especially successful if it preserves scope while making the product feel more premium, more coherent, and more maintainable than the current single-file implementation.

## 13. Highest-Priority Truths To Preserve

- U2INVEST is not only an AI chat app
- U2INVEST is not only an in-app product; it also needs a public commercial website layer
- The product is intentionally a three-part system: learn, practice, analyze
- The Academy, Lab, and U2CHAT should remain connected but distinct
- The rebuild should increase clarity and quality, not reduce functionality
- The current code already contains more product scope than the current UI communicates