clean redundant api endpoints

This commit is contained in:
MuslemRahimi 2024-11-18 22:01:48 +01:00
parent 7eb2a1b4c0
commit 7a4033a597
15 changed files with 370 additions and 572 deletions

View File

@ -44,7 +44,7 @@
}; };
// Make the POST request to the endpoint // Make the POST request to the endpoint
const response = await fetch("/api/fastify-post-data", { const response = await fetch("/api/create-price-alert", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -52,7 +52,7 @@
body: JSON.stringify(postData), body: JSON.stringify(postData),
}); });
const output = (await response.json())?.items; const output = await response.json();
if (output === "success") { if (output === "success") {
toast.success(`Successfully created price alert`, { toast.success(`Successfully created price alert`, {

View File

@ -1,66 +0,0 @@
import type { RequestHandler } from "./$types";
function secondsUntilEndOfDay() {
const now = new Date();
const endOfDay = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() + 1,
);
const secondsUntilEndOfDay = (endOfDay - now) / 1000;
return secondsUntilEndOfDay;
}
export const POST = (async ({ request, cookies, locals }) => {
let output = "error";
const data = await request.json();
const sentiment = data?.sentiment;
const ticker = data?.ticker;
const sentimentId = data?.sentimentId;
const maxAge = secondsUntilEndOfDay();
let newData;
if (cookies?.get("community-sentiment-" + ticker)) {
//console.log('already voted')
return new Response(JSON.stringify(output));
} else {
try {
if (sentimentId) {
if (sentiment === "upvote") {
await locals?.pb
?.collection("sentiment")
.update(sentimentId, { "upvote+": 1 });
} else if (sentiment === "downvote") {
await locals?.pb
?.collection("sentiment")
.update(sentimentId, { "downvote+": 1 });
}
} else {
if (sentiment === "upvote") {
newData = await locals?.pb
?.collection("sentiment")
.create({ ticker: ticker, upvote: 1 });
} else if (sentiment === "downvote") {
newData = await locals?.pb
?.collection("sentiment")
.create({ ticker: ticker, downvote: 1 });
}
}
output = "success";
cookies.set("community-sentiment-" + ticker, sentiment, {
httpOnly: true,
sameSite: "lax",
secure: true,
path: "/",
maxAge: maxAge, // End of day expiry
});
} catch (e) {
console.log(e);
}
}
return new Response(JSON.stringify(output));
}) satisfies RequestHandler;

View File

@ -1,189 +0,0 @@
import type { RequestHandler } from "./$types";
import { serialize } from "object-to-formdata";
import { validateData } from "$lib/utils";
import {
createCommentTextSchema,
createCommentImageSchema,
} from "$lib/schemas";
import { error } from "@sveltejs/kit";
//import sharp from 'sharp';
//import { marked } from 'marked';
/*
export const config = {
runtime: 'nodejs20.x',
};
*/
/*
function removeDuplicateClasses(str) {
return str.replace(/class="([^"]*)"/g, (match, classAttr) => {
return `class="${[...new Set(classAttr.split(' '))].join(' ')}"`;
});
}
function addClassesToHtml(htmlString) {
// Helper function to add a class to a specific tag
function addClassToTag(tag, className) {
// Add class if the tag doesn't already have a class attribute
const regex = new RegExp(`<${tag}(?![^>]*\\bclass=)([^>]*)>`, 'g');
htmlString = htmlString.replace(regex, `<${tag} class="${className}"$1>`);
// Append the new class to tags that already have a class attribute, ensuring no duplicates
const regexWithClass = new RegExp(`(<${tag}[^>]*\\bclass=["'][^"']*)(?!.*\\b${className}\\b)([^"']*)["']`, 'g');
htmlString = htmlString.replace(regexWithClass, `$1 ${className}$2"`);
}
// Add classes to headings
addClassToTag('h1', 'text-lg');
addClassToTag('h2', 'text-lg');
addClassToTag('h3', 'text-lg');
addClassToTag('h4', 'text-lg');
addClassToTag('h5', 'text-lg');
addClassToTag('h6', 'text-lg');
// Add classes to anchor tags
addClassToTag('a', 'text-blue-400 hover:text-white underline');
// Add classes to ordered lists
addClassToTag('ol', 'list-decimal ml-10 text-sm');
// Add classes to unordered lists
addClassToTag('ul', 'list-disc ml-10 text-sm -mt-5');
// Add classes to blockquotes and their paragraphs
function addClassToBlockquote() {
// Add class to blockquote
htmlString = htmlString.replace(
/<blockquote/g,
'<blockquote class="pl-4 pr-4 rounded-lg bg-[#323232]"'
);
// Add class to p inside blockquote
htmlString = htmlString.replace(
/<blockquote([^>]*)>\s*<p/g,
`<blockquote$1>\n<p class="text-sm font-medium leading-relaxed text-white"`
);
}
addClassToBlockquote();
// Remove duplicate classes after all modifications
htmlString = removeDuplicateClasses(htmlString);
return htmlString;
}
*/
export const POST = (async ({ request, locals }) => {
let output = "error";
const body = await request.formData();
if (body?.get("comment") === "undefined") {
body?.delete("comment");
body?.append("comment", "");
}
if (body?.get("reply") === null) {
body?.delete("reply");
body?.append("reply", "");
}
const { formData, errors } = await validateData(
body,
body?.get("image")?.length === 0
? createCommentTextSchema
: createCommentImageSchema,
);
if (errors) {
return new Response(JSON.stringify(output));
}
//formData.comment = addClassesToHtml(marked(formData?.comment))
/*
if (formData?.image?.type?.includes('image'))
{
try {
// image optimization before storing into the database
const image = formData?.image;
const imageBuffer = await image?.arrayBuffer();
const imageBufferArray = new Uint8Array(imageBuffer);
const optimizedImageBuffer = await sharp(imageBufferArray)
.resize({
width: 800,
height: 1000,
fit: sharp.fit.inside, // Maintain aspect ratio and fit within the specified dimensions
withoutEnlargement: true, // Do not upscale the image if it's smaller than the specified dimensions
})
.jpeg({ quality: 50 }) // Example: Convert the image to JPEG format with 50% quality
.toBuffer();
formData.image = new File([optimizedImageBuffer], image.name, {
type: image.type,
lastModified: image.lastModified,
});
} catch(err) {
console.log('Error: ', err);
error(err.status, err.message);
}
}
*/
//Each comment gives the user +1 Karma points
await locals.pb.collection("users").update(locals?.user?.id, {
"karma+": 1,
});
let newComment;
try {
newComment = await locals.pb
.collection("comments")
.create(serialize(formData), {
expand: "user,alreadyVoted(comment)",
fields:
"*,expand.user,expand.alreadyVoted(comment).user,expand.alreadyVoted(comment).type",
});
let postId = formData.post;
const opPost = await locals.pb.collection("posts").getOne(postId);
//create new record for notifications collections
if (locals?.user?.id !== opPost?.user) {
let formDataNotifications = new FormData();
formDataNotifications.append("opUser", opPost?.user);
formDataNotifications.append("user", formData?.user);
formDataNotifications.append("post", postId);
formDataNotifications.append("comment", newComment?.id);
formDataNotifications.append("notifyType", "comment");
await locals.pb.collection("notifications").create(formDataNotifications);
}
let formDataAlreadyVoted = new FormData();
formDataAlreadyVoted.append("comment", newComment?.id);
formDataAlreadyVoted.append("user", newComment?.user);
formDataAlreadyVoted.append("type", "upvote");
//console.log(formDataAlreadyVoted)
await locals.pb.collection("alreadyVoted").create(formDataAlreadyVoted);
//User always upvotes their comment in the intial state
await locals.pb.collection("comments").update(newComment?.id, {
"upvote+": 1,
});
output = "success";
} catch (err) {
console.log("Error: ", err);
error(err.status, err.message);
}
return new Response(JSON.stringify([output, newComment]));
}) satisfies RequestHandler;

View File

@ -0,0 +1,31 @@
import type { RequestHandler } from "./$types";
export const POST: RequestHandler = async ({ request, locals }) => {
const { pb } = locals;
const data = await request.json();
let output;
let newAlert = {
'user': data['userId'],
'symbol': data['symbol']?.toUpperCase(),
'name': data['name'],
'assetType': data['assetType']?.toLowerCase(),
'targetPrice': Number(data['targetPrice']),
'condition': data['condition']?.toLowerCase(),
'priceWhenCreated': Number(data['priceWhenCreated']),
'triggered': false,
}
try {
await pb.collection("priceAlert")?.create(newAlert)
output = 'success';
} catch (err) {
output = 'failure'
}
return new Response(JSON.stringify(output));
};

View File

@ -0,0 +1,17 @@
import type { RequestHandler } from "./$types";
export const POST: RequestHandler = async ({ request, locals }) => {
const { pb } = locals;
const data = await request.json();
let output;
try {
output = await pb.collection("stockscreener").create(data)
}
catch(e) {
output = {};
}
return new Response(JSON.stringify(output));
};

View File

@ -0,0 +1,24 @@
import type { RequestHandler } from "./$types";
export const POST = (async ({ request, locals }) => {
const { pb } = locals;
const data = await request.json();
const priceAlertIdList = data?.priceAlertIdList;
let output;
try {
for (const item of priceAlertIdList) {
await pb.collection("priceAlert")?.delete(item)
}
output = 'success';
}
catch(e) {
//console.log(e)
output = 'failure';
}
return new Response(JSON.stringify(output));
}) satisfies RequestHandler;

View File

@ -0,0 +1,20 @@
import type { RequestHandler } from "./$types";
export const POST = (async ({ request, locals }) => {
const { pb } = locals;
const data = await request.json();
let output;
try {
await pb.collection("stockscreener")?.delete(data?.strategyId)
output = 'success';
}
catch(e) {
output = 'failure';
}
return new Response(JSON.stringify(output));
}) satisfies RequestHandler;

View File

@ -0,0 +1,29 @@
// Declare a route
module.exports = function (fastify, opts, done) {
const pb = opts.pb;
fastify.post('/edit-name-watchlist', async (request, reply) => {
const data = request.body;
const watchListId = data?.watchListId;
const newTitle = data?.title;
let output;
try {
await pb.collection("watchlist").update(watchListId, {
'title': newTitle
})
output = 'success';
}
catch(e) {
//console.log(e)
output = 'failure';
}
reply.send({ items: output })
});
done();
};

View File

@ -1,21 +0,0 @@
import type { RequestHandler } from "./$types";
export const POST: RequestHandler = async ({ request, locals }) => {
const data = await request.json();
const { fastifyURL } = locals;
// Destructure 'path' from data and collect the rest
const { path, ...restData } = data;
const response = await fetch(`${fastifyURL}/${path}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
// Pass the rest of the data (excluding path) in the body
body: JSON.stringify(restData),
});
const output = await response.json();
return new Response(JSON.stringify(output));
};

View File

@ -1,18 +0,0 @@
import type { RequestHandler } from "./$types";
export const POST: RequestHandler = async ({ request, locals }) => {
const data = await request.json();
const { fastifyURL } = locals;
const response = await fetch(fastifyURL + "/get-one-post", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
const output = await response.json();
return new Response(JSON.stringify(output));
};

View File

@ -1,18 +0,0 @@
import type { RequestHandler } from "./$types";
export const POST: RequestHandler = async ({ request, locals }) => {
const data = await request.json();
const { fastifyURL } = locals;
const response = await fetch(fastifyURL + "/get-post", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
const output = await response.json();
return new Response(JSON.stringify(output));
};

View File

@ -0,0 +1,21 @@
import type { RequestHandler } from "./$types";
export const POST = (async ({ request, locals }) => {
const { pb } = locals;
const data = await request.json();
let output;
try {
output = await pb.collection("stockscreener").update(data?.strategyId, {
'rules': data?.rules
})
}
catch(e) {
output = {};
}
return new Response(JSON.stringify(output));
}) satisfies RequestHandler;

View File

@ -7,7 +7,6 @@
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { screenWidth } from "$lib/store"; import { screenWidth } from "$lib/store";
import MiniPlot from "$lib/components/MiniPlot.svelte"; import MiniPlot from "$lib/components/MiniPlot.svelte";
import { onMount } from "svelte";
import ArrowLogo from "lucide-svelte/icons/move-up-right"; import ArrowLogo from "lucide-svelte/icons/move-up-right";
export let data; export let data;
@ -133,7 +132,6 @@
}, },
); );
let isLoaded = false;
let priceAlertList = data?.getPriceAlert; let priceAlertList = data?.getPriceAlert;
function stockSelector(symbol, assetType) { function stockSelector(symbol, assetType) {
@ -175,10 +173,9 @@
const postData = { const postData = {
priceAlertIdList: deletePriceAlertList, priceAlertIdList: deletePriceAlertList,
path: "delete-price-alert",
}; };
const response = await fetch("/api/fastify-post-data", { const response = await fetch("/api/delete-price-alert", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -191,10 +188,6 @@
} }
} }
onMount(async () => {
isLoaded = true;
});
$: charNumber = $screenWidth < 640 ? 15 : 40; $: charNumber = $screenWidth < 640 ? 15 : 40;
</script> </script>
@ -251,249 +244,232 @@
</h1> </h1>
</div> </div>
{#if isLoaded} <div class="sm:hidden">
<div class="sm:hidden"> <div class="text-white text-xs sm:text-sm pb-5 sm:pb-2">
<div class="text-white text-xs sm:text-sm pb-5 sm:pb-2"> Stock Indexes - {getCurrentDateFormatted()}
Stock Indexes - {getCurrentDateFormatted()}
</div>
<div
class="w-full -mt-4 sm:mt-0 mb-8 m-auto flex justify-start sm:justify-center items-center"
>
<div
class="w-full grid grid-cols-2 md:grid-cols-4 gap-y-3 lg:gap-y-0 gap-x-3"
>
<MiniPlot
title="S&P500"
priceData={priceDataSP500}
changesPercentage={changeSP500}
previousClose={previousCloseSP500}
/>
<MiniPlot
title="Nasdaq"
priceData={priceDataNasdaq}
changesPercentage={changeNasdaq}
previousClose={previousCloseNasdaq}
/>
<MiniPlot
title="Dow"
priceData={priceDataDowJones}
changesPercentage={changeDowJones}
previousClose={previousCloseDowJones}
/>
<MiniPlot
title="Russel"
priceData={priceDataRussel2000}
changesPercentage={changeRussel2000}
previousClose={previousCloseRussel2000}
/>
</div>
</div>
</div> </div>
{#if priceAlertList?.length === 0} <div
class="w-full -mt-4 sm:mt-0 mb-8 m-auto flex justify-start sm:justify-center items-center"
>
<div <div
class="flex flex-col justify-center items-center m-auto pt-8" class="w-full grid grid-cols-2 md:grid-cols-4 gap-y-3 lg:gap-y-0 gap-x-3"
> >
<span <MiniPlot
class="text-white font-bold text-white text-xl sm:text-3xl" title="S&P500"
> priceData={priceDataSP500}
No Alerts set changesPercentage={changeSP500}
</span> previousClose={previousCloseSP500}
/>
<span <MiniPlot
class="text-white text-sm sm:text-[1rem] m-auto p-4 text-center" title="Nasdaq"
> priceData={priceDataNasdaq}
Create price alerts for your stocks that have the most changesPercentage={changeNasdaq}
potential in your opinion. previousClose={previousCloseNasdaq}
</span> />
{#if !data?.user} <MiniPlot
<a title="Dow"
class="w-64 flex mt-10 justify-center items-center m-auto btn text-white bg-[#fff] sm:hover:bg-gray-300 transition duration-150 ease-in-out group" priceData={priceDataDowJones}
href="/register" changesPercentage={changeDowJones}
> previousClose={previousCloseDowJones}
Get Started />
<span <MiniPlot
class="tracking-normal group-hover:translate-x-0.5 transition-transform duration-150 ease-in-out" title="Russel"
> priceData={priceDataRussel2000}
<svg changesPercentage={changeRussel2000}
class="w-4 h-4" previousClose={previousCloseRussel2000}
xmlns="http://www.w3.org/2000/svg" />
viewBox="0 0 24 24"
><g transform="rotate(90 12 12)"
><g fill="none"
><path
d="M24 0v24H0V0h24ZM12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035c-.01-.004-.019-.001-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427c-.002-.01-.009-.017-.017-.018Zm.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093c.012.004.023 0 .029-.008l.004-.014l-.034-.614c-.003-.012-.01-.02-.02-.022Zm-.715.002a.023.023 0 0 0-.027.006l-.006.014l-.034.614c0 .012.007.02.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01l-.184-.092Z"
/><path
fill="white"
d="M13.06 3.283a1.5 1.5 0 0 0-2.12 0L5.281 8.939a1.5 1.5 0 0 0 2.122 2.122L10.5 7.965V19.5a1.5 1.5 0 0 0 3 0V7.965l3.096 3.096a1.5 1.5 0 1 0 2.122-2.122L13.06 3.283Z"
/></g
></g
></svg
>
</span>
</a>
{/if}
</div> </div>
{:else} </div>
<div class="flex flex-row justify-end items-center pb-2"> </div>
{#if editMode}
<label {#if priceAlertList?.length === 0}
on:click={handleDelete} <div class="flex flex-col justify-center items-center m-auto pt-8">
class="border text-sm border-gray-600 ml-3 cursor-pointer inline-flex items-center justify-center space-x-1 whitespace-nowrap rounded-md py-2 pl-3 pr-4 font-semibold text-white shadow-sm bg-[#09090B] sm:hover:bg-[#09090B]/60 ease-out" <span class="text-white font-bold text-white text-xl sm:text-3xl">
No Alerts set
</span>
<span
class="text-white text-sm sm:text-[1rem] m-auto p-4 text-center"
>
Create price alerts for your stocks that have the most potential
in your opinion.
</span>
{#if !data?.user}
<a
class="w-64 flex mt-10 justify-center items-center m-auto btn text-white bg-[#fff] sm:hover:bg-gray-300 transition duration-150 ease-in-out group"
href="/register"
>
Get Started
<span
class="tracking-normal group-hover:translate-x-0.5 transition-transform duration-150 ease-in-out"
> >
<svg <svg
class="inline-block w-5 h-5" class="w-4 h-4"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24" viewBox="0 0 24 24"
><path ><g transform="rotate(90 12 12)"
fill="white" ><g fill="none"
d="M10 5h4a2 2 0 1 0-4 0M8.5 5a3.5 3.5 0 1 1 7 0h5.75a.75.75 0 0 1 0 1.5h-1.32l-1.17 12.111A3.75 3.75 0 0 1 15.026 22H8.974a3.75 3.75 0 0 1-3.733-3.389L4.07 6.5H2.75a.75.75 0 0 1 0-1.5zm2 4.75a.75.75 0 0 0-1.5 0v7.5a.75.75 0 0 0 1.5 0zM14.25 9a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75m-7.516 9.467a2.25 2.25 0 0 0 2.24 2.033h6.052a2.25 2.25 0 0 0 2.24-2.033L18.424 6.5H5.576z" ><path
/></svg d="M24 0v24H0V0h24ZM12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035c-.01-.004-.019-.001-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427c-.002-.01-.009-.017-.017-.018Zm.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093c.012.004.023 0 .029-.008l.004-.014l-.034-.614c-.003-.012-.01-.02-.02-.022Zm-.715.002a.023.023 0 0 0-.027.006l-.006.014l-.034.614c0 .012.007.02.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01l-.184-.092Z"
/><path
fill="white"
d="M13.06 3.283a1.5 1.5 0 0 0-2.12 0L5.281 8.939a1.5 1.5 0 0 0 2.122 2.122L10.5 7.965V19.5a1.5 1.5 0 0 0 3 0V7.965l3.096 3.096a1.5 1.5 0 1 0 2.122-2.122L13.06 3.283Z"
/></g
></g
></svg
> >
<span class="ml-1 text-white text-sm"> </span>
{numberOfChecked} </a>
</span> {/if}
</label> </div>
{/if} {:else}
<div class="flex flex-row justify-end items-center pb-2">
{#if editMode}
<label <label
on:click={() => (editMode = !editMode)} on:click={handleDelete}
class="border text-sm border-gray-600 ml-3 cursor-pointer inline-flex items-center justify-center space-x-1 whitespace-nowrap rounded-md py-2 pl-3 pr-4 font-semibold text-white shadow-sm bg-[#09090B] sm:hover:bg-[#09090B]/60 ease-out" class="border text-sm border-gray-600 ml-3 cursor-pointer inline-flex items-center justify-center space-x-1 whitespace-nowrap rounded-md py-2 pl-3 pr-4 font-semibold text-white shadow-sm bg-[#09090B] sm:hover:bg-[#09090B]/60 ease-out"
> >
<svg <svg
class="inline-block w-5 h-5" class="inline-block w-5 h-5"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1024 1024" viewBox="0 0 24 24"
><path ><path
fill="white" fill="white"
d="M832 512a32 32 0 1 1 64 0v352a32 32 0 0 1-32 32H160a32 32 0 0 1-32-32V160a32 32 0 0 1 32-32h352a32 32 0 0 1 0 64H192v640h640z" d="M10 5h4a2 2 0 1 0-4 0M8.5 5a3.5 3.5 0 1 1 7 0h5.75a.75.75 0 0 1 0 1.5h-1.32l-1.17 12.111A3.75 3.75 0 0 1 15.026 22H8.974a3.75 3.75 0 0 1-3.733-3.389L4.07 6.5H2.75a.75.75 0 0 1 0-1.5zm2 4.75a.75.75 0 0 0-1.5 0v7.5a.75.75 0 0 0 1.5 0zM14.25 9a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75m-7.516 9.467a2.25 2.25 0 0 0 2.24 2.033h6.052a2.25 2.25 0 0 0 2.24-2.033L18.424 6.5H5.576z"
/><path
fill="white"
d="m469.952 554.24l52.8-7.552L847.104 222.4a32 32 0 1 0-45.248-45.248L477.44 501.44l-7.552 52.8zm422.4-422.4a96 96 0 0 1 0 135.808l-331.84 331.84a32 32 0 0 1-18.112 9.088L436.8 623.68a32 32 0 0 1-36.224-36.224l15.104-105.6a32 32 0 0 1 9.024-18.112l331.904-331.84a96 96 0 0 1 135.744 0z"
/></svg /></svg
> >
{#if !editMode} <span class="ml-1 text-white text-sm">
<span class="ml-1 text-white text-sm"> Edit </span> {numberOfChecked}
{:else} </span>
<span class="ml-1 text-white text-sm"> Cancel </span>
{/if}
</label> </label>
</div> {/if}
<!--Start Table--> <label
<div on:click={() => (editMode = !editMode)}
class="w-full rounded-lg overflow-hidden overflow-x-scroll no-scrollbar" class="border text-sm border-gray-600 ml-3 cursor-pointer inline-flex items-center justify-center space-x-1 whitespace-nowrap rounded-md py-2 pl-3 pr-4 font-semibold text-white shadow-sm bg-[#09090B] sm:hover:bg-[#09090B]/60 ease-out"
> >
<table <svg
class="table table-sm table-compact rounded-none sm:rounded-md w-full bg-[#09090B] border-bg-[#09090B] m-auto mt-4" class="inline-block w-5 h-5"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1024 1024"
><path
fill="white"
d="M832 512a32 32 0 1 1 64 0v352a32 32 0 0 1-32 32H160a32 32 0 0 1-32-32V160a32 32 0 0 1 32-32h352a32 32 0 0 1 0 64H192v640h640z"
/><path
fill="white"
d="m469.952 554.24l52.8-7.552L847.104 222.4a32 32 0 1 0-45.248-45.248L477.44 501.44l-7.552 52.8zm422.4-422.4a96 96 0 0 1 0 135.808l-331.84 331.84a32 32 0 0 1-18.112 9.088L436.8 623.68a32 32 0 0 1-36.224-36.224l15.104-105.6a32 32 0 0 1 9.024-18.112l331.904-331.84a96 96 0 0 1 135.744 0z"
/></svg
> >
<!-- head --> {#if !editMode}
<thead> <span class="ml-1 text-white text-sm"> Edit </span>
<tr class=""> {:else}
<th class="text-white font-semibold text-sm">Symbol</th> <span class="ml-1 text-white text-sm"> Cancel </span>
<th class="text-white font-semibold text-sm">Company</th> {/if}
<th class="text-white font-semibold text-end text-sm" </label>
>Volume</th
>
<th class="text-white font-semibold text-end text-sm"
>Price when Created</th
>
<th class="text-white font-semibold text-end text-sm"
>Price Target</th
>
<th class="text-white font-semibold text-end text-sm"
>Current Price</th
>
<th class="text-white font-semibold text-end text-sm"
>Change</th
>
</tr>
</thead>
<tbody class="p-3">
{#each priceAlertList as item, index}
<!-- row -->
<tr
on:click={() =>
stockSelector(item?.symbol, item?.assetType)}
class="sm:hover:bg-[#245073] sm:hover:bg-opacity-[0.2] odd:bg-[#27272A] border-b-[#09090B] cursor-pointer"
>
<td
on:click={() => handleFilter(item?.id)}
class="text-blue-400 font-medium text-sm sm:text-[1rem] whitespace-nowrap text-start border-b-[#09090B] flex flex-row items-center"
>
<input
type="checkbox"
checked={deletePriceAlertList?.includes(item?.id) ??
false}
class="{!editMode
? 'hidden'
: ''} bg-[#2E3238] h-[18px] w-[18px] rounded-sm ring-offset-0 mr-3"
/>
{item?.symbol}
</td>
<td
on:click={() => handleFilter(item?.id)}
class="text-white text-sm sm:text-[1rem] whitespace-nowrap border-b-[#09090B]"
>
{item?.name?.length > charNumber
? item?.name?.slice(0, charNumber) + "..."
: item?.name}
</td>
<td
class="text-white font-medium text-sm sm:text-[1rem] whitespace-nowrap text-end border-b-[#09090B]"
>
{abbreviateNumber(item?.volume)}
</td>
<td
class="text-white font-medium text-sm sm:text-[1rem] whitespace-nowrap text-end border-b-[#09090B]"
>
{item?.priceWhenCreated}
</td>
<td
class="text-white font-medium text-sm sm:text-[1rem] whitespace-nowrap text-end border-b-[#09090B]"
>
{item?.targetPrice}
</td>
<td
class="text-white font-medium text-sm sm:text-[1rem] whitespace-nowrap text-end border-b-[#09090B]"
>
{item.price?.toFixed(2)}
</td>
<td
class="text-white font-medium text-sm sm:text-[1rem] whitespace-nowrap text-end border-b-[#09090B]"
>
{#if item?.changesPercentage >= 0}
<span class="text-[#00FC50]"
>+{item?.changesPercentage?.toFixed(2)}%</span
>
{:else}
<span class="text-[#FF2F1F]"
>{item?.changesPercentage?.toFixed(2)}%
</span>
{/if}
</td>
</tr>
{/each}
</tbody>
</table>
</div>
<!--End Table-->
{/if}
{:else}
<div class="flex justify-center items-center h-80">
<div class="relative">
<label
class="bg-[#09090B] rounded-xl h-14 w-14 flex justify-center items-center absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2"
>
<span class="loading loading-spinner loading-md text-gray-400"
></span>
</label>
</div>
</div> </div>
<!--Start Table-->
<div
class="w-full rounded-lg overflow-hidden overflow-x-scroll no-scrollbar"
>
<table
class="table table-sm table-compact rounded-none sm:rounded-md w-full bg-[#09090B] border-bg-[#09090B] m-auto mt-4"
>
<!-- head -->
<thead>
<tr class="">
<th class="text-white font-semibold text-sm">Symbol</th>
<th class="text-white font-semibold text-sm">Company</th>
<th class="text-white font-semibold text-end text-sm"
>Volume</th
>
<th class="text-white font-semibold text-end text-sm"
>Price when Created</th
>
<th class="text-white font-semibold text-end text-sm"
>Price Target</th
>
<th class="text-white font-semibold text-end text-sm"
>Current Price</th
>
<th class="text-white font-semibold text-end text-sm"
>Change</th
>
</tr>
</thead>
<tbody class="p-3">
{#each priceAlertList as item, index}
<!-- row -->
<tr
on:click={() =>
stockSelector(item?.symbol, item?.assetType)}
class="sm:hover:bg-[#245073] sm:hover:bg-opacity-[0.2] odd:bg-[#27272A] border-b-[#09090B] cursor-pointer"
>
<td
on:click={() => handleFilter(item?.id)}
class="text-blue-400 font-medium text-sm sm:text-[1rem] whitespace-nowrap text-start border-b-[#09090B] flex flex-row items-center"
>
<input
type="checkbox"
checked={deletePriceAlertList?.includes(item?.id) ??
false}
class="{!editMode
? 'hidden'
: ''} bg-[#2E3238] h-[18px] w-[18px] rounded-sm ring-offset-0 mr-3"
/>
{item?.symbol}
</td>
<td
on:click={() => handleFilter(item?.id)}
class="text-white text-sm sm:text-[1rem] whitespace-nowrap border-b-[#09090B]"
>
{item?.name?.length > charNumber
? item?.name?.slice(0, charNumber) + "..."
: item?.name}
</td>
<td
class="text-white font-medium text-sm sm:text-[1rem] whitespace-nowrap text-end border-b-[#09090B]"
>
{abbreviateNumber(item?.volume)}
</td>
<td
class="text-white font-medium text-sm sm:text-[1rem] whitespace-nowrap text-end border-b-[#09090B]"
>
{item?.priceWhenCreated}
</td>
<td
class="text-white font-medium text-sm sm:text-[1rem] whitespace-nowrap text-end border-b-[#09090B]"
>
{item?.targetPrice}
</td>
<td
class="text-white font-medium text-sm sm:text-[1rem] whitespace-nowrap text-end border-b-[#09090B]"
>
{item.price?.toFixed(2)}
</td>
<td
class="text-white font-medium text-sm sm:text-[1rem] whitespace-nowrap text-end border-b-[#09090B]"
>
{#if item?.changesPercentage >= 0}
<span class="text-[#00FC50]"
>+{item?.changesPercentage?.toFixed(2)}%</span
>
{:else}
<span class="text-[#FF2F1F]"
>{item?.changesPercentage?.toFixed(2)}%
</span>
{/if}
</td>
</tr>
{/each}
</tbody>
</table>
</div>
<!--End Table-->
{/if} {/if}
</main> </main>

View File

@ -28,21 +28,23 @@ const ensureAllEmaParameters = (params) => {
}; };
export const load = async ({ locals }) => { export const load = async ({ locals }) => {
const { apiURL, apiKey, fastifyURL, user } = locals; const { apiURL, apiKey, user, pb } = locals;
const getAllStrategies = async () => { const getAllStrategies = async () => {
const postData = { userId: user?.id }; let output = [];
const response = await fetch(fastifyURL + "/all-strategies", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(postData),
});
const output = (await response.json())?.items; try {
output = await pb.collection("stockscreener").getFullList({
filter: `user="${user?.id}"`,
});
output?.sort((a, b) => new Date(b?.updated) - new Date(a?.updated));
output?.sort((a, b) => new Date(b?.updated) - new Date(a?.updated)); }
catch(e) {
output = [];
}
return output; return output;
}; };

View File

@ -1305,7 +1305,7 @@
} }
async function handleCreateStrategy() { async function handleCreateStrategy() {
if (data?.user?.tier === "Pro" && !data?.user?.freeTrial) { if (data?.user?.tier === "Pro") {
const closePopup = document.getElementById("addStrategy"); const closePopup = document.getElementById("addStrategy");
closePopup?.dispatchEvent(new MouseEvent("click")); closePopup?.dispatchEvent(new MouseEvent("click"));
} else { } else {
@ -1314,9 +1314,9 @@
} }
async function handleDeleteStrategy() { async function handleDeleteStrategy() {
const postData = { strategyId: selectedStrategy, path: "delete-strategy" }; const postData = { strategyId: selectedStrategy };
const response = await fetch("/api/fastify-post-data", { const response = await fetch("/api/delete-strategy", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -1324,7 +1324,7 @@
body: JSON.stringify(postData), body: JSON.stringify(postData),
}); });
const output = (await response.json())?.items; const output = await response.json();
if (output === "success") { if (output === "success") {
toast.success("Strategy deleted successfully!", { toast.success("Strategy deleted successfully!", {
@ -1398,9 +1398,8 @@
for (const [key, value] of formData.entries()) { for (const [key, value] of formData.entries()) {
postData[key] = value; postData[key] = value;
} }
postData["path"] = "create-strategy";
const response = await fetch("/api/fastify-post-data", { const response = await fetch("/api/create-strategy", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -1408,7 +1407,7 @@
body: JSON.stringify(postData), body: JSON.stringify(postData),
}); });
const output = (await response.json())?.items; const output = await response?.json();
if (output?.id && output?.id?.length !== 0) { if (output?.id && output?.id?.length !== 0) {
toast.success("Strategy created successfully!", { toast.success("Strategy created successfully!", {
style: "border-radius: 200px; background: #333; color: #fff;", style: "border-radius: 200px; background: #333; color: #fff;",
@ -1686,10 +1685,9 @@ const handleKeyDown = (event) => {
const postData = { const postData = {
strategyId: selectedStrategy, strategyId: selectedStrategy,
rules: ruleOfList, rules: ruleOfList,
path: "save-strategy",
}; };
const response = await fetch("/api/fastify-post-data", { const response = await fetch("/api/save-strategy", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -1697,18 +1695,10 @@ const handleKeyDown = (event) => {
body: JSON.stringify(postData), body: JSON.stringify(postData),
}); });
const output = (await response.json())?.items;
if (printToast === true) { if (printToast === true) {
if (output?.id && output?.id?.length !== 0) { toast.success("Strategy saved!", {
toast.success("Strategy saved!", { style: "border-radius: 200px; background: #333; color: #fff;",
style: "border-radius: 200px; background: #333; color: #fff;", });
});
} else {
toast.error("Something went wrong. Please try again later!", {
style: "border-radius: 200px; background: #333; color: #fff;",
});
}
} }
//isSaved = true; //isSaved = true;