+page.svelte 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <script>
  2. import CurrentPositionChart from '../../components/CurrentPositionChart.svelte';
  3. import { onMount } from 'svelte';
  4. import { authentication } from '../store.js';
  5. import { fade } from 'svelte/transition';
  6. import { goto } from '$app/navigation';
  7. import { getRequest } from '../../utils/api.js';
  8. let authToken;
  9. let data = {};
  10. let isLoading = true;
  11. let currency = 'USD';
  12. let total = 0;
  13. // Removed chartKey
  14. onMount(() => {
  15. return authentication.subscribe(async (auth) => {
  16. if (!auth || !auth.token) {
  17. await goto('/login');
  18. } else {
  19. authToken = auth.token;
  20. await fetchPortfolio();
  21. }
  22. });
  23. });
  24. async function fetchPortfolio() {
  25. try {
  26. const response = await getRequest(
  27. `${import.meta.env.VITE_STOCKS_HOST}/api/portfolios?currency=${currency}`,
  28. {},
  29. authToken
  30. );
  31. if (response.ok) {
  32. const portfolio = await response.json();
  33. if (portfolio?.length) {
  34. data = {
  35. ...portfolio[0],
  36. stocks: [...portfolio[0].stocks].sort((a, b) => a.total - b.total)
  37. };
  38. total = portfolio[0].totalValue;
  39. } else {
  40. data = {};
  41. total = 0;
  42. }
  43. } else {
  44. const error = await response.json();
  45. console.error('Failed to find portfolio info:', error);
  46. data = {};
  47. total = 0;
  48. }
  49. } catch (error) {
  50. console.error('Failed to fetch insights:', error);
  51. await goto('/logout');
  52. } finally {
  53. isLoading = false;
  54. }
  55. }
  56. function updateCurrency(event) {
  57. currency = event.target.value;
  58. isLoading = true;
  59. fetchPortfolio();
  60. }
  61. </script>
  62. <svelte:head>
  63. <title>Insights</title>
  64. <meta name="description" content="Insights" />
  65. </svelte:head>
  66. {#if isLoading}
  67. <div in:fade>Loading...</div>
  68. {:else}
  69. <div in:fade>
  70. <select class="form-control order-select" on:change={updateCurrency} value={currency}>
  71. <option value="BRL">BRL</option>
  72. <option value="EUR">EUR</option>
  73. <option value="USD" selected>USD</option>
  74. </select>
  75. <CurrentPositionChart {data} {currency} {total} />
  76. </div>
  77. {/if}