Merge branch 'develop'
This commit is contained in:
@@ -55,7 +55,14 @@ export default function PayPalPayment({
|
|||||||
trackingId,
|
trackingId,
|
||||||
})
|
})
|
||||||
.then((response) => response.data)
|
.then((response) => response.data)
|
||||||
.then((data) => data.id);
|
.then((data) => {
|
||||||
|
setIsLoading(false);
|
||||||
|
return data.id;
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
setIsLoading(false);
|
||||||
|
return err;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const onApprove = async (data: OnApproveData, actions: OnApproveActions) => {
|
const onApprove = async (data: OnApproveData, actions: OnApproveActions) => {
|
||||||
@@ -63,18 +70,26 @@ export default function PayPalPayment({
|
|||||||
throw new Error("trackingId is not set");
|
throw new Error("trackingId is not set");
|
||||||
}
|
}
|
||||||
|
|
||||||
const request = await axios.post<{ ok: boolean; reason?: string }>(
|
axios
|
||||||
"/api/paypal/approve",
|
.post<{ ok: boolean; reason?: string }>("/api/paypal/approve", {
|
||||||
{ id: data.orderID, duration, duration_unit, trackingId }
|
id: data.orderID,
|
||||||
);
|
duration,
|
||||||
|
duration_unit,
|
||||||
|
trackingId,
|
||||||
|
})
|
||||||
|
.then((request) => {
|
||||||
|
if (request.status !== 200) {
|
||||||
|
toast.error("Something went wrong, please try again later");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (request.status !== 200) {
|
toast.success("Your account has been credited more time!");
|
||||||
toast.error("Something went wrong, please try again later");
|
return onSuccess(duration, duration_unit);
|
||||||
return;
|
})
|
||||||
}
|
.catch((err) => {
|
||||||
|
console.error(err);
|
||||||
toast.success("Your account has been credited more time!");
|
toast.error("Something went wrong, please try again later");
|
||||||
return onSuccess(duration, duration_unit);
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const onError = async (data: Record<string, unknown>) => {
|
const onError = async (data: Record<string, unknown>) => {
|
||||||
@@ -96,7 +111,6 @@ export default function PayPalPayment({
|
|||||||
currency,
|
currency,
|
||||||
intent: "capture",
|
intent: "capture",
|
||||||
commit: true,
|
commit: true,
|
||||||
vault: true,
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<PayPalButtons
|
<PayPalButtons
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
</p>
|
</p>
|
||||||
<br />
|
<br />
|
||||||
<p>Don't forget to do it before its end date!</p>
|
<p>Don't forget to do it before its end date!</p>
|
||||||
<p>Click <b><a href="https://platform.encoach.com">here</a></b> to open the EnCoach Platform!</p>
|
<p>Click <b><a href="https://{{environment}}.encoach.com">here</a></b> to open the EnCoach Platform!</p>
|
||||||
<br />
|
<br />
|
||||||
<p>Thanks,</p>
|
<p>Thanks,</p>
|
||||||
<p>Your EnCoach team</p>
|
<p>Your EnCoach team</p>
|
||||||
|
|||||||
@@ -11,7 +11,8 @@
|
|||||||
<img src="/logo_title.png" class="w-48 h-48 self-center" />
|
<img src="/logo_title.png" class="w-48 h-48 self-center" />
|
||||||
<div>
|
<div>
|
||||||
<span>Hello future {{type}} of <b>EnCoach</b>,</span><br />
|
<span>Hello future {{type}} of <b>EnCoach</b>,</span><br />
|
||||||
<span>You have been invited to register at <a href="https://platform.encoach.com/register?code={{code}}">EnCoach</a>
|
<span>You have been invited to register at <a
|
||||||
|
href="https://{{environment}}.encoach.com/register?code={{code}}">EnCoach</a>
|
||||||
to
|
to
|
||||||
become a
|
become a
|
||||||
{{type}}!</span><br />
|
{{type}}!</span><br />
|
||||||
@@ -19,7 +20,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<br />
|
<br />
|
||||||
<br />
|
<br />
|
||||||
<a href="https://platform.encoach.com/register?code={{code}}"></a>
|
<a href="https://{{environment}}.encoach.com/register?code={{code}}"></a>
|
||||||
<span class="self-center p-4 px-12 text-lg text-[#]" style="background-color: #D5D9F0; color: #353338">
|
<span class="self-center p-4 px-12 text-lg text-[#]" style="background-color: #D5D9F0; color: #353338">
|
||||||
<b>{{code}}</b>
|
<b>{{code}}</b>
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -10,7 +10,8 @@
|
|||||||
<p>Hello {{name}},</p>
|
<p>Hello {{name}},</p>
|
||||||
<br />
|
<br />
|
||||||
<p>Follow this link to verify your email address.</p>
|
<p>Follow this link to verify your email address.</p>
|
||||||
<a href="https://platform.encoach.com/action?mode=signIn&continueUrl={{email}}&oobCode={{code}}">Verify account</a>
|
<a href="https://{{environment}}.encoach.com/action?mode=signIn&continueUrl={{email}}&oobCode={{code}}">Verify
|
||||||
|
account</a>
|
||||||
<br />
|
<br />
|
||||||
<br />
|
<br />
|
||||||
<p>If you didn’t ask to verify this address, you can ignore this email.</p>
|
<p>If you didn’t ask to verify this address, you can ignore this email.</p>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "Tiago Ribeiro",
|
"name": "Tiago Ribeiro",
|
||||||
"email": "tiago.ribeiro@ecrop.dev",
|
"email": "tiago.ribeiro@ecrop.dev",
|
||||||
"code": "123"
|
"code": "123",
|
||||||
|
"environment": "platform"
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,8 @@ import InviteCard from "@/components/Medium/InviteCard";
|
|||||||
import {useRouter} from "next/router";
|
import {useRouter} from "next/router";
|
||||||
import {PayPalScriptProvider} from "@paypal/react-paypal-js";
|
import {PayPalScriptProvider} from "@paypal/react-paypal-js";
|
||||||
import { usePaypalTracking } from "@/hooks/usePaypalTracking";
|
import { usePaypalTracking } from "@/hooks/usePaypalTracking";
|
||||||
|
import {ToastContainer} from "react-toastify";
|
||||||
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
user: User;
|
user: User;
|
||||||
@@ -47,6 +49,7 @@ export default function PaymentDue({user, hasExpired = false, clientID, reload}:
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
<ToastContainer />
|
||||||
{isLoading && (
|
{isLoading && (
|
||||||
<div className="absolute left-0 top-0 z-[999] h-screen w-screen overflow-hidden bg-black/60">
|
<div className="absolute left-0 top-0 z-[999] h-screen w-screen overflow-hidden bg-black/60">
|
||||||
<div className="absolute left-1/2 top-1/2 flex h-fit w-fit -translate-x-1/2 -translate-y-1/2 animate-pulse flex-col items-center gap-8 text-white">
|
<div className="absolute left-1/2 top-1/2 flex h-fit w-fit -translate-x-1/2 -translate-y-1/2 animate-pulse flex-col items-center gap-8 text-white">
|
||||||
@@ -97,7 +100,6 @@ export default function PaymentDue({user, hasExpired = false, clientID, reload}:
|
|||||||
currency: "USD",
|
currency: "USD",
|
||||||
intent: "capture",
|
intent: "capture",
|
||||||
commit: true,
|
commit: true,
|
||||||
vault: true,
|
|
||||||
}}>
|
}}>
|
||||||
{packages.map((p) => (
|
{packages.map((p) => (
|
||||||
<div key={p.id} className={clsx("flex flex-col items-start gap-6 rounded-xl bg-white p-4")}>
|
<div key={p.id} className={clsx("flex flex-col items-start gap-6 rounded-xl bg-white p-4")}>
|
||||||
|
|||||||
@@ -1,227 +1,170 @@
|
|||||||
/* eslint-disable @next/next/no-img-element */
|
/* eslint-disable @next/next/no-img-element */
|
||||||
import { toast, ToastContainer } from "react-toastify";
|
import {toast, ToastContainer} from "react-toastify";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import { FormEvent, useEffect, useState } from "react";
|
import {FormEvent, useEffect, useState} from "react";
|
||||||
import Head from "next/head";
|
import Head from "next/head";
|
||||||
import useUser from "@/hooks/useUser";
|
import useUser from "@/hooks/useUser";
|
||||||
import { Divider } from "primereact/divider";
|
import {Divider} from "primereact/divider";
|
||||||
import Button from "@/components/Low/Button";
|
import Button from "@/components/Low/Button";
|
||||||
import { BsArrowRepeat } from "react-icons/bs";
|
import {BsArrowRepeat} from "react-icons/bs";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import Input from "@/components/Low/Input";
|
import Input from "@/components/Low/Input";
|
||||||
import { useRouter } from "next/router";
|
import {useRouter} from "next/router";
|
||||||
|
|
||||||
export function getServerSideProps({
|
export function getServerSideProps({
|
||||||
query,
|
query,
|
||||||
res,
|
res,
|
||||||
}: {
|
}: {
|
||||||
query: {
|
query: {
|
||||||
oobCode: string;
|
oobCode: string;
|
||||||
mode: string;
|
mode: string;
|
||||||
continueUrl?: string;
|
continueUrl?: string;
|
||||||
};
|
};
|
||||||
res: any;
|
res: any;
|
||||||
}) {
|
}) {
|
||||||
if (!query || !query.oobCode || !query.mode) {
|
if (!query || !query.oobCode || !query.mode) {
|
||||||
res.setHeader("location", "/login");
|
res.setHeader("location", "/login");
|
||||||
res.statusCode = 302;
|
res.statusCode = 302;
|
||||||
res.end();
|
res.end();
|
||||||
return {
|
return {
|
||||||
props: {},
|
props: {},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
props: {
|
props: {
|
||||||
code: query.oobCode,
|
code: query.oobCode,
|
||||||
mode: query.mode,
|
mode: query.mode,
|
||||||
...(query.continueUrl ? { continueUrl: query.continueUrl } : {}),
|
...(query.continueUrl ? {continueUrl: query.continueUrl} : {}),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Reset({
|
export default function Reset({code, mode, continueUrl}: {code: string; mode: string; continueUrl?: string}) {
|
||||||
code,
|
const [password, setPassword] = useState("");
|
||||||
mode,
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
continueUrl,
|
|
||||||
}: {
|
|
||||||
code: string;
|
|
||||||
mode: string;
|
|
||||||
continueUrl?: string;
|
|
||||||
}) {
|
|
||||||
const [password, setPassword] = useState("");
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
useUser({
|
useUser({
|
||||||
redirectTo: "/",
|
redirectTo: "/",
|
||||||
redirectIfFound: true,
|
redirectIfFound: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (mode === "signIn") {
|
if (mode === "signIn") {
|
||||||
axios
|
axios
|
||||||
.post<{ ok: boolean }>("/api/reset/verify", {
|
.post<{ok: boolean}>("/api/reset/verify", {
|
||||||
email: continueUrl?.replace("https://platform.encoach.com/", ""),
|
email: continueUrl?.replace("https://platform.encoach.com/", "").replace("https://staging.encoach.com/", ""),
|
||||||
})
|
})
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
if (response.data.ok) {
|
if (response.data.ok) {
|
||||||
toast.success("Your account has been verified!", {
|
toast.success("Your account has been verified!", {
|
||||||
toastId: "verify-successful",
|
toastId: "verify-successful",
|
||||||
});
|
});
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
router.push("/");
|
router.push("/");
|
||||||
}, 1000);
|
}, 1000);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
toast.error(
|
toast.error("Something went wrong! Please make sure to click the link in your e-mail again and input the correct e-mail!", {
|
||||||
"Something went wrong! Please make sure to click the link in your e-mail again and input the correct e-mail!",
|
toastId: "verify-error",
|
||||||
{
|
});
|
||||||
toastId: "verify-error",
|
})
|
||||||
},
|
.catch(() => {
|
||||||
);
|
toast.error("Something went wrong! Please make sure to click the link in your e-mail again and input the correct e-mail!", {
|
||||||
})
|
toastId: "verify-error",
|
||||||
.catch(() => {
|
});
|
||||||
toast.error(
|
setIsLoading(false);
|
||||||
"Something went wrong! Please make sure to click the link in your e-mail again and input the correct e-mail!",
|
});
|
||||||
{
|
}
|
||||||
toastId: "verify-error",
|
});
|
||||||
},
|
|
||||||
);
|
|
||||||
setIsLoading(false);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const login = (e: FormEvent<HTMLFormElement>) => {
|
const login = (e: FormEvent<HTMLFormElement>) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
axios
|
axios
|
||||||
.post<{ ok: boolean }>("/api/reset/confirm", { code, password })
|
.post<{ok: boolean}>("/api/reset/confirm", {code, password})
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
if (response.data.ok) {
|
if (response.data.ok) {
|
||||||
toast.success("Your password has been reset!", {
|
toast.success("Your password has been reset!", {
|
||||||
toastId: "reset-successful",
|
toastId: "reset-successful",
|
||||||
});
|
});
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
router.push("/login");
|
router.push("/login");
|
||||||
}, 1000);
|
}, 1000);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
toast.error(
|
toast.error("Something went wrong! Please make sure to click the link in your e-mail again!", {toastId: "reset-error"});
|
||||||
"Something went wrong! Please make sure to click the link in your e-mail again!",
|
})
|
||||||
{ toastId: "reset-error" },
|
.catch(() => {
|
||||||
);
|
toast.error("Something went wrong! Please make sure to click the link in your e-mail again!", {toastId: "reset-error"});
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.finally(() => setIsLoading(false));
|
||||||
toast.error(
|
};
|
||||||
"Something went wrong! Please make sure to click the link in your e-mail again!",
|
|
||||||
{ toastId: "reset-error" },
|
|
||||||
);
|
|
||||||
})
|
|
||||||
.finally(() => setIsLoading(false));
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Head>
|
<Head>
|
||||||
<title>Reset | EnCoach</title>
|
<title>Reset | EnCoach</title>
|
||||||
<meta name="description" content="Generated by create next app" />
|
<meta name="description" content="Generated by create next app" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<link rel="icon" href="/favicon.ico" />
|
<link rel="icon" href="/favicon.ico" />
|
||||||
</Head>
|
</Head>
|
||||||
<main className="flex h-[100vh] w-full bg-white text-black">
|
<main className="flex h-[100vh] w-full bg-white text-black">
|
||||||
<ToastContainer />
|
<ToastContainer />
|
||||||
<section className="relative hidden h-full w-fit min-w-fit lg:flex">
|
<section className="relative hidden h-full w-fit min-w-fit lg:flex">
|
||||||
<div className="bg-mti-rose-light absolute z-10 h-full w-full bg-opacity-50" />
|
<div className="bg-mti-rose-light absolute z-10 h-full w-full bg-opacity-50" />
|
||||||
<img
|
<img src="/people-talking-tablet.png" alt="People smiling looking at a tablet" className="aspect-auto h-full" />
|
||||||
src="/people-talking-tablet.png"
|
</section>
|
||||||
alt="People smiling looking at a tablet"
|
{mode === "resetPassword" && (
|
||||||
className="aspect-auto h-full"
|
<section className="flex h-full w-full flex-col items-center justify-center gap-2">
|
||||||
/>
|
<div className="relative flex flex-col items-center gap-2">
|
||||||
</section>
|
<img src="/logo_title.png" alt="EnCoach's Logo" className="absolute -top-36 w-36 lg:-top-64 lg:w-64" />
|
||||||
{mode === "resetPassword" && (
|
<h1 className="text-2xl font-bold lg:text-4xl">Reset your password</h1>
|
||||||
<section className="flex h-full w-full flex-col items-center justify-center gap-2">
|
<p className="text-mti-gray-cool self-start text-sm font-normal lg:text-base">to your registered Email Address</p>
|
||||||
<div className="relative flex flex-col items-center gap-2">
|
</div>
|
||||||
<img
|
<Divider className="max-w-xs lg:max-w-md" />
|
||||||
src="/logo_title.png"
|
<form className="-lg:px-8 flex w-full flex-col items-center gap-6 lg:w-1/2" onSubmit={login}>
|
||||||
alt="EnCoach's Logo"
|
<Input type="password" name="password" onChange={(e) => setPassword(e)} placeholder="Password" />
|
||||||
className="absolute -top-36 w-36 lg:-top-64 lg:w-64"
|
|
||||||
/>
|
|
||||||
<h1 className="text-2xl font-bold lg:text-4xl">
|
|
||||||
Reset your password
|
|
||||||
</h1>
|
|
||||||
<p className="text-mti-gray-cool self-start text-sm font-normal lg:text-base">
|
|
||||||
to your registered Email Address
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Divider className="max-w-xs lg:max-w-md" />
|
|
||||||
<form
|
|
||||||
className="-lg:px-8 flex w-full flex-col items-center gap-6 lg:w-1/2"
|
|
||||||
onSubmit={login}
|
|
||||||
>
|
|
||||||
<Input
|
|
||||||
type="password"
|
|
||||||
name="password"
|
|
||||||
onChange={(e) => setPassword(e)}
|
|
||||||
placeholder="Password"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Button
|
<Button className="mt-8 w-full" color="purple" disabled={isLoading}>
|
||||||
className="mt-8 w-full"
|
{!isLoading && "Reset"}
|
||||||
color="purple"
|
{isLoading && (
|
||||||
disabled={isLoading}
|
<div className="flex items-center justify-center">
|
||||||
>
|
<BsArrowRepeat className="animate-spin text-white" size={25} />
|
||||||
{!isLoading && "Reset"}
|
</div>
|
||||||
{isLoading && (
|
)}
|
||||||
<div className="flex items-center justify-center">
|
</Button>
|
||||||
<BsArrowRepeat
|
</form>
|
||||||
className="animate-spin text-white"
|
<span className="text-mti-gray-cool mt-8 text-sm font-normal">
|
||||||
size={25}
|
Don't have an account?{" "}
|
||||||
/>
|
<Link className="text-mti-purple-light" href="/register">
|
||||||
</div>
|
Sign up
|
||||||
)}
|
</Link>
|
||||||
</Button>
|
</span>
|
||||||
</form>
|
</section>
|
||||||
<span className="text-mti-gray-cool mt-8 text-sm font-normal">
|
)}
|
||||||
Don't have an account?{" "}
|
{mode === "signIn" && (
|
||||||
<Link className="text-mti-purple-light" href="/register">
|
<section className="flex h-full w-full flex-col items-center justify-center gap-2">
|
||||||
Sign up
|
<div className="relative flex flex-col items-center gap-2">
|
||||||
</Link>
|
<img src="/logo_title.png" alt="EnCoach's Logo" className="absolute -top-36 w-36 lg:-top-64 lg:w-64" />
|
||||||
</span>
|
<h1 className="text-2xl font-bold lg:text-4xl">Confirm your account</h1>
|
||||||
</section>
|
<p className="text-mti-gray-cool self-start text-sm font-normal lg:text-base">to your registered Email Address</p>
|
||||||
)}
|
</div>
|
||||||
{mode === "signIn" && (
|
<Divider className="max-w-xs lg:max-w-md" />
|
||||||
<section className="flex h-full w-full flex-col items-center justify-center gap-2">
|
<div className="-lg:px-8 flex w-full flex-col items-center gap-6 lg:w-1/2">
|
||||||
<div className="relative flex flex-col items-center gap-2">
|
<span className="text-center">
|
||||||
<img
|
Your e-mail is currently being verified, please wait a second. <br /> <br />
|
||||||
src="/logo_title.png"
|
Once it has been verified, you will be redirected to the home page.
|
||||||
alt="EnCoach's Logo"
|
</span>
|
||||||
className="absolute -top-36 w-36 lg:-top-64 lg:w-64"
|
</div>
|
||||||
/>
|
</section>
|
||||||
<h1 className="text-2xl font-bold lg:text-4xl">
|
)}
|
||||||
Confirm your account
|
</main>
|
||||||
</h1>
|
</>
|
||||||
<p className="text-mti-gray-cool self-start text-sm font-normal lg:text-base">
|
);
|
||||||
to your registered Email Address
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Divider className="max-w-xs lg:max-w-md" />
|
|
||||||
<div className="-lg:px-8 flex w-full flex-col items-center gap-6 lg:w-1/2">
|
|
||||||
<span className="text-center">
|
|
||||||
Your e-mail is currently being verified, please wait a second.{" "}
|
|
||||||
<br /> <br />
|
|
||||||
Once it has been verified, you will be redirected to the home
|
|
||||||
page.
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
)}
|
|
||||||
</main>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -163,6 +163,7 @@ async function POST(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
modules: examModulesLabel,
|
modules: examModulesLabel,
|
||||||
assigner: teacher.name,
|
assigner: teacher.name,
|
||||||
},
|
},
|
||||||
|
environment: process.env.ENVIRONMENT,
|
||||||
},
|
},
|
||||||
[assignee.email],
|
[assignee.email],
|
||||||
"EnCoach - New Assignment!",
|
"EnCoach - New Assignment!",
|
||||||
|
|||||||
@@ -113,6 +113,7 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
corporateName: invitedBy.name,
|
corporateName: invitedBy.name,
|
||||||
name: req.session.user.name,
|
name: req.session.user.name,
|
||||||
decision: "accept",
|
decision: "accept",
|
||||||
|
environment: process.env.ENVIRONMENT,
|
||||||
},
|
},
|
||||||
[invitedBy.email],
|
[invitedBy.email],
|
||||||
`${req.session.user.name} has accepted your invite!`,
|
`${req.session.user.name} has accepted your invite!`,
|
||||||
|
|||||||
@@ -1,72 +1,62 @@
|
|||||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||||
import type { NextApiRequest, NextApiResponse } from "next";
|
import type {NextApiRequest, NextApiResponse} from "next";
|
||||||
import { app } from "@/firebase";
|
import {app} from "@/firebase";
|
||||||
import {
|
import {getFirestore, getDoc, doc, deleteDoc, setDoc, getDocs, collection, where, query} from "firebase/firestore";
|
||||||
getFirestore,
|
import {withIronSessionApiRoute} from "iron-session/next";
|
||||||
getDoc,
|
import {sessionOptions} from "@/lib/session";
|
||||||
doc,
|
import {Ticket} from "@/interfaces/ticket";
|
||||||
deleteDoc,
|
import {Invite} from "@/interfaces/invite";
|
||||||
setDoc,
|
import {Group, User} from "@/interfaces/user";
|
||||||
getDocs,
|
import {v4} from "uuid";
|
||||||
collection,
|
import {sendEmail} from "@/email";
|
||||||
where,
|
|
||||||
query,
|
|
||||||
} from "firebase/firestore";
|
|
||||||
import { withIronSessionApiRoute } from "iron-session/next";
|
|
||||||
import { sessionOptions } from "@/lib/session";
|
|
||||||
import { Ticket } from "@/interfaces/ticket";
|
|
||||||
import { Invite } from "@/interfaces/invite";
|
|
||||||
import { Group, User } from "@/interfaces/user";
|
|
||||||
import { v4 } from "uuid";
|
|
||||||
import { sendEmail } from "@/email";
|
|
||||||
|
|
||||||
const db = getFirestore(app);
|
const db = getFirestore(app);
|
||||||
|
|
||||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||||
|
|
||||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||||
if (req.method === "GET") return await get(req, res);
|
if (req.method === "GET") return await get(req, res);
|
||||||
|
|
||||||
res.status(404).json(undefined);
|
res.status(404).json(undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||||
if (!req.session.user) {
|
if (!req.session.user) {
|
||||||
res.status(401).json({ ok: false });
|
res.status(401).json({ok: false});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { id } = req.query as { id: string };
|
const {id} = req.query as {id: string};
|
||||||
const snapshot = await getDoc(doc(db, "invites", id));
|
const snapshot = await getDoc(doc(db, "invites", id));
|
||||||
|
|
||||||
if (snapshot.exists()) {
|
if (snapshot.exists()) {
|
||||||
const invite = { ...snapshot.data(), id: snapshot.id } as Invite;
|
const invite = {...snapshot.data(), id: snapshot.id} as Invite;
|
||||||
if (invite.to !== req.session.user.id)
|
if (invite.to !== req.session.user.id) return res.status(403).json({ok: false});
|
||||||
return res.status(403).json({ ok: false });
|
|
||||||
|
|
||||||
await deleteDoc(snapshot.ref);
|
await deleteDoc(snapshot.ref);
|
||||||
const invitedByRef = await getDoc(doc(db, "users", invite.from));
|
const invitedByRef = await getDoc(doc(db, "users", invite.from));
|
||||||
if (!invitedByRef.exists()) return res.status(404).json({ ok: false });
|
if (!invitedByRef.exists()) return res.status(404).json({ok: false});
|
||||||
|
|
||||||
const invitedBy = { ...invitedByRef.data(), id: invitedByRef.id } as User;
|
const invitedBy = {...invitedByRef.data(), id: invitedByRef.id} as User;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await sendEmail(
|
await sendEmail(
|
||||||
"respondedInvite",
|
"respondedInvite",
|
||||||
{
|
{
|
||||||
corporateName: invitedBy.name,
|
corporateName: invitedBy.name,
|
||||||
name: req.session.user.name,
|
name: req.session.user.name,
|
||||||
decision: "decline",
|
decision: "decline",
|
||||||
},
|
environment: process.env.ENVIRONMENT,
|
||||||
[invitedBy.email],
|
},
|
||||||
`${req.session.user.name} has declined your invite!`,
|
[invitedBy.email],
|
||||||
);
|
`${req.session.user.name} has declined your invite!`,
|
||||||
} catch (e) {
|
);
|
||||||
console.log(e);
|
} catch (e) {
|
||||||
}
|
console.log(e);
|
||||||
|
}
|
||||||
|
|
||||||
res.status(200).json({ ok: true });
|
res.status(200).json({ok: true});
|
||||||
} else {
|
} else {
|
||||||
res.status(404).json(undefined);
|
res.status(404).json(undefined);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,13 @@
|
|||||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||||
import { sendEmail } from "@/email";
|
import {sendEmail} from "@/email";
|
||||||
import { app } from "@/firebase";
|
import {app} from "@/firebase";
|
||||||
import { Invite } from "@/interfaces/invite";
|
import {Invite} from "@/interfaces/invite";
|
||||||
import { Ticket } from "@/interfaces/ticket";
|
import {Ticket} from "@/interfaces/ticket";
|
||||||
import { User } from "@/interfaces/user";
|
import {User} from "@/interfaces/user";
|
||||||
import { sessionOptions } from "@/lib/session";
|
import {sessionOptions} from "@/lib/session";
|
||||||
import {
|
import {collection, doc, getDoc, getDocs, getFirestore, setDoc} from "firebase/firestore";
|
||||||
collection,
|
import {withIronSessionApiRoute} from "iron-session/next";
|
||||||
doc,
|
import type {NextApiRequest, NextApiResponse} from "next";
|
||||||
getDoc,
|
|
||||||
getDocs,
|
|
||||||
getFirestore,
|
|
||||||
setDoc,
|
|
||||||
} from "firebase/firestore";
|
|
||||||
import { withIronSessionApiRoute } from "iron-session/next";
|
|
||||||
import type { NextApiRequest, NextApiResponse } from "next";
|
|
||||||
import ShortUniqueId from "short-unique-id";
|
import ShortUniqueId from "short-unique-id";
|
||||||
|
|
||||||
const db = getFirestore(app);
|
const db = getFirestore(app);
|
||||||
@@ -22,67 +15,60 @@ const db = getFirestore(app);
|
|||||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||||
|
|
||||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||||
if (!req.session.user) {
|
if (!req.session.user) {
|
||||||
res.status(401).json({ ok: false });
|
res.status(401).json({ok: false});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (req.method === "GET") await get(req, res);
|
if (req.method === "GET") await get(req, res);
|
||||||
if (req.method === "POST") await post(req, res);
|
if (req.method === "POST") await post(req, res);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const snapshot = await getDocs(collection(db, "invites"));
|
const snapshot = await getDocs(collection(db, "invites"));
|
||||||
|
|
||||||
res.status(200).json(
|
res.status(200).json(
|
||||||
snapshot.docs.map((doc) => ({
|
snapshot.docs.map((doc) => ({
|
||||||
id: doc.id,
|
id: doc.id,
|
||||||
...doc.data(),
|
...doc.data(),
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const body = req.body as Invite;
|
const body = req.body as Invite;
|
||||||
|
|
||||||
const existingInvites = (await getDocs(collection(db, "invites"))).docs.map(
|
const existingInvites = (await getDocs(collection(db, "invites"))).docs.map((x) => ({...x.data(), id: x.id})) as Invite[];
|
||||||
(x) => ({ ...x.data(), id: x.id }),
|
|
||||||
) as Invite[];
|
|
||||||
|
|
||||||
const invitedRef = await getDoc(doc(db, "users", body.to));
|
const invitedRef = await getDoc(doc(db, "users", body.to));
|
||||||
if (!invitedRef.exists()) return res.status(404).json({ ok: false });
|
if (!invitedRef.exists()) return res.status(404).json({ok: false});
|
||||||
|
|
||||||
const invitedByRef = await getDoc(doc(db, "users", body.from));
|
const invitedByRef = await getDoc(doc(db, "users", body.from));
|
||||||
if (!invitedByRef.exists()) return res.status(404).json({ ok: false });
|
if (!invitedByRef.exists()) return res.status(404).json({ok: false});
|
||||||
|
|
||||||
const invited = { ...invitedRef.data(), id: invitedRef.id } as User;
|
const invited = {...invitedRef.data(), id: invitedRef.id} as User;
|
||||||
const invitedBy = { ...invitedByRef.data(), id: invitedByRef.id } as User;
|
const invitedBy = {...invitedByRef.data(), id: invitedByRef.id} as User;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await sendEmail(
|
await sendEmail(
|
||||||
"receivedInvite",
|
"receivedInvite",
|
||||||
{
|
{
|
||||||
name: invited.name,
|
name: invited.name,
|
||||||
corporateName:
|
corporateName:
|
||||||
invitedBy.type === "corporate"
|
invitedBy.type === "corporate" ? invitedBy.corporateInformation?.companyInformation?.name || invitedBy.name : invitedBy.name,
|
||||||
? invitedBy.corporateInformation?.companyInformation?.name ||
|
environment: process.env.ENVIRONMENT,
|
||||||
invitedBy.name
|
},
|
||||||
: invitedBy.name,
|
[invited.email],
|
||||||
},
|
"You have been invited to a group!",
|
||||||
[invited.email],
|
);
|
||||||
"You have been invited to a group!",
|
} catch (e) {
|
||||||
);
|
console.log(e);
|
||||||
} catch (e) {
|
}
|
||||||
console.log(e);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
if (existingInvites.filter((i) => i.to === body.to && i.from === body.from).length == 0) {
|
||||||
existingInvites.filter((i) => i.to === body.to && i.from === body.from)
|
const shortUID = new ShortUniqueId();
|
||||||
.length == 0
|
await setDoc(doc(db, "invites", body.id || shortUID.randomUUID(8)), body);
|
||||||
) {
|
}
|
||||||
const shortUID = new ShortUniqueId();
|
|
||||||
await setDoc(doc(db, "invites", body.id || shortUID.randomUUID(8)), body);
|
|
||||||
}
|
|
||||||
|
|
||||||
res.status(200).json({ ok: true });
|
res.status(200).json({ok: true});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,91 +42,96 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
if (!trackingId)
|
if (!trackingId)
|
||||||
return res.status(401).json({ ok: false, reason: "Missing tracking id!" });
|
return res.status(401).json({ ok: false, reason: "Missing tracking id!" });
|
||||||
|
|
||||||
const request = await axios.post(
|
const url = `${process.env.PAYPAL_ACCESS_TOKEN_URL}/v2/checkout/orders/${id}/capture`;
|
||||||
`${process.env.PAYPAL_ACCESS_TOKEN_URL}/v2/checkout/orders/${id}/capture`,
|
const headers = {
|
||||||
{},
|
headers: {
|
||||||
{
|
Authorization: `Bearer ${accessToken}`,
|
||||||
headers: {
|
"PayPal-Client-Metadata-Id": trackingId,
|
||||||
Authorization: `Bearer ${accessToken}`,
|
},
|
||||||
"PayPal-Client-Metadata-Id": trackingId,
|
};
|
||||||
},
|
axios
|
||||||
}
|
.post(url, {}, headers)
|
||||||
);
|
.then(async (request) => {
|
||||||
|
if (request.data.status === "COMPLETED") {
|
||||||
|
const user = req.session.user;
|
||||||
|
const subscriptionExpirationDate =
|
||||||
|
user!.subscriptionExpirationDate;
|
||||||
|
const today = moment(new Date());
|
||||||
|
const dateToBeAddedTo = !subscriptionExpirationDate
|
||||||
|
? today
|
||||||
|
: moment(subscriptionExpirationDate).isAfter(today)
|
||||||
|
? moment(subscriptionExpirationDate)
|
||||||
|
: today;
|
||||||
|
|
||||||
if (request.data.status === "COMPLETED") {
|
const updatedExpirationDate = dateToBeAddedTo.add(
|
||||||
const user = req.session.user;
|
duration,
|
||||||
const subscriptionExpirationDate =
|
duration_unit
|
||||||
req.session.user.subscriptionExpirationDate;
|
);
|
||||||
const today = moment(new Date());
|
await setDoc(
|
||||||
const dateToBeAddedTo = !subscriptionExpirationDate
|
doc(db, "users", req.session.user!.id),
|
||||||
? today
|
{
|
||||||
: moment(subscriptionExpirationDate).isAfter(today)
|
subscriptionExpirationDate: updatedExpirationDate.toISOString(),
|
||||||
? moment(subscriptionExpirationDate)
|
status: "active",
|
||||||
: today;
|
},
|
||||||
|
{ merge: true }
|
||||||
|
);
|
||||||
|
|
||||||
const updatedExpirationDate = dateToBeAddedTo.add(duration, duration_unit);
|
try {
|
||||||
await setDoc(
|
await setDoc(doc(db, "paypalpayments", v4()), {
|
||||||
doc(db, "users", req.session.user.id),
|
orderId: id,
|
||||||
{
|
userId: req.session.user!.id,
|
||||||
subscriptionExpirationDate: updatedExpirationDate.toISOString(),
|
status: request.data.status,
|
||||||
status: "active",
|
createdAt: new Date().toISOString(),
|
||||||
},
|
value:
|
||||||
{ merge: true }
|
request.data.purchase_units[0].payments.captures[0].amount.value,
|
||||||
);
|
currency:
|
||||||
|
request.data.purchase_units[0].payments.captures[0].amount
|
||||||
|
.currency_code,
|
||||||
|
subscriptionDuration: duration,
|
||||||
|
subscriptionDurationUnit: duration_unit,
|
||||||
|
subscriptionExpirationDate: updatedExpirationDate.toISOString(),
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to insert paypal payment!", err);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
if (user!.type === "corporate") {
|
||||||
await setDoc(
|
const snapshot = await getDocs(collection(db, "groups"));
|
||||||
doc(db, 'paypalpayments', v4()),
|
const groups: Group[] = (
|
||||||
{
|
snapshot.docs.map((doc) => ({
|
||||||
orderId: id,
|
id: doc.id,
|
||||||
userId: req.session.user.id,
|
...doc.data(),
|
||||||
status: request.data.status,
|
})) as Group[]
|
||||||
createdAt: new Date().toISOString(),
|
).filter((x) => x.admin === user!.id);
|
||||||
value: request.data.purchase_units[0].payments.captures[0].amount.value,
|
|
||||||
currency: request.data.purchase_units[0].payments.captures[0].amount.currency_code,
|
|
||||||
subscriptionDuration: duration,
|
|
||||||
subscriptionDurationUnit: duration_unit,
|
|
||||||
subscriptionExpirationDate: updatedExpirationDate.toISOString(),
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} catch(err) {
|
|
||||||
console.error('Failed to insert paypal payment!', err);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (user.type === "corporate") {
|
await Promise.all(
|
||||||
const snapshot = await getDocs(collection(db, "groups"));
|
groups
|
||||||
const groups: Group[] = (
|
.flatMap((x) => x.participants)
|
||||||
snapshot.docs.map((doc) => ({
|
.map(
|
||||||
id: doc.id,
|
async (x) =>
|
||||||
...doc.data(),
|
await setDoc(
|
||||||
})) as Group[]
|
doc(db, "users", x),
|
||||||
).filter((x) => x.admin === user.id);
|
{
|
||||||
|
subscriptionExpirationDate:
|
||||||
await Promise.all(
|
updatedExpirationDate.toISOString(),
|
||||||
groups
|
status: "active",
|
||||||
.flatMap((x) => x.participants)
|
},
|
||||||
.map(
|
{ merge: true }
|
||||||
async (x) =>
|
)
|
||||||
await setDoc(
|
|
||||||
doc(db, "users", x),
|
|
||||||
{
|
|
||||||
subscriptionExpirationDate:
|
|
||||||
updatedExpirationDate.toISOString(),
|
|
||||||
status: "active",
|
|
||||||
},
|
|
||||||
{ merge: true }
|
|
||||||
)
|
)
|
||||||
)
|
);
|
||||||
);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return res.status(200).json({ ok: true });
|
return res.status(200).json({ ok: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
res
|
res.status(404).json({
|
||||||
.status(404)
|
ok: false,
|
||||||
.json({
|
reason: "Order ID not found or purchase was not approved!",
|
||||||
ok: false,
|
});
|
||||||
reason: "Order ID not found or purchase was not approved!",
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error(err.response.status, err.response.data);
|
||||||
|
res.status(err.response.status).json(err.response.data);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,62 +1,99 @@
|
|||||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||||
import type {NextApiRequest, NextApiResponse} from "next";
|
import type { NextApiRequest, NextApiResponse } from "next";
|
||||||
import {app} from "@/firebase";
|
import { app } from "@/firebase";
|
||||||
import {getFirestore, collection, getDocs} from "firebase/firestore";
|
import { getFirestore, collection, getDocs } from "firebase/firestore";
|
||||||
import {withIronSessionApiRoute} from "iron-session/next";
|
import { withIronSessionApiRoute } from "iron-session/next";
|
||||||
import {sessionOptions} from "@/lib/session";
|
import { sessionOptions } from "@/lib/session";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import {v4} from "uuid";
|
import { v4 } from "uuid";
|
||||||
import {OrderResponseBody} from "@paypal/paypal-js";
|
import { OrderResponseBody } from "@paypal/paypal-js";
|
||||||
import {getAccessToken} from "@/utils/paypal";
|
import { getAccessToken } from "@/utils/paypal";
|
||||||
|
|
||||||
const db = getFirestore(app);
|
const db = getFirestore(app);
|
||||||
|
|
||||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||||
|
|
||||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||||
if (req.method !== "POST") return res.status(404).json({ok: false, reason: "Method not supported!"});
|
if (req.method !== "POST")
|
||||||
if (!req.session.user) return res.status(401).json({ok: false});
|
return res.status(404).json({ ok: false, reason: "Method not supported!" });
|
||||||
|
if (!req.session.user) return res.status(401).json({ ok: false });
|
||||||
|
|
||||||
const accessToken = await getAccessToken();
|
const accessToken = await getAccessToken();
|
||||||
if (!accessToken) return res.status(401).json({ok: false, reason: "Authorization failed!"});
|
if (!accessToken)
|
||||||
|
return res.status(401).json({ ok: false, reason: "Authorization failed!" });
|
||||||
|
|
||||||
const {currencyCode, price, trackingId} = req.body as {currencyCode: string; price: number, trackingId: string};
|
const { currencyCode, price, trackingId } = req.body as {
|
||||||
|
currencyCode: string;
|
||||||
|
price: number;
|
||||||
|
trackingId: string;
|
||||||
|
};
|
||||||
|
|
||||||
if(!trackingId) return res.status(401).json({ok: false, reason: "Missing tracking id!"});
|
if (!trackingId)
|
||||||
|
return res.status(401).json({ ok: false, reason: "Missing tracking id!" });
|
||||||
|
|
||||||
const request = await axios.post<OrderResponseBody>(
|
const url = `${process.env.PAYPAL_ACCESS_TOKEN_URL}/v2/checkout/orders`;
|
||||||
`${process.env.PAYPAL_ACCESS_TOKEN_URL}/v2/checkout/orders`,
|
const amount = {
|
||||||
{
|
currency_code: currencyCode,
|
||||||
purchase_units: [
|
value: price.toString(),
|
||||||
{
|
};
|
||||||
amount: {
|
|
||||||
currency_code: currencyCode,
|
const data = {
|
||||||
value: price.toString(),
|
purchase_units: [
|
||||||
},
|
{
|
||||||
reference_id: v4(),
|
invoice_id: `INV-${v4()}`,
|
||||||
},
|
amount: {
|
||||||
],
|
...amount,
|
||||||
payment_source: {
|
breakdown: {
|
||||||
paypal: {
|
item_total: amount,
|
||||||
email_address: req.session.user.email || "",
|
|
||||||
experience_context: {
|
|
||||||
payment_method_preference: "IMMEDIATE_PAYMENT_REQUIRED",
|
|
||||||
locale: "en-US",
|
|
||||||
landing_page: "LOGIN",
|
|
||||||
shipping_preference: "NO_SHIPPING",
|
|
||||||
user_action: "PAY_NOW",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
name: "Encoach Subscription",
|
||||||
|
quantity: "1",
|
||||||
|
category: "DIGITAL_GOODS",
|
||||||
|
unit_amount: amount,
|
||||||
|
},
|
||||||
|
],
|
||||||
},
|
},
|
||||||
intent: "CAPTURE",
|
],
|
||||||
},
|
payment_source: {
|
||||||
{
|
paypal: {
|
||||||
headers: {
|
email_address: req.session.user.email || "",
|
||||||
Authorization: `Bearer ${accessToken}`,
|
experience_context: {
|
||||||
'PayPal-Client-Metadata-Id': trackingId,
|
payment_method_preference: "IMMEDIATE_PAYMENT_REQUIRED",
|
||||||
},
|
locale: "en-US",
|
||||||
},
|
landing_page: "LOGIN",
|
||||||
);
|
shipping_preference: "NO_SHIPPING",
|
||||||
|
user_action: "PAY_NOW",
|
||||||
|
brand_name: "Encoach",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
intent: "CAPTURE",
|
||||||
|
};
|
||||||
|
|
||||||
res.status(request.status).json(request.data);
|
const headers = {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
"PayPal-Client-Metadata-Id": trackingId,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
console.log(
|
||||||
|
JSON.stringify({
|
||||||
|
url,
|
||||||
|
data,
|
||||||
|
headers,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
axios
|
||||||
|
.post<OrderResponseBody>(url, data, headers)
|
||||||
|
.then((request) => {
|
||||||
|
res.status(request.status).json(request.data);
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error(err.response.status, err.response.data);
|
||||||
|
res.status(err.response.status).json(err.response.data);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,29 +25,35 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
|
|
||||||
const trackingId = `${req.session.user.id}-${Date.now()}`;
|
const trackingId = `${req.session.user.id}-${Date.now()}`;
|
||||||
|
|
||||||
try {
|
const url = `${process.env.PAYPAL_ACCESS_TOKEN_URL}/v1/risk/transaction-contexts/${process.env.PAYPAL_MERCHANT_ID}/${trackingId}`;
|
||||||
const request = await axios.put(
|
const data = {
|
||||||
`${process.env.PAYPAL_ACCESS_TOKEN_URL}/v1/risk/transaction-contexts/${process.env.PAYPAL_MERCHANT_ID}/${trackingId}`,
|
additional_data: [
|
||||||
{
|
{
|
||||||
additional_data: [
|
key: "user_id",
|
||||||
{
|
value: req.session.user.id,
|
||||||
key: "user_id",
|
|
||||||
value: req.session.user.id,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
{
|
],
|
||||||
headers: {
|
};
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
const headers = {
|
||||||
}
|
headers: {
|
||||||
);
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
url,
|
||||||
|
data,
|
||||||
|
headers,
|
||||||
|
}));
|
||||||
|
try {
|
||||||
|
const request = await axios.put(url, data, headers);
|
||||||
|
|
||||||
return res.status(request.status).json({
|
return res.status(request.status).json({
|
||||||
ok: true,
|
ok: true,
|
||||||
trackingId,
|
trackingId,
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
console.error(url, err);
|
||||||
return res
|
return res
|
||||||
.status(500)
|
.status(500)
|
||||||
.json({ ok: false, reason: "Failed to create tracking ID" });
|
.json({ ok: false, reason: "Failed to create tracking ID" });
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ async function sendVerification(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
name: req.session.user.name,
|
name: req.session.user.name,
|
||||||
code: short.randomUUID(6),
|
code: short.randomUUID(6),
|
||||||
email: req.session.user.email,
|
email: req.session.user.email,
|
||||||
|
environment: process.env.ENVIRONMENT,
|
||||||
},
|
},
|
||||||
[req.session.user.email],
|
[req.session.user.email],
|
||||||
"EnCoach Verification",
|
"EnCoach Verification",
|
||||||
|
|||||||
@@ -1,109 +1,104 @@
|
|||||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||||
import type { NextApiRequest, NextApiResponse } from "next";
|
import type {NextApiRequest, NextApiResponse} from "next";
|
||||||
import { app } from "@/firebase";
|
import {app} from "@/firebase";
|
||||||
import {
|
import {getFirestore, getDoc, doc, deleteDoc, setDoc} from "firebase/firestore";
|
||||||
getFirestore,
|
import {withIronSessionApiRoute} from "iron-session/next";
|
||||||
getDoc,
|
import {sessionOptions} from "@/lib/session";
|
||||||
doc,
|
import {Ticket, TicketTypeLabel, TicketStatusLabel} from "@/interfaces/ticket";
|
||||||
deleteDoc,
|
|
||||||
setDoc,
|
|
||||||
} from "firebase/firestore";
|
|
||||||
import { withIronSessionApiRoute } from "iron-session/next";
|
|
||||||
import { sessionOptions } from "@/lib/session";
|
|
||||||
import { Ticket, TicketTypeLabel, TicketStatusLabel } from "@/interfaces/ticket";
|
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import { sendEmail } from "@/email";
|
import {sendEmail} from "@/email";
|
||||||
|
|
||||||
const db = getFirestore(app);
|
const db = getFirestore(app);
|
||||||
|
|
||||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||||
|
|
||||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||||
if (req.method === "GET") return await get(req, res);
|
if (req.method === "GET") return await get(req, res);
|
||||||
if (req.method === "DELETE") return await del(req, res);
|
if (req.method === "DELETE") return await del(req, res);
|
||||||
if (req.method === "PATCH") return await patch(req, res);
|
if (req.method === "PATCH") return await patch(req, res);
|
||||||
|
|
||||||
res.status(404).json(undefined);
|
res.status(404).json(undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||||
if (!req.session.user) {
|
if (!req.session.user) {
|
||||||
res.status(401).json({ ok: false });
|
res.status(401).json({ok: false});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { id } = req.query as { id: string };
|
const {id} = req.query as {id: string};
|
||||||
|
|
||||||
const snapshot = await getDoc(doc(db, "tickets", id));
|
const snapshot = await getDoc(doc(db, "tickets", id));
|
||||||
|
|
||||||
if (snapshot.exists()) {
|
if (snapshot.exists()) {
|
||||||
res.status(200).json({ ...snapshot.data(), id: snapshot.id });
|
res.status(200).json({...snapshot.data(), id: snapshot.id});
|
||||||
} else {
|
} else {
|
||||||
res.status(404).json(undefined);
|
res.status(404).json(undefined);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function del(req: NextApiRequest, res: NextApiResponse) {
|
async function del(req: NextApiRequest, res: NextApiResponse) {
|
||||||
if (!req.session.user) {
|
if (!req.session.user) {
|
||||||
res.status(401).json({ ok: false });
|
res.status(401).json({ok: false});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { id } = req.query as { id: string };
|
const {id} = req.query as {id: string};
|
||||||
|
|
||||||
const snapshot = await getDoc(doc(db, "tickets", id));
|
const snapshot = await getDoc(doc(db, "tickets", id));
|
||||||
const data = snapshot.data() as Ticket;
|
const data = snapshot.data() as Ticket;
|
||||||
|
|
||||||
const user = req.session.user;
|
const user = req.session.user;
|
||||||
if (user.type === "admin" || user.type === "developer") {
|
if (user.type === "admin" || user.type === "developer") {
|
||||||
await deleteDoc(snapshot.ref);
|
await deleteDoc(snapshot.ref);
|
||||||
res.status(200).json({ ok: true });
|
res.status(200).json({ok: true});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(403).json({ ok: false });
|
res.status(403).json({ok: false});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function patch(req: NextApiRequest, res: NextApiResponse) {
|
async function patch(req: NextApiRequest, res: NextApiResponse) {
|
||||||
if (!req.session.user) {
|
if (!req.session.user) {
|
||||||
res.status(401).json({ ok: false });
|
res.status(401).json({ok: false});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { id } = req.query as { id: string };
|
const {id} = req.query as {id: string};
|
||||||
const body = req.body as Ticket;
|
const body = req.body as Ticket;
|
||||||
|
|
||||||
const snapshot = await getDoc(doc(db, "tickets", id));
|
const snapshot = await getDoc(doc(db, "tickets", id));
|
||||||
|
|
||||||
const user = req.session.user;
|
const user = req.session.user;
|
||||||
if (user.type === "admin" || user.type === "developer") {
|
if (user.type === "admin" || user.type === "developer") {
|
||||||
const data = snapshot.data() as Ticket;
|
const data = snapshot.data() as Ticket;
|
||||||
await setDoc(snapshot.ref, body, { merge: true });
|
await setDoc(snapshot.ref, body, {merge: true});
|
||||||
try {
|
try {
|
||||||
// send email if the status actually changed to completed
|
// send email if the status actually changed to completed
|
||||||
if(data.status !== req.body.status && req.body.status === 'completed') {
|
if (data.status !== req.body.status && req.body.status === "completed") {
|
||||||
await sendEmail(
|
await sendEmail(
|
||||||
"ticketStatusCompleted",
|
"ticketStatusCompleted",
|
||||||
{
|
{
|
||||||
id,
|
id,
|
||||||
subject: body.subject,
|
subject: body.subject,
|
||||||
reporter: body.reporter,
|
reporter: body.reporter,
|
||||||
date: moment(body.date).format("DD/MM/YYYY - HH:mm"),
|
date: moment(body.date).format("DD/MM/YYYY - HH:mm"),
|
||||||
type: TicketTypeLabel[body.type],
|
type: TicketTypeLabel[body.type],
|
||||||
reportedFrom: body.reportedFrom,
|
reportedFrom: body.reportedFrom,
|
||||||
description: body.description,
|
description: body.description,
|
||||||
},
|
environment: process.env.ENVIRONMENT,
|
||||||
[data.reporter.email],
|
},
|
||||||
`Ticket ${id}: ${data.subject}`,
|
[data.reporter.email],
|
||||||
);
|
`Ticket ${id}: ${data.subject}`,
|
||||||
}
|
);
|
||||||
} catch(err) {
|
}
|
||||||
console.error(err);
|
} catch (err) {
|
||||||
// doesnt matter if the email fails
|
console.error(err);
|
||||||
}
|
// doesnt matter if the email fails
|
||||||
res.status(200).json({ ok: true });
|
}
|
||||||
return;
|
res.status(200).json({ok: true});
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
res.status(403).json({ ok: false });
|
res.status(403).json({ok: false});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,110 +1,103 @@
|
|||||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||||
import { sendEmail } from "@/email";
|
import {sendEmail} from "@/email";
|
||||||
import { app } from "@/firebase";
|
import {app} from "@/firebase";
|
||||||
import { Ticket, TicketTypeLabel, TicketWithCorporate } from "@/interfaces/ticket";
|
import {Ticket, TicketTypeLabel, TicketWithCorporate} from "@/interfaces/ticket";
|
||||||
import { sessionOptions } from "@/lib/session";
|
import {sessionOptions} from "@/lib/session";
|
||||||
import {
|
import {collection, doc, getDocs, getFirestore, setDoc, where, query} from "firebase/firestore";
|
||||||
collection,
|
import {withIronSessionApiRoute} from "iron-session/next";
|
||||||
doc,
|
|
||||||
getDocs,
|
|
||||||
getFirestore,
|
|
||||||
setDoc,
|
|
||||||
where,
|
|
||||||
query,
|
|
||||||
} from "firebase/firestore";
|
|
||||||
import { withIronSessionApiRoute } from "iron-session/next";
|
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import type { NextApiRequest, NextApiResponse } from "next";
|
import type {NextApiRequest, NextApiResponse} from "next";
|
||||||
import ShortUniqueId from "short-unique-id";
|
import ShortUniqueId from "short-unique-id";
|
||||||
import { Group, CorporateUser } from "@/interfaces/user";
|
import {Group, CorporateUser} from "@/interfaces/user";
|
||||||
|
|
||||||
const db = getFirestore(app);
|
const db = getFirestore(app);
|
||||||
|
|
||||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||||
|
|
||||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||||
// due to integration with the homepage the POST request should be public
|
// due to integration with the homepage the POST request should be public
|
||||||
if (req.method === "POST") {
|
if (req.method === "POST") {
|
||||||
await post(req, res);
|
await post(req, res);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// specific logic for the preflight request
|
// specific logic for the preflight request
|
||||||
if (req.method === "OPTIONS") {
|
if (req.method === "OPTIONS") {
|
||||||
res.status(200).end();
|
res.status(200).end();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!req.session.user) {
|
if (!req.session.user) {
|
||||||
res.status(401).json({ ok: false });
|
res.status(401).json({ok: false});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (req.method === "GET") {
|
if (req.method === "GET") {
|
||||||
await get(req, res);
|
await get(req, res);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function get(req: NextApiRequest, res: NextApiResponse) {
|
async function get(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const snapshot = await getDocs(collection(db, "tickets"));
|
const snapshot = await getDocs(collection(db, "tickets"));
|
||||||
|
|
||||||
const docs = snapshot.docs.map((doc) => ({
|
const docs = snapshot.docs.map((doc) => ({
|
||||||
id: doc.id,
|
id: doc.id,
|
||||||
...doc.data(),
|
...doc.data(),
|
||||||
})) as Ticket[];
|
})) as Ticket[];
|
||||||
|
|
||||||
// fetch all groups for these users
|
// fetch all groups for these users
|
||||||
|
|
||||||
const reporters = [...new Set(docs.map((d) => d.reporter.id).filter((id) => id))];
|
const reporters = [...new Set(docs.map((d) => d.reporter.id).filter((id) => id))];
|
||||||
|
|
||||||
const groupsSnapshot = await getDocs(query(collection(db, "groups"), where("participants", "array-contains-any", reporters)));
|
const groupsSnapshot = await getDocs(query(collection(db, "groups"), where("participants", "array-contains-any", reporters)));
|
||||||
const groups = groupsSnapshot.docs.map((doc) => doc.data()) as Group[];
|
const groups = groupsSnapshot.docs.map((doc) => doc.data()) as Group[];
|
||||||
|
|
||||||
// based on the admin of each group, verify if it exists and it's of type corporate
|
// based on the admin of each group, verify if it exists and it's of type corporate
|
||||||
const groupsAdmins = [...new Set(groups.map((g) => g.admin).filter((id) => id))];
|
const groupsAdmins = [...new Set(groups.map((g) => g.admin).filter((id) => id))];
|
||||||
const adminsSnapshot = await getDocs(query(collection(db, "users"), where("id", "in", groupsAdmins), where("type", "==", "corporate")));
|
const adminsSnapshot = await getDocs(query(collection(db, "users"), where("id", "in", groupsAdmins), where("type", "==", "corporate")));
|
||||||
const admins = adminsSnapshot.docs.map((doc) => doc.data());
|
const admins = adminsSnapshot.docs.map((doc) => doc.data());
|
||||||
|
|
||||||
const docsWithAdmins = docs.map((d) => {
|
const docsWithAdmins = docs.map((d) => {
|
||||||
const group = groups.find((g) => g.participants.includes(d.reporter.id));
|
const group = groups.find((g) => g.participants.includes(d.reporter.id));
|
||||||
const admin = admins.find((a) => a.id === group?.admin) as CorporateUser;
|
const admin = admins.find((a) => a.id === group?.admin) as CorporateUser;
|
||||||
|
|
||||||
if(admin) {
|
if (admin) {
|
||||||
return {
|
return {
|
||||||
...d,
|
...d,
|
||||||
corporate: admin.corporateInformation?.companyInformation?.name,
|
corporate: admin.corporateInformation?.companyInformation?.name,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return d;
|
return d;
|
||||||
}) as TicketWithCorporate[];
|
}) as TicketWithCorporate[];
|
||||||
|
|
||||||
res.status(200).json(docsWithAdmins);
|
res.status(200).json(docsWithAdmins);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const body = req.body as Ticket;
|
const body = req.body as Ticket;
|
||||||
|
|
||||||
const shortUID = new ShortUniqueId();
|
const shortUID = new ShortUniqueId();
|
||||||
const id = body.id || shortUID.randomUUID(8);
|
const id = body.id || shortUID.randomUUID(8);
|
||||||
await setDoc(doc(db, "tickets", id), body);
|
await setDoc(doc(db, "tickets", id), body);
|
||||||
res.status(200).json({ ok: true });
|
res.status(200).json({ok: true});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await sendEmail(
|
await sendEmail(
|
||||||
"submittedFeedback",
|
"submittedFeedback",
|
||||||
{
|
{
|
||||||
id,
|
id,
|
||||||
subject: body.subject,
|
subject: body.subject,
|
||||||
reporter: body.reporter,
|
reporter: body.reporter,
|
||||||
date: moment(body.date).format("DD/MM/YYYY - HH:mm"),
|
date: moment(body.date).format("DD/MM/YYYY - HH:mm"),
|
||||||
type: TicketTypeLabel[body.type],
|
type: TicketTypeLabel[body.type],
|
||||||
reportedFrom: body.reportedFrom,
|
reportedFrom: body.reportedFrom,
|
||||||
description: body.description,
|
description: body.description,
|
||||||
},
|
environment: process.env.ENVIRONMENT,
|
||||||
[body.reporter.email],
|
},
|
||||||
`Ticket ${id}: ${body.subject}`
|
[body.reporter.email],
|
||||||
);
|
`Ticket ${id}: ${body.subject}`,
|
||||||
} catch (e) {
|
);
|
||||||
console.log(e);
|
} catch (e) {
|
||||||
}
|
console.log(e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user