+page.svelte 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. <script>
  2. import { authentication } from '../store.js';
  3. import { onMount } from 'svelte';
  4. import { fade } from 'svelte/transition';
  5. let portfolioId = undefined;
  6. let result = [];
  7. let totalValue = 0;
  8. let totalAssets = 0;
  9. let authToken;
  10. let isLoading = true;
  11. let showModal = false;
  12. let searchStockResult = [];
  13. let orderBy = "total";
  14. onMount(() => {
  15. const unsubscribe = authentication.subscribe(value => {
  16. if (value?.token) {
  17. authToken = value.token;
  18. fetchPortfolio();
  19. }
  20. });
  21. return () => unsubscribe();
  22. });
  23. async function fetchPortfolio() {
  24. try {
  25. const response = await fetch(
  26. `${import.meta.env.VITE_STOCKS_HOST}/api/portfolios`,
  27. {
  28. method: 'GET',
  29. headers: {
  30. Authorization: 'Bearer ' + authToken
  31. }
  32. }
  33. );
  34. if (response.ok) {
  35. await update(response.json())
  36. } else {
  37. const error = await response.json();
  38. console.error('Failed to find portfolio info:', error);
  39. alert('Failed to find portfolio info: ' + error.message);
  40. }
  41. } catch (err) {
  42. console.error('Failed to find portfolio info', err);
  43. alert('Failed to find portfolio info');
  44. } finally {
  45. isLoading = false;
  46. }
  47. }
  48. async function update(response) {
  49. const portfolio = await response;
  50. if (portfolio?.length > 0) {
  51. if (orderBy === "code") {
  52. result = portfolio[0].stocks.sort((a, b) => a.code.localeCompare(b.code));
  53. }
  54. if (orderBy === "name") {
  55. result = portfolio[0].stocks.sort((a, b) => a.name.localeCompare(b.name));
  56. }
  57. if (orderBy === "total") {
  58. result = portfolio[0].stocks.sort((a, b) => a.total - b.total);
  59. }
  60. result = portfolio[0].stocks;
  61. totalValue = portfolio[0].totalValue;
  62. totalAssets = portfolio[0].totalAssets;
  63. portfolioId = portfolio[0].id;
  64. } else {
  65. await createNewPortfolio();
  66. }
  67. }
  68. async function createNewPortfolio() {
  69. try {
  70. const response = await fetch(`${import.meta.env.VITE_STOCKS_HOST}/api/portfolios`, {
  71. method: 'POST',
  72. headers: {
  73. Authorization: 'Bearer ' + authToken
  74. }
  75. });
  76. if (response.status === 400) {
  77. alert("Bad request. Invalid code.");
  78. return;
  79. }
  80. await fetchPortfolio();
  81. } catch (err) {
  82. console.error('Update failed', err);
  83. }
  84. }
  85. async function updatePortfolio(stocks) {
  86. try {
  87. const response = await fetch(`${import.meta.env.VITE_STOCKS_HOST}/api/portfolios/${portfolioId}`, {
  88. method: 'PUT',
  89. headers: {
  90. Authorization: 'Bearer ' + authToken,
  91. 'Content-Type': 'application/json'
  92. },
  93. body: JSON.stringify({stocks})
  94. });
  95. if (response.status === 400) {
  96. alert("Bad request. Invalid code.");
  97. return;
  98. }
  99. await fetchPortfolio();
  100. } catch (err) {
  101. console.error('Update failed', err);
  102. }
  103. }
  104. async function searchStock(code) {
  105. if (!code) return;
  106. try {
  107. const res = await fetch(`${import.meta.env.VITE_STOCKS_HOST}/api/stocks?q=${code}`);
  108. return await res.json();
  109. } catch (err) {
  110. console.error("Search error:", err);
  111. return [];
  112. }
  113. }
  114. async function handleSubmit(e) {
  115. e.preventDefault();
  116. const code = new FormData(e.target).get("stock_code").toUpperCase();
  117. const data = await searchStock(code);
  118. if (!data || data.length === 0) {
  119. alert("Stock not found.");
  120. return;
  121. }
  122. searchStockResult = data;
  123. const alreadyInPortfolio = result.some(s => s.code === data[0]?.code);
  124. if (data.length === 1 && !alreadyInPortfolio) {
  125. await addSelectedStock(data[0]);
  126. closeOrOpenModal();
  127. }
  128. }
  129. async function addSelectedStock(newStock) {
  130. const exists = result.some(stock => stock.code === newStock.code);
  131. if (exists) return;
  132. result = [
  133. ...result,
  134. {
  135. code: newStock.code,
  136. name: newStock.name,
  137. quantity: 0,
  138. price: newStock.price,
  139. total: 0,
  140. totalPercent: 0
  141. }
  142. ];
  143. closeOrOpenModal();
  144. await updatePortfolio(result);
  145. }
  146. function remove(code) {
  147. result = result.filter(stock => stock.code !== code);
  148. updatePortfolio(result);
  149. }
  150. function formatCurrency(value) {
  151. return value.toLocaleString('en-US', {
  152. style: 'currency',
  153. currency: 'USD'
  154. });
  155. }
  156. function calculatePercentage(part, total) {
  157. return total ? Math.floor((part / total) * 10000) / 100 : 0;
  158. }
  159. function updateStockQuantity(e) {
  160. e.preventDefault();
  161. const form = new FormData(e.target);
  162. const code = form.get("code");
  163. const quantity = parseInt(form.get("quantity")) || 0;
  164. result = result.map(stock =>
  165. stock.code === code ? {...stock, quantity} : stock
  166. );
  167. updatePortfolio(result);
  168. }
  169. function closeOrOpenModal() {
  170. searchStockResult = [];
  171. showModal = !showModal;
  172. }
  173. function updateOrderBy(event) {
  174. orderBy = event.target.value;
  175. fetchPortfolio()
  176. }
  177. </script>
  178. <svelte:head>
  179. <title>Stocks</title>
  180. <meta name="description" content="About"/>
  181. </svelte:head>
  182. {#if isLoading}
  183. <div in:fade>Loading...</div>
  184. {:else if portfolioId}
  185. <div class="button-container">
  186. <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#exampleModal" on:click={closeOrOpenModal}>Add</button>
  187. <!-- Dropdown for ordering the list -->
  188. <select class="form-control order-select" on:change={updateOrderBy}>
  189. <option value="code">Order by Code</option>
  190. <option value="name">Order by Name</option>
  191. <option value="total" selected>Order by Total</option>
  192. </select>
  193. </div>
  194. {#if showModal}
  195. <div class="modal-container">
  196. <div class="modal-content">
  197. <form on:submit|preventDefault={handleSubmit}>
  198. <div class="row">
  199. <div class="col">
  200. <input type="text" class="form-control" placeholder="stock code or name"
  201. name="stock_code"
  202. oninput="this.value = this.value.toUpperCase()"
  203. autocomplete="off" autofocus>
  204. </div>
  205. <div class="col">
  206. <input type="reset" value="cancel" class="btn btn-danger" on:click={closeOrOpenModal}/>
  207. <input type="submit" value="search" class="btn btn-primary"/>
  208. </div>
  209. </div>
  210. </form>
  211. {#if searchStockResult.length > 0}
  212. <div class="modal-result">
  213. <div class="card" style="width: 100%;">
  214. <ul class="list-group list-group-flush">
  215. {#each searchStockResult as result}
  216. <li class="list-group-item d-flex justify-content-between align-items-center"
  217. on:click={addSelectedStock(result)}>
  218. ({result.code}) {result.name}
  219. <button class="btn btn-primary btn-sm">+</button>
  220. </li>
  221. {/each}
  222. </ul>
  223. </div>
  224. </div>
  225. {/if}
  226. </div>
  227. </div>
  228. {/if}
  229. <div in:fade class="table-container">
  230. <table class="stock-table">
  231. <thead>
  232. <tr>
  233. <th>Total Value</th>
  234. <th>Total Assets</th>
  235. </tr>
  236. </thead>
  237. <tbody>
  238. <tr>
  239. <td class="code">{formatCurrency(totalValue)}</td>
  240. <td class="code">{totalAssets}</td>
  241. </tr>
  242. </tbody>
  243. </table>
  244. </div>
  245. <div in:fade class="table-container">
  246. <table class="stock-table">
  247. <thead>
  248. <tr>
  249. <th>Code</th>
  250. <th>Name</th>
  251. <th>Qty</th>
  252. <th>Price</th>
  253. <th>Total</th>
  254. <th>% of Portfolio</th>
  255. <th scope="col"></th>
  256. </tr>
  257. </thead>
  258. <tbody>
  259. {#each result as stock}
  260. <tr>
  261. <td class="code">{stock.code}</td>
  262. <td class="name">{stock.name}</td>
  263. <td class="qty-edit">
  264. <form id="updateQuantity" on:submit|preventDefault={updateStockQuantity}>
  265. <input type="hidden" name="code" value="{stock.code}"/>
  266. <input type="number" class="qty-input" name="quantity" value="{stock.quantity}"/>
  267. </form>
  268. </td>
  269. <td class="price">{formatCurrency(stock.price)}</td>
  270. <td class="total">{formatCurrency(stock.total)}</td>
  271. <td class="percent">{calculatePercentage(stock.total, totalValue)}%</td>
  272. <td>
  273. <button class="remove-btn" on:click={() => remove(stock.code)} title="remove"></button>
  274. </td>
  275. </tr>
  276. {/each}
  277. </tbody>
  278. </table>
  279. </div>
  280. {:else}
  281. <div>No portfolio data available.</div>
  282. {/if}
  283. <style>
  284. /* General Styles for Table (Unchanged) */
  285. .table-container {
  286. margin-top: 2rem;
  287. overflow-x: auto;
  288. border-radius: 12px;
  289. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  290. }
  291. .stock-table {
  292. width: 100%;
  293. border-collapse: collapse;
  294. font-family: system-ui, sans-serif;
  295. background-color: #fff;
  296. border-radius: 12px;
  297. overflow: hidden;
  298. min-width: 600px;
  299. }
  300. th, td {
  301. padding: 1rem 1.25rem;
  302. text-align: left;
  303. white-space: nowrap;
  304. }
  305. thead {
  306. background-color: #f7f7f7;
  307. border-bottom: 2px solid #e0e0e0;
  308. }
  309. th {
  310. font-weight: 600;
  311. font-size: 0.95rem;
  312. color: #333;
  313. }
  314. tbody tr:nth-child(odd) {
  315. background-color: #fafafa;
  316. }
  317. tbody tr:nth-child(even) {
  318. background-color: #f0f4f8;
  319. }
  320. tbody tr:hover {
  321. background-color: #e1ecf4;
  322. }
  323. td {
  324. font-size: 0.95rem;
  325. color: #555;
  326. border-bottom: 1px solid #eee;
  327. }
  328. .code {
  329. font-weight: 600;
  330. color: #2c3e50;
  331. }
  332. .name {
  333. color: #7f8c8d;
  334. }
  335. .qty-edit {
  336. display: flex;
  337. align-items: center;
  338. gap: 0.5rem;
  339. }
  340. .qty-input {
  341. width: 60px;
  342. padding: 0.4rem 0.5rem;
  343. font-size: 0.9rem;
  344. border: 1px solid #ccc;
  345. border-radius: 6px;
  346. text-align: right;
  347. background-color: #fff;
  348. color: #333;
  349. transition: border-color 0.2s ease;
  350. }
  351. .qty-input:focus {
  352. outline: none;
  353. border-color: #2980b9;
  354. }
  355. .remove-btn {
  356. height: 15px;
  357. width: 15px;
  358. background-color: #e74c3c;
  359. border-radius: 50%;
  360. display: inline-block;
  361. border: 0;
  362. }
  363. .price {
  364. color: #27ae60;
  365. font-weight: bold;
  366. }
  367. .total {
  368. font-weight: 500;
  369. color: #34495e;
  370. }
  371. .percent {
  372. color: #2980b9;
  373. }
  374. /* Responsive design */
  375. @media (max-width: 768px) {
  376. .modal-content {
  377. width: 90%;
  378. padding: 1.5rem;
  379. }
  380. input[type="text"],
  381. input[type="number"] {
  382. font-size: 0.9rem;
  383. }
  384. .modal-result {
  385. max-height: 200px;
  386. }
  387. .list-group-item {
  388. font-size: 0.9rem;
  389. }
  390. }
  391. @media (max-width: 768px) {
  392. .stock-table {
  393. font-size: 0.875rem;
  394. }
  395. th, td {
  396. padding: 0.75rem 1rem;
  397. }
  398. }
  399. /* Modal Styling */
  400. .modal-container {
  401. position: fixed;
  402. top: 20%;
  403. left: 0;
  404. right: 0;
  405. display: flex;
  406. justify-content: center;
  407. align-items: center;
  408. z-index: 9999;
  409. animation: fadeIn 0.3s ease;
  410. }
  411. /* Modal content styling */
  412. .modal-content {
  413. background-color: #fff;
  414. color: #333;
  415. width: 450px;
  416. height: auto;
  417. max-width: 500px;
  418. border-radius: 10px;
  419. padding: 2rem;
  420. box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  421. transition: transform 0.3s ease-in-out;
  422. }
  423. /* Button container for Add and Dropdown */
  424. .button-container {
  425. display: flex;
  426. gap: 10px;
  427. margin-bottom: 1rem;
  428. align-items: center;
  429. }
  430. .order-select {
  431. width: 200px;
  432. padding: 0.5rem;
  433. border-radius: 8px;
  434. border: 1px solid #ddd;
  435. font-size: 1rem;
  436. background-color: #f9f9f9;
  437. transition: border-color 0.3s ease;
  438. }
  439. .order-select:focus {
  440. border-color: #2980b9;
  441. outline: none;
  442. }
  443. /* Input Fields (Stock code and search) */
  444. input[type="text"], input[type="number"] {
  445. width: 100%;
  446. padding: 0.8rem;
  447. font-size: 1rem;
  448. border-radius: 8px;
  449. border: 1px solid #ddd;
  450. margin-bottom: 10px;
  451. background-color: #f9f9f9;
  452. color: #333;
  453. transition: border-color 0.3s ease;
  454. }
  455. input[type="text"]:focus, input[type="number"]:focus {
  456. border-color: #2980b9;
  457. outline: none;
  458. }
  459. /* Button styles */
  460. .btn {
  461. padding: 0.6rem 1.2rem;
  462. font-size: 1rem;
  463. border-radius: 8px;
  464. border: none;
  465. cursor: pointer;
  466. transition: background-color 0.3s ease;
  467. }
  468. .btn-primary {
  469. background-color: #2980b9;
  470. color: white;
  471. }
  472. .btn-primary:hover {
  473. background-color: #3498db;
  474. }
  475. .btn-danger {
  476. background-color: #e74c3c;
  477. color: white;
  478. }
  479. .btn-danger:hover {
  480. background-color: #c0392b;
  481. }
  482. /* Reset Button (Modal) */
  483. input[type="reset"] {
  484. background-color: #e74c3c;
  485. color: white;
  486. font-size: 1rem;
  487. padding: 0.6rem 1.2rem;
  488. border-radius: 8px;
  489. cursor: pointer;
  490. border: none;
  491. }
  492. /* Modal result items */
  493. .modal-result {
  494. max-width: 100%;
  495. max-height: 300px;
  496. overflow-y: auto;
  497. padding: 0.8rem;
  498. background-color: #fafafa;
  499. border-radius: 10px;
  500. margin-top: 1rem;
  501. }
  502. .list-group-item {
  503. display: flex;
  504. justify-content: space-between;
  505. align-items: center;
  506. padding: 10px;
  507. border: 1px solid #ddd;
  508. margin-bottom: 0.5rem;
  509. border-radius: 8px;
  510. background-color: #f9f9f9;
  511. transition: background-color 0.3s ease;
  512. }
  513. .list-group-item:hover {
  514. background-color: #f1f1f1;
  515. }
  516. .list-group-item .btn-primary {
  517. background-color: #2980b9;
  518. color: white;
  519. border-radius: 50%;
  520. height: 30px;
  521. width: 30px;
  522. padding: 0;
  523. border: none;
  524. }
  525. .list-group-item .btn-primary:hover {
  526. background-color: #3498db;
  527. }
  528. /* Modal transition */
  529. @keyframes fadeIn {
  530. from {
  531. opacity: 0;
  532. }
  533. to {
  534. opacity: 1;
  535. }
  536. }
  537. </style>