Compare commits
19 Commits
feature/EN
...
ENCOA-38/a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
85b94512e9 | ||
|
|
906646ebce | ||
|
|
96108a4958 | ||
|
|
fb449f2054 | ||
|
|
d5ee3d9519 | ||
|
|
4e20ec6575 | ||
|
|
836b674076 | ||
|
|
5086c6fb09 | ||
|
|
489c9c3b7e | ||
|
|
e3ded29e77 | ||
|
|
16419a5584 | ||
|
|
3e3b24cc30 | ||
|
|
841698ba10 | ||
|
|
d50904611c | ||
|
|
e77fd16d26 | ||
|
|
649f24e4ae | ||
|
|
2f0cbfe74e | ||
|
|
d022bd078a | ||
|
|
c18afee9ad |
@@ -47,7 +47,6 @@
|
||||
"next": "13.1.6",
|
||||
"nodemailer": "^6.9.5",
|
||||
"nodemailer-express-handlebars": "^6.1.0",
|
||||
"paymob-react": "git+https://github.com/tiago-ecrop/paymob-react-oman.git",
|
||||
"primeicons": "^6.0.1",
|
||||
"primereact": "^9.2.3",
|
||||
"qrcode": "^1.5.3",
|
||||
|
||||
@@ -16,9 +16,13 @@ function Question({
|
||||
}: MultipleChoiceQuestion & {userSolution: string | undefined; onSelectOption?: (option: string) => void; showSolution?: boolean}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-10">
|
||||
<span className="">
|
||||
{id} - {prompt}
|
||||
</span>
|
||||
{isNaN(Number(id)) ? (
|
||||
<span className="">{prompt}</span>
|
||||
) : (
|
||||
<span className="">
|
||||
{id} - {prompt}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-4 justify-between">
|
||||
{variant === "image" &&
|
||||
options.map((option) => (
|
||||
|
||||
@@ -20,15 +20,6 @@ interface Props {
|
||||
|
||||
export default function PaymobPayment({user, price, setIsPaymentLoading, currency, duration, duration_unit, onSuccess}: Props) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
|
||||
const [firstName, setFirstName] = useState(user.name.split(" ")[0]);
|
||||
const [lastName, setLastName] = useState([...user.name.split(" ")].pop());
|
||||
const [street, setStreet] = useState("");
|
||||
const [apartment, setApartment] = useState("");
|
||||
const [building, setBuilding] = useState("");
|
||||
const [state, setState] = useState("");
|
||||
const [floor, setFloor] = useState("");
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
@@ -50,16 +41,16 @@ export default function PaymobPayment({user, price, setIsPaymentLoading, currenc
|
||||
},
|
||||
},
|
||||
billing_data: {
|
||||
apartment: apartment || "N/A",
|
||||
building: building || "N/A",
|
||||
apartment: "N/A",
|
||||
building: "N/A",
|
||||
country: user.demographicInformation?.country || "N/A",
|
||||
email: user.email,
|
||||
first_name: user.name.split(" ")[0],
|
||||
last_name: [...user.name.split(" ")].pop() || "N/A",
|
||||
floor: floor || "N/A",
|
||||
floor: "N/A",
|
||||
phone_number: user.demographicInformation?.phone || "N/A",
|
||||
state: state || "N/A",
|
||||
street: street || "N/A",
|
||||
state: "N/A",
|
||||
street: "N/A",
|
||||
},
|
||||
extras: {
|
||||
userID: user.id,
|
||||
@@ -71,7 +62,6 @@ export default function PaymobPayment({user, price, setIsPaymentLoading, currenc
|
||||
const response = await axios.post<{iframeURL: string}>(`/api/paymob`, paymentIntention);
|
||||
|
||||
router.push(response.data.iframeURL);
|
||||
setIsModalOpen(false);
|
||||
} catch (error) {
|
||||
console.error("Error starting card payment process:", error);
|
||||
}
|
||||
@@ -79,27 +69,7 @@ export default function PaymobPayment({user, price, setIsPaymentLoading, currenc
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal isOpen={isModalOpen} title="Billing Data" onClose={() => setIsModalOpen(false)}>
|
||||
<div className="flex flex-col gap-4 mt-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input label="First Name" value={firstName} onChange={setFirstName} type="text" name="firstName" />
|
||||
<Input label="Last Name" value={lastName} onChange={setLastName} type="text" name="lastName" />
|
||||
</div>
|
||||
<div className="grid grid-cols-3 -md:grid-cols-1 gap-4">
|
||||
<Input label="State" value={state} onChange={setState} type="text" name="state" />
|
||||
<Input label="Street" value={street} onChange={setStreet} type="text" name="street" />
|
||||
<Input label="Building" value={building} onChange={setBuilding} type="text" name="building" />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input label="Floor" value={floor} onChange={setFloor} type="text" name="floor" />
|
||||
<Input label="Apartment" value={apartment} onChange={setApartment} type="text" name="apartment" />
|
||||
</div>
|
||||
<Button className="w-full max-w-[200px] self-end mt-4" disabled={!firstName || !lastName} onClick={handleCardPayment}>
|
||||
Complete Payment
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
<Button isLoading={isLoading} onClick={() => setIsModalOpen(true)}>
|
||||
<Button isLoading={isLoading} onClick={handleCardPayment}>
|
||||
Select
|
||||
</Button>
|
||||
</>
|
||||
|
||||
@@ -27,9 +27,13 @@ function Question({
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<span>
|
||||
{id} - {prompt}
|
||||
</span>
|
||||
{isNaN(Number(id)) ? (
|
||||
<span className="">{prompt}</span>
|
||||
) : (
|
||||
<span className="">
|
||||
{id} - {prompt}
|
||||
</span>
|
||||
)}
|
||||
<div className="grid grid-cols-4 gap-4 place-items-center">
|
||||
{variant === "image" &&
|
||||
options.map((option) => (
|
||||
|
||||
@@ -1,55 +1,56 @@
|
||||
export interface TokenSuccess {
|
||||
scope: string;
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
app_id: string;
|
||||
expires_in: number;
|
||||
nonce: string;
|
||||
scope: string;
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
app_id: string;
|
||||
expires_in: number;
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
export interface TokenError {
|
||||
error: string;
|
||||
error_description: string;
|
||||
error: string;
|
||||
error_description: string;
|
||||
}
|
||||
|
||||
export interface Package {
|
||||
id: string;
|
||||
currency: string;
|
||||
duration: number;
|
||||
duration_unit: DurationUnit;
|
||||
price: number;
|
||||
id: string;
|
||||
currency: string;
|
||||
duration: number;
|
||||
duration_unit: DurationUnit;
|
||||
price: number;
|
||||
}
|
||||
|
||||
export interface Discount {
|
||||
id: string;
|
||||
percentage: number;
|
||||
domain: string;
|
||||
id: string;
|
||||
percentage: number;
|
||||
domain: string;
|
||||
validUntil?: Date;
|
||||
}
|
||||
|
||||
export type DurationUnit = "weeks" | "days" | "months" | "years";
|
||||
|
||||
export interface Payment {
|
||||
id: string;
|
||||
corporate: string;
|
||||
agent?: string;
|
||||
agentCommission: number;
|
||||
agentValue: number;
|
||||
currency: string;
|
||||
value: number;
|
||||
isPaid: boolean;
|
||||
date: Date | string;
|
||||
corporateTransfer?: string;
|
||||
commissionTransfer?: string;
|
||||
id: string;
|
||||
corporate: string;
|
||||
agent?: string;
|
||||
agentCommission: number;
|
||||
agentValue: number;
|
||||
currency: string;
|
||||
value: number;
|
||||
isPaid: boolean;
|
||||
date: Date | string;
|
||||
corporateTransfer?: string;
|
||||
commissionTransfer?: string;
|
||||
}
|
||||
|
||||
export interface PaypalPayment {
|
||||
orderId: string;
|
||||
userId: string;
|
||||
status: string;
|
||||
createdAt: Date;
|
||||
value: number;
|
||||
currency: string;
|
||||
subscriptionDuration: number;
|
||||
subscriptionDurationUnit: DurationUnit;
|
||||
subscriptionExpirationDate: Date;
|
||||
orderId: string;
|
||||
userId: string;
|
||||
status: string;
|
||||
createdAt: Date;
|
||||
value: number;
|
||||
currency: string;
|
||||
subscriptionDuration: number;
|
||||
subscriptionDurationUnit: DurationUnit;
|
||||
subscriptionExpirationDate: Date;
|
||||
}
|
||||
|
||||
@@ -7,336 +7,301 @@ import useCodes from "@/hooks/useCodes";
|
||||
import useDiscounts from "@/hooks/useDiscounts";
|
||||
import useUser from "@/hooks/useUser";
|
||||
import useUsers from "@/hooks/useUsers";
|
||||
import { Discount } from "@/interfaces/paypal";
|
||||
import { Code, User } from "@/interfaces/user";
|
||||
import { USER_TYPE_LABELS } from "@/resources/user";
|
||||
import {
|
||||
createColumnHelper,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table";
|
||||
import {Discount} from "@/interfaces/paypal";
|
||||
import {Code, User} from "@/interfaces/user";
|
||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
||||
import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import moment from "moment";
|
||||
import { useEffect, useState } from "react";
|
||||
import { BsPencil, BsTrash } from "react-icons/bs";
|
||||
import { toast } from "react-toastify";
|
||||
import {useEffect, useState} from "react";
|
||||
import ReactDatePicker from "react-datepicker";
|
||||
import {BsPencil, BsTrash} from "react-icons/bs";
|
||||
import {toast} from "react-toastify";
|
||||
|
||||
const columnHelper = createColumnHelper<Discount>();
|
||||
|
||||
const DiscountCreator = ({
|
||||
discount,
|
||||
onClose,
|
||||
}: {
|
||||
discount?: Discount;
|
||||
onClose: () => void;
|
||||
}) => {
|
||||
const [percentage, setPercentage] = useState(discount?.percentage);
|
||||
const [domain, setDomain] = useState(discount?.domain);
|
||||
const DiscountCreator = ({discount, onClose}: {discount?: Discount; onClose: () => void}) => {
|
||||
const [percentage, setPercentage] = useState(discount?.percentage);
|
||||
const [domain, setDomain] = useState(discount?.domain);
|
||||
const [validUntil, setValidUntil] = useState(discount?.validUntil);
|
||||
|
||||
const submit = async () => {
|
||||
const body = { percentage, domain };
|
||||
const submit = async () => {
|
||||
const body = {percentage, domain, validUntil: validUntil?.toISOString() || undefined};
|
||||
|
||||
if (discount) {
|
||||
return axios
|
||||
.patch(`/api/discounts/${discount.id}`, body)
|
||||
.then(() => {
|
||||
toast.success("Discount has been edited successfully!");
|
||||
onClose();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong, please try again later!");
|
||||
});
|
||||
}
|
||||
if (discount) {
|
||||
return axios
|
||||
.patch(`/api/discounts/${discount.id}`, body)
|
||||
.then(() => {
|
||||
toast.success("Discount has been edited successfully!");
|
||||
onClose();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong, please try again later!");
|
||||
});
|
||||
}
|
||||
|
||||
return axios
|
||||
.post(`/api/discounts`, body)
|
||||
.then(() => {
|
||||
toast.success("New discount has been created successfully!");
|
||||
onClose();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong, please try again later!");
|
||||
});
|
||||
};
|
||||
return axios
|
||||
.post(`/api/discounts`, body)
|
||||
.then(() => {
|
||||
toast.success("New discount has been created successfully!");
|
||||
onClose();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong, please try again later!");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-8 py-8">
|
||||
<div className="w-full grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div className="flex flex-col gap-3">
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Domain *
|
||||
</label>
|
||||
<div className="flex gap-4 items-center">
|
||||
<Input
|
||||
defaultValue={domain}
|
||||
placeholder="encoach.com"
|
||||
name="domain"
|
||||
type="text"
|
||||
onChange={(e) => setDomain(e.replaceAll("@", ""))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Percentage (in %) *
|
||||
</label>
|
||||
<div className="flex gap-4 items-center">
|
||||
<Input
|
||||
defaultValue={percentage}
|
||||
placeholder="20"
|
||||
name="percentage"
|
||||
type="number"
|
||||
onChange={(e) => setPercentage(parseFloat(e))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full justify-end items-center gap-8 mt-8">
|
||||
<Button
|
||||
variant="outline"
|
||||
color="red"
|
||||
className="w-full max-w-[200px]"
|
||||
onClick={onClose}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
className="w-full max-w-[200px]"
|
||||
onClick={submit}
|
||||
disabled={!percentage || !domain}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className="flex flex-col gap-8 py-8">
|
||||
<div className="w-full grid grid-cols-1 gap-8">
|
||||
<div className="flex flex-col gap-3">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Domain *</label>
|
||||
<div className="flex gap-4 items-center">
|
||||
<Input
|
||||
defaultValue={domain}
|
||||
placeholder="encoach.com"
|
||||
name="domain"
|
||||
type="text"
|
||||
onChange={(e) => setDomain(e.replaceAll("@", ""))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Percentage (in %) *</label>
|
||||
<div className="flex gap-4 items-center">
|
||||
<Input
|
||||
defaultValue={percentage}
|
||||
placeholder="20"
|
||||
name="percentage"
|
||||
type="number"
|
||||
onChange={(e) => setPercentage(parseFloat(e))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3 w-full">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Valid Until</label>
|
||||
<div className="flex gap-4 items-center w-full">
|
||||
<ReactDatePicker
|
||||
wrapperClassName="w-full z-[900]"
|
||||
calendarClassName="z-[900]"
|
||||
popperClassName="z-[900]"
|
||||
isClearable
|
||||
className={clsx(
|
||||
"flex min-h-[70px] w-full cursor-pointer justify-center rounded-full border p-6 text-sm font-normal focus:outline-none",
|
||||
"hover:border-mti-purple tooltip",
|
||||
"transition duration-300 ease-in-out",
|
||||
)}
|
||||
filterDate={(date) => moment(date).isAfter(new Date())}
|
||||
dateFormat="dd/MM/yyyy"
|
||||
selected={validUntil}
|
||||
onChange={(date) => setValidUntil(date ? moment(date).endOf("day").toDate() : undefined)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full justify-end items-center gap-8 mt-8">
|
||||
<Button variant="outline" color="red" className="w-full max-w-[200px]" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button className="w-full max-w-[200px]" onClick={submit} disabled={!percentage || !domain}>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default function DiscountList({ user }: { user: User }) {
|
||||
const [selectedDiscounts, setSelectedDiscounts] = useState<string[]>([]);
|
||||
export default function DiscountList({user}: {user: User}) {
|
||||
const [selectedDiscounts, setSelectedDiscounts] = useState<string[]>([]);
|
||||
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [editingDiscount, setEditingDiscount] = useState<Discount>();
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [editingDiscount, setEditingDiscount] = useState<Discount>();
|
||||
|
||||
const [filteredDiscounts, setFilteredDiscounts] = useState<Discount[]>([]);
|
||||
const [filteredDiscounts, setFilteredDiscounts] = useState<Discount[]>([]);
|
||||
|
||||
const { users } = useUsers();
|
||||
const { discounts, reload } = useDiscounts();
|
||||
const {users} = useUsers();
|
||||
const {discounts, reload} = useDiscounts();
|
||||
|
||||
useEffect(() => {
|
||||
setFilteredDiscounts(discounts);
|
||||
}, [discounts]);
|
||||
useEffect(() => {
|
||||
setFilteredDiscounts(discounts);
|
||||
}, [discounts]);
|
||||
|
||||
const toggleDiscount = (id: string) => {
|
||||
setSelectedDiscounts((prev) =>
|
||||
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
|
||||
);
|
||||
};
|
||||
const toggleDiscount = (id: string) => {
|
||||
setSelectedDiscounts((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
|
||||
};
|
||||
|
||||
const toggleAllDiscounts = (checked: boolean) => {
|
||||
if (checked)
|
||||
return setSelectedDiscounts(filteredDiscounts.map((x) => x.id));
|
||||
const toggleAllDiscounts = (checked: boolean) => {
|
||||
if (checked) return setSelectedDiscounts(filteredDiscounts.map((x) => x.id));
|
||||
|
||||
return setSelectedDiscounts([]);
|
||||
};
|
||||
return setSelectedDiscounts([]);
|
||||
};
|
||||
|
||||
const deleteDiscounts = async (discounts: string[]) => {
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to delete these ${discounts.length} discount(s)?`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
const deleteDiscounts = async (discounts: string[]) => {
|
||||
if (!confirm(`Are you sure you want to delete these ${discounts.length} discount(s)?`)) return;
|
||||
|
||||
const params = new URLSearchParams();
|
||||
discounts.forEach((code) => params.append("discount", code));
|
||||
const params = new URLSearchParams();
|
||||
discounts.forEach((code) => params.append("discount", code));
|
||||
|
||||
axios
|
||||
.delete(`/api/discounts?${params.toString()}`)
|
||||
.then(() => toast.success(`Deleted the discount(s)!`))
|
||||
.catch((reason) => {
|
||||
if (reason.response.status === 404) {
|
||||
toast.error("Discount not found!");
|
||||
return;
|
||||
}
|
||||
axios
|
||||
.delete(`/api/discounts?${params.toString()}`)
|
||||
.then(() => toast.success(`Deleted the discount(s)!`))
|
||||
.catch((reason) => {
|
||||
if (reason.response.status === 404) {
|
||||
toast.error("Discount not found!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (reason.response.status === 403) {
|
||||
toast.error("You do not have permission to delete this discount!");
|
||||
return;
|
||||
}
|
||||
if (reason.response.status === 403) {
|
||||
toast.error("You do not have permission to delete this discount!");
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error("Something went wrong, please try again later.");
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
toast.error("Something went wrong, please try again later.");
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
|
||||
const deleteDiscount = async (discount: Discount) => {
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to delete this "${discount.id}" discount?`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
const deleteDiscount = async (discount: Discount) => {
|
||||
if (!confirm(`Are you sure you want to delete this "${discount.id}" discount?`)) return;
|
||||
|
||||
axios
|
||||
.delete(`/api/discounts/${discount.id}`)
|
||||
.then(() => toast.success(`Deleted the "${discount.id}" discount`))
|
||||
.catch((reason) => {
|
||||
if (reason.response.status === 404) {
|
||||
toast.error("Code not found!");
|
||||
return;
|
||||
}
|
||||
axios
|
||||
.delete(`/api/discounts/${discount.id}`)
|
||||
.then(() => toast.success(`Deleted the "${discount.id}" discount`))
|
||||
.catch((reason) => {
|
||||
if (reason.response.status === 404) {
|
||||
toast.error("Code not found!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (reason.response.status === 403) {
|
||||
toast.error("You do not have permission to delete this discount!");
|
||||
return;
|
||||
}
|
||||
if (reason.response.status === 403) {
|
||||
toast.error("You do not have permission to delete this discount!");
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error("Something went wrong, please try again later.");
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
toast.error("Something went wrong, please try again later.");
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
|
||||
const defaultColumns = [
|
||||
columnHelper.accessor("id", {
|
||||
id: "id",
|
||||
header: () => (
|
||||
<Checkbox
|
||||
disabled={filteredDiscounts.length === 0}
|
||||
isChecked={
|
||||
selectedDiscounts.length === filteredDiscounts.length &&
|
||||
filteredDiscounts.length > 0
|
||||
}
|
||||
onChange={(checked) => toggleAllDiscounts(checked)}
|
||||
>
|
||||
{""}
|
||||
</Checkbox>
|
||||
),
|
||||
cell: (info) => (
|
||||
<Checkbox
|
||||
isChecked={selectedDiscounts.includes(info.getValue())}
|
||||
onChange={() => toggleDiscount(info.getValue())}
|
||||
>
|
||||
{""}
|
||||
</Checkbox>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("id", {
|
||||
header: "ID",
|
||||
cell: (info) => info.getValue(),
|
||||
}),
|
||||
columnHelper.accessor("domain", {
|
||||
header: "Domain",
|
||||
cell: (info) => `@${info.getValue()}`,
|
||||
}),
|
||||
columnHelper.accessor("percentage", {
|
||||
header: "Percentage",
|
||||
cell: (info) => `${info.getValue()}%`,
|
||||
}),
|
||||
{
|
||||
header: "",
|
||||
id: "actions",
|
||||
cell: ({ row }: { row: { original: Discount } }) => {
|
||||
return (
|
||||
<div className="flex gap-4">
|
||||
<div
|
||||
data-tip="Delete"
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => {
|
||||
setEditingDiscount(row.original);
|
||||
}}
|
||||
>
|
||||
<BsPencil className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
<div
|
||||
data-tip="Delete"
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => deleteDiscount(row.original)}
|
||||
>
|
||||
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
const defaultColumns = [
|
||||
columnHelper.accessor("id", {
|
||||
id: "id",
|
||||
header: () => (
|
||||
<Checkbox
|
||||
disabled={filteredDiscounts.length === 0}
|
||||
isChecked={selectedDiscounts.length === filteredDiscounts.length && filteredDiscounts.length > 0}
|
||||
onChange={(checked) => toggleAllDiscounts(checked)}>
|
||||
{""}
|
||||
</Checkbox>
|
||||
),
|
||||
cell: (info) => (
|
||||
<Checkbox isChecked={selectedDiscounts.includes(info.getValue())} onChange={() => toggleDiscount(info.getValue())}>
|
||||
{""}
|
||||
</Checkbox>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("id", {
|
||||
header: "ID",
|
||||
cell: (info) => info.getValue(),
|
||||
}),
|
||||
columnHelper.accessor("domain", {
|
||||
header: "Domain",
|
||||
cell: (info) => `@${info.getValue()}`,
|
||||
}),
|
||||
columnHelper.accessor("percentage", {
|
||||
header: "Percentage",
|
||||
cell: (info) => `${info.getValue()}%`,
|
||||
}),
|
||||
columnHelper.accessor("validUntil", {
|
||||
header: "Valid Until",
|
||||
cell: (info) => (info.getValue() ? moment(info.getValue()).format("DD/MM/YYYY") : ""),
|
||||
}),
|
||||
{
|
||||
header: "",
|
||||
id: "actions",
|
||||
cell: ({row}: {row: {original: Discount}}) => {
|
||||
return (
|
||||
<div className="flex gap-4">
|
||||
<div
|
||||
data-tip="Delete"
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => {
|
||||
setEditingDiscount(row.original);
|
||||
}}>
|
||||
<BsPencil className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
<div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deleteDiscount(row.original)}>
|
||||
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const table = useReactTable({
|
||||
data: filteredDiscounts,
|
||||
columns: defaultColumns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
const table = useReactTable({
|
||||
data: filteredDiscounts,
|
||||
columns: defaultColumns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
|
||||
const closeModal = () => {
|
||||
setIsCreating(false);
|
||||
setEditingDiscount(undefined);
|
||||
reload();
|
||||
};
|
||||
const closeModal = () => {
|
||||
setIsCreating(false);
|
||||
setEditingDiscount(undefined);
|
||||
reload();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
isOpen={isCreating || !!editingDiscount}
|
||||
onClose={closeModal}
|
||||
title={
|
||||
editingDiscount ? `Editing ${editingDiscount.id}` : "New Discount"
|
||||
}
|
||||
>
|
||||
<DiscountCreator onClose={closeModal} discount={editingDiscount} />
|
||||
</Modal>
|
||||
<div className="flex items-center justify-end pb-4 pt-1">
|
||||
<div className="flex gap-4 items-center">
|
||||
<span>{selectedDiscounts.length} code(s) selected</span>
|
||||
<Button
|
||||
disabled={selectedDiscounts.length === 0}
|
||||
variant="outline"
|
||||
color="red"
|
||||
className="!py-1 px-10"
|
||||
onClick={() => deleteDiscounts(selectedDiscounts)}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
|
||||
<thead>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<th className="p-4 text-left" key={header.id}>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody className="px-2">
|
||||
{table.getRowModel().rows.map((row) => (
|
||||
<tr
|
||||
className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2"
|
||||
key={row.id}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<td className="px-4 py-2" key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<button
|
||||
onClick={() => setIsCreating(true)}
|
||||
className="w-full py-2 bg-mti-purple-light hover:bg-mti-purple transition ease-in-out duration-300 text-white"
|
||||
>
|
||||
New Discount
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
isOpen={isCreating || !!editingDiscount}
|
||||
onClose={closeModal}
|
||||
title={editingDiscount ? `Editing ${editingDiscount.id}` : "New Discount"}>
|
||||
<DiscountCreator onClose={closeModal} discount={editingDiscount} />
|
||||
</Modal>
|
||||
<div className="flex items-center justify-end pb-4 pt-1">
|
||||
<div className="flex gap-4 items-center">
|
||||
<span>{selectedDiscounts.length} code(s) selected</span>
|
||||
<Button
|
||||
disabled={selectedDiscounts.length === 0}
|
||||
variant="outline"
|
||||
color="red"
|
||||
className="!py-1 px-10"
|
||||
onClick={() => deleteDiscounts(selectedDiscounts)}>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
|
||||
<thead>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<th className="p-4 text-left" key={header.id}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody className="px-2">
|
||||
{table.getRowModel().rows.map((row) => (
|
||||
<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<td className="px-4 py-2" key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<button
|
||||
onClick={() => setIsCreating(true)}
|
||||
className="w-full py-2 bg-mti-purple-light hover:bg-mti-purple transition ease-in-out duration-300 text-white">
|
||||
New Discount
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ function PackageCreator({pack, onClose}: {pack?: Package; onClose: () => void})
|
||||
const [unit, setUnit] = useState<DurationUnit>(pack?.duration_unit || "months");
|
||||
|
||||
const [price, setPrice] = useState(pack?.price || 0);
|
||||
const [currency, setCurrency] = useState<string>(pack?.currency || "EUR");
|
||||
const [currency, setCurrency] = useState<string>(pack?.currency || "OMR");
|
||||
|
||||
const submit = () => {
|
||||
(pack ? axios.patch : axios.post)(pack ? `/api/packages/${pack.id}` : "/api/packages", {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import { Module } from "@/interfaces";
|
||||
import { useEffect, useState } from "react";
|
||||
import {Module} from "@/interfaces";
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
import AbandonPopup from "@/components/AbandonPopup";
|
||||
import Layout from "@/components/High/Layout";
|
||||
@@ -12,567 +12,447 @@ import Selection from "@/exams/Selection";
|
||||
import Speaking from "@/exams/Speaking";
|
||||
import Writing from "@/exams/Writing";
|
||||
import useUser from "@/hooks/useUser";
|
||||
import { Exam, UserSolution, Variant } from "@/interfaces/exam";
|
||||
import { Stat } from "@/interfaces/user";
|
||||
import {Exam, UserSolution, Variant} from "@/interfaces/exam";
|
||||
import {Stat} from "@/interfaces/user";
|
||||
import useExamStore from "@/stores/examStore";
|
||||
import {
|
||||
evaluateSpeakingAnswer,
|
||||
evaluateWritingAnswer,
|
||||
} from "@/utils/evaluation";
|
||||
import { defaultExamUserSolutions, getExam } from "@/utils/exams";
|
||||
import {evaluateSpeakingAnswer, evaluateWritingAnswer} from "@/utils/evaluation";
|
||||
import {defaultExamUserSolutions, getExam} from "@/utils/exams";
|
||||
import axios from "axios";
|
||||
import { useRouter } from "next/router";
|
||||
import { toast, ToastContainer } from "react-toastify";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import {useRouter} from "next/router";
|
||||
import {toast, ToastContainer} from "react-toastify";
|
||||
import {v4 as uuidv4} from "uuid";
|
||||
import useSessions from "@/hooks/useSessions";
|
||||
import ShortUniqueId from "short-unique-id";
|
||||
|
||||
interface Props {
|
||||
page: "exams" | "exercises";
|
||||
page: "exams" | "exercises";
|
||||
}
|
||||
|
||||
export default function ExamPage({ page }: Props) {
|
||||
const [variant, setVariant] = useState<Variant>("full");
|
||||
const [avoidRepeated, setAvoidRepeated] = useState(false);
|
||||
const [hasBeenUploaded, setHasBeenUploaded] = useState(false);
|
||||
const [showAbandonPopup, setShowAbandonPopup] = useState(false);
|
||||
const [isEvaluationLoading, setIsEvaluationLoading] = useState(false);
|
||||
const [statsAwaitingEvaluation, setStatsAwaitingEvaluation] = useState<
|
||||
string[]
|
||||
>([]);
|
||||
const [timeSpent, setTimeSpent] = useState(0);
|
||||
export default function ExamPage({page}: Props) {
|
||||
const [variant, setVariant] = useState<Variant>("full");
|
||||
const [avoidRepeated, setAvoidRepeated] = useState(false);
|
||||
const [hasBeenUploaded, setHasBeenUploaded] = useState(false);
|
||||
const [showAbandonPopup, setShowAbandonPopup] = useState(false);
|
||||
const [isEvaluationLoading, setIsEvaluationLoading] = useState(false);
|
||||
const [statsAwaitingEvaluation, setStatsAwaitingEvaluation] = useState<string[]>([]);
|
||||
const [timeSpent, setTimeSpent] = useState(0);
|
||||
|
||||
const resetStore = useExamStore((state) => state.reset);
|
||||
const assignment = useExamStore((state) => state.assignment);
|
||||
const initialTimeSpent = useExamStore((state) => state.timeSpent);
|
||||
const resetStore = useExamStore((state) => state.reset);
|
||||
const assignment = useExamStore((state) => state.assignment);
|
||||
const initialTimeSpent = useExamStore((state) => state.timeSpent);
|
||||
|
||||
const examStore = useExamStore;
|
||||
const examStore = useExamStore;
|
||||
|
||||
const { exam, setExam } = useExamStore((state) => state);
|
||||
const { exams, setExams } = useExamStore((state) => state);
|
||||
const { sessionId, setSessionId } = useExamStore((state) => state);
|
||||
const { partIndex, setPartIndex } = useExamStore((state) => state);
|
||||
const { moduleIndex, setModuleIndex } = useExamStore((state) => state);
|
||||
const { questionIndex, setQuestionIndex } = useExamStore((state) => state);
|
||||
const { exerciseIndex, setExerciseIndex } = useExamStore((state) => state);
|
||||
const { userSolutions, setUserSolutions } = useExamStore((state) => state);
|
||||
const { showSolutions, setShowSolutions } = useExamStore((state) => state);
|
||||
const { selectedModules, setSelectedModules } = useExamStore(
|
||||
(state) => state,
|
||||
);
|
||||
const {exam, setExam} = useExamStore((state) => state);
|
||||
const {exams, setExams} = useExamStore((state) => state);
|
||||
const {sessionId, setSessionId} = useExamStore((state) => state);
|
||||
const {partIndex, setPartIndex} = useExamStore((state) => state);
|
||||
const {moduleIndex, setModuleIndex} = useExamStore((state) => state);
|
||||
const {questionIndex, setQuestionIndex} = useExamStore((state) => state);
|
||||
const {exerciseIndex, setExerciseIndex} = useExamStore((state) => state);
|
||||
const {userSolutions, setUserSolutions} = useExamStore((state) => state);
|
||||
const {showSolutions, setShowSolutions} = useExamStore((state) => state);
|
||||
const {selectedModules, setSelectedModules} = useExamStore((state) => state);
|
||||
|
||||
const { user } = useUser({ redirectTo: "/login" });
|
||||
const router = useRouter();
|
||||
const {user} = useUser({redirectTo: "/login"});
|
||||
const router = useRouter();
|
||||
|
||||
const reset = () => {
|
||||
resetStore();
|
||||
setVariant("full");
|
||||
setAvoidRepeated(false);
|
||||
setHasBeenUploaded(false);
|
||||
setShowAbandonPopup(false);
|
||||
setIsEvaluationLoading(false);
|
||||
setStatsAwaitingEvaluation([]);
|
||||
setTimeSpent(0);
|
||||
};
|
||||
const reset = () => {
|
||||
resetStore();
|
||||
setVariant("full");
|
||||
setAvoidRepeated(false);
|
||||
setHasBeenUploaded(false);
|
||||
setShowAbandonPopup(false);
|
||||
setIsEvaluationLoading(false);
|
||||
setStatsAwaitingEvaluation([]);
|
||||
setTimeSpent(0);
|
||||
};
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
const saveSession = async () => {
|
||||
console.log("Saving your session...");
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
const saveSession = async () => {
|
||||
console.log("Saving your session...");
|
||||
|
||||
await axios.post("/api/sessions", {
|
||||
id: sessionId,
|
||||
sessionId,
|
||||
date: new Date().toISOString(),
|
||||
userSolutions,
|
||||
moduleIndex,
|
||||
selectedModules,
|
||||
assignment,
|
||||
timeSpent,
|
||||
exams,
|
||||
exam,
|
||||
partIndex,
|
||||
exerciseIndex,
|
||||
questionIndex,
|
||||
user: user?.id,
|
||||
});
|
||||
};
|
||||
await axios.post("/api/sessions", {
|
||||
id: sessionId,
|
||||
sessionId,
|
||||
date: new Date().toISOString(),
|
||||
userSolutions,
|
||||
moduleIndex,
|
||||
selectedModules,
|
||||
assignment,
|
||||
timeSpent,
|
||||
exams,
|
||||
exam,
|
||||
partIndex,
|
||||
exerciseIndex,
|
||||
questionIndex,
|
||||
user: user?.id,
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(
|
||||
() => setTimeSpent((prev) => prev + initialTimeSpent),
|
||||
[initialTimeSpent],
|
||||
);
|
||||
useEffect(() => setTimeSpent((prev) => prev + initialTimeSpent), [initialTimeSpent]);
|
||||
|
||||
useEffect(() => {
|
||||
if (userSolutions.length === 0 && exams.length > 0) {
|
||||
const defaultSolutions = exams.map(defaultExamUserSolutions).flat();
|
||||
setUserSolutions(defaultSolutions);
|
||||
}
|
||||
}, [exams, setUserSolutions, userSolutions]);
|
||||
useEffect(() => {
|
||||
if (userSolutions.length === 0 && exams.length > 0) {
|
||||
const defaultSolutions = exams.map(defaultExamUserSolutions).flat();
|
||||
setUserSolutions(defaultSolutions);
|
||||
}
|
||||
}, [exams, setUserSolutions, userSolutions]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
sessionId.length > 0 &&
|
||||
userSolutions.length > 0 &&
|
||||
selectedModules.length > 0 &&
|
||||
exams.length > 0 &&
|
||||
!!exam &&
|
||||
timeSpent > 0 &&
|
||||
!showSolutions &&
|
||||
moduleIndex < selectedModules.length
|
||||
)
|
||||
saveSession();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [
|
||||
assignment,
|
||||
exam,
|
||||
exams,
|
||||
moduleIndex,
|
||||
selectedModules,
|
||||
sessionId,
|
||||
userSolutions,
|
||||
user,
|
||||
exerciseIndex,
|
||||
partIndex,
|
||||
questionIndex,
|
||||
]);
|
||||
useEffect(() => {
|
||||
if (
|
||||
sessionId.length > 0 &&
|
||||
userSolutions.length > 0 &&
|
||||
selectedModules.length > 0 &&
|
||||
exams.length > 0 &&
|
||||
!!exam &&
|
||||
timeSpent > 0 &&
|
||||
!showSolutions &&
|
||||
moduleIndex < selectedModules.length
|
||||
)
|
||||
saveSession();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [assignment, exam, exams, moduleIndex, selectedModules, sessionId, userSolutions, user, exerciseIndex, partIndex, questionIndex]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
timeSpent % 20 === 0 &&
|
||||
timeSpent > 0 &&
|
||||
moduleIndex < selectedModules.length &&
|
||||
!showSolutions
|
||||
)
|
||||
saveSession();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [timeSpent]);
|
||||
useEffect(() => {
|
||||
if (timeSpent % 20 === 0 && timeSpent > 0 && moduleIndex < selectedModules.length && !showSolutions) saveSession();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [timeSpent]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedModules.length > 0 && sessionId.length === 0) {
|
||||
const shortUID = new ShortUniqueId();
|
||||
setSessionId(shortUID.randomUUID(8));
|
||||
}
|
||||
}, [setSessionId, selectedModules, sessionId]);
|
||||
useEffect(() => {
|
||||
if (selectedModules.length > 0 && sessionId.length === 0) {
|
||||
const shortUID = new ShortUniqueId();
|
||||
setSessionId(shortUID.randomUUID(8));
|
||||
}
|
||||
}, [setSessionId, selectedModules, sessionId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (user?.type === "developer") console.log(exam);
|
||||
}, [exam, user]);
|
||||
useEffect(() => {
|
||||
if (user?.type === "developer") console.log(exam);
|
||||
}, [exam, user]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedModules.length > 0 && timeSpent === 0 && !showSolutions) {
|
||||
const timerInterval = setInterval(() => {
|
||||
setTimeSpent((prev) => prev + 1);
|
||||
}, 1000);
|
||||
useEffect(() => {
|
||||
if (selectedModules.length > 0 && timeSpent === 0 && !showSolutions) {
|
||||
const timerInterval = setInterval(() => {
|
||||
setTimeSpent((prev) => prev + 1);
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
clearInterval(timerInterval);
|
||||
};
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedModules.length]);
|
||||
return () => {
|
||||
clearInterval(timerInterval);
|
||||
};
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedModules.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (showSolutions) setModuleIndex(-1);
|
||||
}, [setModuleIndex, showSolutions]);
|
||||
useEffect(() => {
|
||||
if (showSolutions) setModuleIndex(-1);
|
||||
}, [setModuleIndex, showSolutions]);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
if (
|
||||
selectedModules.length > 0 &&
|
||||
exams.length > 0 &&
|
||||
moduleIndex < selectedModules.length
|
||||
) {
|
||||
const nextExam = exams[moduleIndex];
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
if (selectedModules.length > 0 && exams.length > 0 && moduleIndex < selectedModules.length) {
|
||||
const nextExam = exams[moduleIndex];
|
||||
|
||||
if (partIndex === -1 && nextExam.module !== "listening")
|
||||
setPartIndex(0);
|
||||
if (
|
||||
exerciseIndex === -1 &&
|
||||
!["reading", "listening"].includes(nextExam?.module)
|
||||
)
|
||||
setExerciseIndex(0);
|
||||
setExam(nextExam ? updateExamWithUserSolutions(nextExam) : undefined);
|
||||
}
|
||||
})();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedModules, moduleIndex, exams]);
|
||||
if (partIndex === -1 && nextExam.module !== "listening") setPartIndex(0);
|
||||
if (exerciseIndex === -1 && !["reading", "listening"].includes(nextExam?.module)) setExerciseIndex(0);
|
||||
setExam(nextExam ? updateExamWithUserSolutions(nextExam) : undefined);
|
||||
}
|
||||
})();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedModules, moduleIndex, exams]);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
if (selectedModules.length > 0 && exams.length === 0) {
|
||||
const examPromises = selectedModules.map((module) =>
|
||||
getExam(
|
||||
module,
|
||||
avoidRepeated,
|
||||
variant,
|
||||
user?.type === "student" || user?.type === "developer"
|
||||
? user.preferredGender
|
||||
: undefined,
|
||||
),
|
||||
);
|
||||
Promise.all(examPromises).then((values) => {
|
||||
if (values.every((x) => !!x)) {
|
||||
setExams(values.map((x) => x!));
|
||||
} else {
|
||||
toast.error("Something went wrong, please try again");
|
||||
setTimeout(router.reload, 500);
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedModules, setExams, exams]);
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
if (selectedModules.length > 0 && exams.length === 0) {
|
||||
const examPromises = selectedModules.map((module) =>
|
||||
getExam(
|
||||
module,
|
||||
avoidRepeated,
|
||||
variant,
|
||||
user?.type === "student" || user?.type === "developer" ? user.preferredGender : undefined,
|
||||
),
|
||||
);
|
||||
Promise.all(examPromises).then((values) => {
|
||||
if (values.every((x) => !!x)) {
|
||||
setExams(values.map((x) => x!));
|
||||
} else {
|
||||
toast.error("Something went wrong, please try again");
|
||||
setTimeout(router.reload, 500);
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedModules, setExams, exams]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
selectedModules.length > 0 &&
|
||||
exams.length !== 0 &&
|
||||
moduleIndex >= selectedModules.length &&
|
||||
!hasBeenUploaded &&
|
||||
!showSolutions
|
||||
) {
|
||||
const newStats: Stat[] = userSolutions.map((solution) => ({
|
||||
...solution,
|
||||
id: solution.id || uuidv4(),
|
||||
timeSpent,
|
||||
session: sessionId,
|
||||
exam: solution.exam!,
|
||||
module: solution.module!,
|
||||
user: user?.id || "",
|
||||
date: new Date().getTime(),
|
||||
isDisabled: solution.isDisabled,
|
||||
...(assignment ? { assignment: assignment.id } : {}),
|
||||
}));
|
||||
useEffect(() => {
|
||||
if (selectedModules.length > 0 && exams.length !== 0 && moduleIndex >= selectedModules.length && !hasBeenUploaded && !showSolutions) {
|
||||
const newStats: Stat[] = userSolutions.map((solution) => ({
|
||||
...solution,
|
||||
id: solution.id || uuidv4(),
|
||||
timeSpent,
|
||||
session: sessionId,
|
||||
exam: solution.exam!,
|
||||
module: solution.module!,
|
||||
user: user?.id || "",
|
||||
date: new Date().getTime(),
|
||||
isDisabled: solution.isDisabled,
|
||||
...(assignment ? {assignment: assignment.id} : {}),
|
||||
}));
|
||||
|
||||
axios
|
||||
.post<{ ok: boolean }>("/api/stats", newStats)
|
||||
.then((response) => setHasBeenUploaded(response.data.ok))
|
||||
.catch(() => setHasBeenUploaded(false));
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedModules, moduleIndex, hasBeenUploaded]);
|
||||
axios
|
||||
.post<{ok: boolean}>("/api/stats", newStats)
|
||||
.then((response) => setHasBeenUploaded(response.data.ok))
|
||||
.catch(() => setHasBeenUploaded(false));
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedModules, moduleIndex, hasBeenUploaded]);
|
||||
|
||||
useEffect(() => {
|
||||
setIsEvaluationLoading(statsAwaitingEvaluation.length !== 0);
|
||||
}, [statsAwaitingEvaluation]);
|
||||
useEffect(() => {
|
||||
setIsEvaluationLoading(statsAwaitingEvaluation.length !== 0);
|
||||
}, [statsAwaitingEvaluation]);
|
||||
|
||||
useEffect(() => {
|
||||
if (statsAwaitingEvaluation.length > 0) {
|
||||
checkIfStatsHaveBeenEvaluated(statsAwaitingEvaluation);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [statsAwaitingEvaluation]);
|
||||
useEffect(() => {
|
||||
if (statsAwaitingEvaluation.length > 0) {
|
||||
checkIfStatsHaveBeenEvaluated(statsAwaitingEvaluation);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [statsAwaitingEvaluation]);
|
||||
|
||||
const checkIfStatsHaveBeenEvaluated = (ids: string[]) => {
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
const awaitedStats = await Promise.all(
|
||||
ids.map(
|
||||
async (id) => (await axios.get<Stat>(`/api/stats/${id}`)).data,
|
||||
),
|
||||
);
|
||||
const solutionsEvaluated = awaitedStats.every((stat) =>
|
||||
stat.solutions.every((x) => x.evaluation !== null),
|
||||
);
|
||||
if (solutionsEvaluated) {
|
||||
const statsUserSolutions: UserSolution[] = awaitedStats.map(
|
||||
(stat) => ({
|
||||
id: stat.id,
|
||||
exercise: stat.exercise,
|
||||
score: stat.score,
|
||||
solutions: stat.solutions,
|
||||
type: stat.type,
|
||||
exam: stat.exam,
|
||||
module: stat.module,
|
||||
}),
|
||||
);
|
||||
const checkIfStatsHaveBeenEvaluated = (ids: string[]) => {
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
const awaitedStats = await Promise.all(ids.map(async (id) => (await axios.get<Stat>(`/api/stats/${id}`)).data));
|
||||
const solutionsEvaluated = awaitedStats.every((stat) => stat.solutions.every((x) => x.evaluation !== null));
|
||||
if (solutionsEvaluated) {
|
||||
const statsUserSolutions: UserSolution[] = awaitedStats.map((stat) => ({
|
||||
id: stat.id,
|
||||
exercise: stat.exercise,
|
||||
score: stat.score,
|
||||
solutions: stat.solutions,
|
||||
type: stat.type,
|
||||
exam: stat.exam,
|
||||
module: stat.module,
|
||||
}));
|
||||
|
||||
const updatedUserSolutions = userSolutions.map((x) => {
|
||||
const respectiveSolution = statsUserSolutions.find(
|
||||
(y) => y.exercise === x.exercise,
|
||||
);
|
||||
return respectiveSolution ? respectiveSolution : x;
|
||||
});
|
||||
const updatedUserSolutions = userSolutions.map((x) => {
|
||||
const respectiveSolution = statsUserSolutions.find((y) => y.exercise === x.exercise);
|
||||
return respectiveSolution ? respectiveSolution : x;
|
||||
});
|
||||
|
||||
setUserSolutions(updatedUserSolutions);
|
||||
return setStatsAwaitingEvaluation((prev) =>
|
||||
prev.filter((x) => !ids.includes(x)),
|
||||
);
|
||||
}
|
||||
setUserSolutions(updatedUserSolutions);
|
||||
return setStatsAwaitingEvaluation((prev) => prev.filter((x) => !ids.includes(x)));
|
||||
}
|
||||
|
||||
return checkIfStatsHaveBeenEvaluated(ids);
|
||||
} catch {
|
||||
return checkIfStatsHaveBeenEvaluated(ids);
|
||||
}
|
||||
}, 5 * 1000);
|
||||
};
|
||||
return checkIfStatsHaveBeenEvaluated(ids);
|
||||
} catch {
|
||||
return checkIfStatsHaveBeenEvaluated(ids);
|
||||
}
|
||||
}, 5 * 1000);
|
||||
};
|
||||
|
||||
const updateExamWithUserSolutions = (exam: Exam): Exam => {
|
||||
if (exam.module === "reading" || exam.module === "listening") {
|
||||
const parts = exam.parts.map((p) =>
|
||||
Object.assign(p, {
|
||||
exercises: p.exercises.map((x) =>
|
||||
Object.assign(x, {
|
||||
userSolutions: userSolutions.find((y) => x.id === y.exercise)
|
||||
?.solutions,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
return Object.assign(exam, { parts });
|
||||
}
|
||||
const updateExamWithUserSolutions = (exam: Exam): Exam => {
|
||||
if (exam.module === "reading" || exam.module === "listening") {
|
||||
const parts = exam.parts.map((p) =>
|
||||
Object.assign(p, {
|
||||
exercises: p.exercises.map((x) =>
|
||||
Object.assign(x, {
|
||||
userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
return Object.assign(exam, {parts});
|
||||
}
|
||||
|
||||
const exercises = exam.exercises.map((x) =>
|
||||
Object.assign(x, {
|
||||
userSolutions: userSolutions.find((y) => x.id === y.exercise)
|
||||
?.solutions,
|
||||
}),
|
||||
);
|
||||
return Object.assign(exam, { exercises });
|
||||
};
|
||||
const exercises = exam.exercises.map((x) =>
|
||||
Object.assign(x, {
|
||||
userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions,
|
||||
}),
|
||||
);
|
||||
return Object.assign(exam, {exercises});
|
||||
};
|
||||
|
||||
const onFinish = async (solutions: UserSolution[]) => {
|
||||
const solutionIds = solutions.map((x) => x.exercise);
|
||||
const solutionExams = solutions.map((x) => x.exam);
|
||||
const onFinish = async (solutions: UserSolution[]) => {
|
||||
const solutionIds = solutions.map((x) => x.exercise);
|
||||
const solutionExams = solutions.map((x) => x.exam);
|
||||
|
||||
let newSolutions = [...solutions];
|
||||
let newSolutions = [...solutions];
|
||||
|
||||
if (exam && !solutionExams.includes(exam.id)) return;
|
||||
if (exam && !solutionExams.includes(exam.id)) return;
|
||||
|
||||
if (
|
||||
exam &&
|
||||
(exam.module === "writing" || exam.module === "speaking") &&
|
||||
solutions.length > 0 &&
|
||||
!showSolutions
|
||||
) {
|
||||
setHasBeenUploaded(true);
|
||||
setIsEvaluationLoading(true);
|
||||
if (exam && (exam.module === "writing" || exam.module === "speaking") && solutions.length > 0 && !showSolutions) {
|
||||
setHasBeenUploaded(true);
|
||||
setIsEvaluationLoading(true);
|
||||
|
||||
const responses: UserSolution[] = (
|
||||
await Promise.all(
|
||||
exam.exercises.map(async (exercise, index) => {
|
||||
const evaluationID = uuidv4();
|
||||
if (exercise.type === "writing")
|
||||
return await evaluateWritingAnswer(
|
||||
exercise,
|
||||
index + 1,
|
||||
solutions.find((x) => x.exercise === exercise.id)!,
|
||||
evaluationID,
|
||||
);
|
||||
const responses: UserSolution[] = (
|
||||
await Promise.all(
|
||||
exam.exercises.map(async (exercise, index) => {
|
||||
const evaluationID = uuidv4();
|
||||
if (exercise.type === "writing")
|
||||
return await evaluateWritingAnswer(exercise, index + 1, solutions.find((x) => x.exercise === exercise.id)!, evaluationID);
|
||||
|
||||
if (
|
||||
exercise.type === "interactiveSpeaking" ||
|
||||
exercise.type === "speaking"
|
||||
)
|
||||
return await evaluateSpeakingAnswer(
|
||||
exercise,
|
||||
solutions.find((x) => x.exercise === exercise.id)!,
|
||||
evaluationID,
|
||||
);
|
||||
}),
|
||||
)
|
||||
).filter((x) => !!x) as UserSolution[];
|
||||
if (exercise.type === "interactiveSpeaking" || exercise.type === "speaking")
|
||||
return await evaluateSpeakingAnswer(
|
||||
exercise,
|
||||
solutions.find((x) => x.exercise === exercise.id)!,
|
||||
evaluationID,
|
||||
index === 0 ? 1 : 2,
|
||||
);
|
||||
}),
|
||||
)
|
||||
).filter((x) => !!x) as UserSolution[];
|
||||
|
||||
newSolutions = [
|
||||
...newSolutions.filter(
|
||||
(x) => !responses.map((y) => y.exercise).includes(x.exercise),
|
||||
),
|
||||
...responses,
|
||||
];
|
||||
setStatsAwaitingEvaluation((prev) => [
|
||||
...prev,
|
||||
...responses.filter((x) => !!x).map((r) => (r as any).id),
|
||||
]);
|
||||
setHasBeenUploaded(false);
|
||||
}
|
||||
newSolutions = [...newSolutions.filter((x) => !responses.map((y) => y.exercise).includes(x.exercise)), ...responses];
|
||||
setStatsAwaitingEvaluation((prev) => [...prev, ...responses.filter((x) => !!x).map((r) => (r as any).id)]);
|
||||
setHasBeenUploaded(false);
|
||||
}
|
||||
|
||||
axios.get("/api/stats/update");
|
||||
axios.get("/api/stats/update");
|
||||
|
||||
setUserSolutions([
|
||||
...userSolutions.filter((x) => !solutionIds.includes(x.exercise)),
|
||||
...newSolutions,
|
||||
]);
|
||||
setModuleIndex(moduleIndex + 1);
|
||||
setUserSolutions([...userSolutions.filter((x) => !solutionIds.includes(x.exercise)), ...newSolutions]);
|
||||
setModuleIndex(moduleIndex + 1);
|
||||
|
||||
setPartIndex(-1);
|
||||
setExerciseIndex(-1);
|
||||
setQuestionIndex(0);
|
||||
};
|
||||
setPartIndex(-1);
|
||||
setExerciseIndex(-1);
|
||||
setQuestionIndex(0);
|
||||
};
|
||||
|
||||
const aggregateScoresByModule = (): {
|
||||
module: Module;
|
||||
total: number;
|
||||
missing: number;
|
||||
correct: number;
|
||||
}[] => {
|
||||
const scores: {
|
||||
[key in Module]: { total: number; missing: number; correct: number };
|
||||
} = {
|
||||
reading: {
|
||||
total: 0,
|
||||
correct: 0,
|
||||
missing: 0,
|
||||
},
|
||||
listening: {
|
||||
total: 0,
|
||||
correct: 0,
|
||||
missing: 0,
|
||||
},
|
||||
writing: {
|
||||
total: 0,
|
||||
correct: 0,
|
||||
missing: 0,
|
||||
},
|
||||
speaking: {
|
||||
total: 0,
|
||||
correct: 0,
|
||||
missing: 0,
|
||||
},
|
||||
level: {
|
||||
total: 0,
|
||||
correct: 0,
|
||||
missing: 0,
|
||||
},
|
||||
};
|
||||
const aggregateScoresByModule = (): {
|
||||
module: Module;
|
||||
total: number;
|
||||
missing: number;
|
||||
correct: number;
|
||||
}[] => {
|
||||
const scores: {
|
||||
[key in Module]: {total: number; missing: number; correct: number};
|
||||
} = {
|
||||
reading: {
|
||||
total: 0,
|
||||
correct: 0,
|
||||
missing: 0,
|
||||
},
|
||||
listening: {
|
||||
total: 0,
|
||||
correct: 0,
|
||||
missing: 0,
|
||||
},
|
||||
writing: {
|
||||
total: 0,
|
||||
correct: 0,
|
||||
missing: 0,
|
||||
},
|
||||
speaking: {
|
||||
total: 0,
|
||||
correct: 0,
|
||||
missing: 0,
|
||||
},
|
||||
level: {
|
||||
total: 0,
|
||||
correct: 0,
|
||||
missing: 0,
|
||||
},
|
||||
};
|
||||
|
||||
userSolutions.forEach((x) => {
|
||||
const examModule =
|
||||
x.module ||
|
||||
(x.type === "writing"
|
||||
? "writing"
|
||||
: x.type === "speaking" || x.type === "interactiveSpeaking"
|
||||
? "speaking"
|
||||
: undefined);
|
||||
userSolutions.forEach((x) => {
|
||||
const examModule =
|
||||
x.module || (x.type === "writing" ? "writing" : x.type === "speaking" || x.type === "interactiveSpeaking" ? "speaking" : undefined);
|
||||
|
||||
scores[examModule!] = {
|
||||
total: scores[examModule!].total + x.score.total,
|
||||
correct: scores[examModule!].correct + x.score.correct,
|
||||
missing: scores[examModule!].missing + x.score.missing,
|
||||
};
|
||||
});
|
||||
scores[examModule!] = {
|
||||
total: scores[examModule!].total + x.score.total,
|
||||
correct: scores[examModule!].correct + x.score.correct,
|
||||
missing: scores[examModule!].missing + x.score.missing,
|
||||
};
|
||||
});
|
||||
|
||||
return Object.keys(scores)
|
||||
.filter((x) => scores[x as Module].total > 0)
|
||||
.map((x) => ({ module: x as Module, ...scores[x as Module] }));
|
||||
};
|
||||
return Object.keys(scores)
|
||||
.filter((x) => scores[x as Module].total > 0)
|
||||
.map((x) => ({module: x as Module, ...scores[x as Module]}));
|
||||
};
|
||||
|
||||
const renderScreen = () => {
|
||||
if (selectedModules.length === 0) {
|
||||
return (
|
||||
<Selection
|
||||
page={page}
|
||||
user={user!}
|
||||
disableSelection={page === "exams"}
|
||||
onStart={(modules: Module[], avoid: boolean, variant: Variant) => {
|
||||
setModuleIndex(0);
|
||||
setAvoidRepeated(avoid);
|
||||
setSelectedModules(modules);
|
||||
setVariant(variant);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const renderScreen = () => {
|
||||
if (selectedModules.length === 0) {
|
||||
return (
|
||||
<Selection
|
||||
page={page}
|
||||
user={user!}
|
||||
disableSelection={page === "exams"}
|
||||
onStart={(modules: Module[], avoid: boolean, variant: Variant) => {
|
||||
setModuleIndex(0);
|
||||
setAvoidRepeated(avoid);
|
||||
setSelectedModules(modules);
|
||||
setVariant(variant);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (moduleIndex >= selectedModules.length || moduleIndex === -1) {
|
||||
return (
|
||||
<Finish
|
||||
isLoading={isEvaluationLoading}
|
||||
user={user!}
|
||||
modules={selectedModules}
|
||||
onViewResults={(index?: number) => {
|
||||
setShowSolutions(true);
|
||||
setModuleIndex(index || 0);
|
||||
setExerciseIndex(
|
||||
["reading", "listening"].includes(exams[0].module) ? -1 : 0,
|
||||
);
|
||||
setPartIndex(exams[0].module === "listening" ? -1 : 0);
|
||||
setExam(exams[0]);
|
||||
}}
|
||||
scores={aggregateScoresByModule()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (moduleIndex >= selectedModules.length || moduleIndex === -1) {
|
||||
return (
|
||||
<Finish
|
||||
isLoading={isEvaluationLoading}
|
||||
user={user!}
|
||||
modules={selectedModules}
|
||||
onViewResults={(index?: number) => {
|
||||
setShowSolutions(true);
|
||||
setModuleIndex(index || 0);
|
||||
setExerciseIndex(["reading", "listening"].includes(exams[0].module) ? -1 : 0);
|
||||
setPartIndex(exams[0].module === "listening" ? -1 : 0);
|
||||
setExam(exams[0]);
|
||||
}}
|
||||
scores={aggregateScoresByModule()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (exam && exam.module === "reading") {
|
||||
return (
|
||||
<Reading
|
||||
exam={exam}
|
||||
onFinish={onFinish}
|
||||
showSolutions={showSolutions}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (exam && exam.module === "reading") {
|
||||
return <Reading exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
|
||||
}
|
||||
|
||||
if (exam && exam.module === "listening") {
|
||||
return (
|
||||
<Listening
|
||||
exam={exam}
|
||||
onFinish={onFinish}
|
||||
showSolutions={showSolutions}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (exam && exam.module === "listening") {
|
||||
return <Listening exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
|
||||
}
|
||||
|
||||
if (exam && exam.module === "writing") {
|
||||
return (
|
||||
<Writing
|
||||
exam={exam}
|
||||
onFinish={onFinish}
|
||||
showSolutions={showSolutions}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (exam && exam.module === "writing") {
|
||||
return <Writing exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
|
||||
}
|
||||
|
||||
if (exam && exam.module === "speaking") {
|
||||
return (
|
||||
<Speaking
|
||||
exam={exam}
|
||||
onFinish={onFinish}
|
||||
showSolutions={showSolutions}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (exam && exam.module === "speaking") {
|
||||
return <Speaking exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
|
||||
}
|
||||
|
||||
if (exam && exam.module === "level") {
|
||||
return (
|
||||
<Level exam={exam} onFinish={onFinish} showSolutions={showSolutions} />
|
||||
);
|
||||
}
|
||||
if (exam && exam.module === "level") {
|
||||
return <Level exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
|
||||
}
|
||||
|
||||
return <>Loading...</>;
|
||||
};
|
||||
return <>Loading...</>;
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ToastContainer />
|
||||
{user && (
|
||||
<Layout
|
||||
user={user}
|
||||
className="justify-between"
|
||||
focusMode={
|
||||
selectedModules.length !== 0 &&
|
||||
!showSolutions &&
|
||||
moduleIndex < selectedModules.length
|
||||
}
|
||||
onFocusLayerMouseEnter={() => setShowAbandonPopup(true)}
|
||||
>
|
||||
<>
|
||||
{renderScreen()}
|
||||
{!showSolutions && moduleIndex < selectedModules.length && (
|
||||
<AbandonPopup
|
||||
isOpen={showAbandonPopup}
|
||||
abandonPopupTitle="Leave Exercise"
|
||||
abandonPopupDescription="Are you sure you want to leave the exercise? Your progress will be saved and this exam can be resumed on the Dashboard."
|
||||
abandonConfirmButtonText="Confirm"
|
||||
onAbandon={() => {
|
||||
reset();
|
||||
}}
|
||||
onCancel={() => setShowAbandonPopup(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
</Layout>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<ToastContainer />
|
||||
{user && (
|
||||
<Layout
|
||||
user={user}
|
||||
className="justify-between"
|
||||
focusMode={selectedModules.length !== 0 && !showSolutions && moduleIndex < selectedModules.length}
|
||||
onFocusLayerMouseEnter={() => setShowAbandonPopup(true)}>
|
||||
<>
|
||||
{renderScreen()}
|
||||
{!showSolutions && moduleIndex < selectedModules.length && (
|
||||
<AbandonPopup
|
||||
isOpen={showAbandonPopup}
|
||||
abandonPopupTitle="Leave Exercise"
|
||||
abandonPopupDescription="Are you sure you want to leave the exercise? Your progress will be saved and this exam can be resumed on the Dashboard."
|
||||
abandonConfirmButtonText="Confirm"
|
||||
onAbandon={() => {
|
||||
reset();
|
||||
}}
|
||||
onCancel={() => setShowAbandonPopup(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
</Layout>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import {User} from "@/interfaces/user";
|
||||
import clsx from "clsx";
|
||||
import {capitalize} from "lodash";
|
||||
import {useEffect, useState} from "react";
|
||||
import getSymbolFromCurrency from "currency-symbol-map";
|
||||
import useInvites from "@/hooks/useInvites";
|
||||
import {BsArrowRepeat} from "react-icons/bs";
|
||||
import InviteCard from "@/components/Medium/InviteCard";
|
||||
@@ -15,6 +14,7 @@ import {useRouter} from "next/router";
|
||||
import {ToastContainer} from "react-toastify";
|
||||
import useDiscounts from "@/hooks/useDiscounts";
|
||||
import PaymobPayment from "@/components/PaymobPayment";
|
||||
import moment from "moment";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
@@ -40,7 +40,7 @@ export default function PaymentDue({user, hasExpired = false, clientID, reload}:
|
||||
if (userDiscounts.length === 0) return;
|
||||
|
||||
const biggestDiscount = [...userDiscounts].sort((a, b) => b.percentage - a.percentage).shift();
|
||||
if (!biggestDiscount) return;
|
||||
if (!biggestDiscount || (biggestDiscount.validUntil && moment(biggestDiscount.validUntil).isBefore(moment()))) return;
|
||||
|
||||
setAppliedDiscount(biggestDiscount.percentage);
|
||||
}, [discounts, user]);
|
||||
@@ -121,21 +121,18 @@ export default function PaymentDue({user, hasExpired = false, clientID, reload}:
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
{!appliedDiscount && (
|
||||
{appliedDiscount === 0 && (
|
||||
<span className="text-2xl">
|
||||
{p.price}
|
||||
{getSymbolFromCurrency(p.currency)}
|
||||
{p.price} {p.currency}
|
||||
</span>
|
||||
)}
|
||||
{appliedDiscount && (
|
||||
{appliedDiscount > 0 && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-2xl line-through">
|
||||
{p.price}
|
||||
{getSymbolFromCurrency(p.currency)}
|
||||
{p.price} {p.currency}
|
||||
</span>
|
||||
<span className="text-2xl text-mti-red-light">
|
||||
{(p.price - p.price * (appliedDiscount / 100)).toFixed(2)}
|
||||
{getSymbolFromCurrency(p.currency)}
|
||||
{(p.price - p.price * (appliedDiscount / 100)).toFixed(2)} {p.currency}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -177,8 +174,7 @@ export default function PaymentDue({user, hasExpired = false, clientID, reload}:
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<span className="text-2xl">
|
||||
{user.corporateInformation.payment.value}
|
||||
{getSymbolFromCurrency(user.corporateInformation.payment.currency)}
|
||||
{user.corporateInformation.payment.value} {user.corporateInformation.payment.currency}
|
||||
</span>
|
||||
<PaymobPayment
|
||||
key={clientID}
|
||||
|
||||
@@ -30,6 +30,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
|
||||
const audioFile = files.audio;
|
||||
const audioFileRef = ref(storage, `speaking_recordings/${fields.id}.wav`);
|
||||
const task = parseInt(fields.task.toString());
|
||||
|
||||
const binary = fs.readFileSync((audioFile as any).path).buffer;
|
||||
const snapshot = await uploadBytes(audioFileRef, binary);
|
||||
@@ -39,7 +40,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
res.status(200).json(null);
|
||||
|
||||
console.log("🌱 - Still processing");
|
||||
const backendRequest = await evaluate({answers: [{question: fields.question, answer: path}]});
|
||||
const backendRequest = await evaluate({answer: path, question: fields.question}, task);
|
||||
console.log("🌱 - Process complete");
|
||||
|
||||
const correspondingStat = await getCorrespondingStat(fields.id, 1);
|
||||
@@ -76,14 +77,14 @@ async function getCorrespondingStat(id: string, index: number): Promise<Stat> {
|
||||
return getCorrespondingStat(id, index + 1);
|
||||
}
|
||||
|
||||
async function evaluate(body: {answers: object[]}): Promise<AxiosResponse> {
|
||||
const backendRequest = await axios.post(`${process.env.BACKEND_URL}/speaking_task_3`, body, {
|
||||
async function evaluate(body: {answer: string; question: string}, task: number): Promise<AxiosResponse> {
|
||||
const backendRequest = await axios.post(`${process.env.BACKEND_URL}/speaking_task_${task}`, body, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${process.env.BACKEND_JWT}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (typeof backendRequest.data === "string") return evaluate(body);
|
||||
if (typeof backendRequest.data === "string") return evaluate(body, task);
|
||||
return backendRequest;
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (updatedUser.status || updatedUser.type === "corporate") {
|
||||
// there's no await as this does not affect the user
|
||||
propagateStatusChange(queryId, updatedUser.status);
|
||||
propagateExpiryDateChanges(queryId, user.subscriptionExpirationDate || null, updatedUser.subscriptionExpirationDate || null);
|
||||
propagateExpiryDateChanges(queryId, user.subscriptionExpirationDate, updatedUser.subscriptionExpirationDate || null);
|
||||
}
|
||||
|
||||
res.status(200).json({ok: true});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -95,4 +95,8 @@ export const CURRENCIES: {label: string; currency: string}[] = [
|
||||
label: "United States dollar",
|
||||
currency: "USD",
|
||||
},
|
||||
{
|
||||
label: "Omani rial",
|
||||
currency: "OMR",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -45,10 +45,11 @@ export const evaluateSpeakingAnswer = async (
|
||||
exercise: SpeakingExercise | InteractiveSpeakingExercise,
|
||||
solution: UserSolution,
|
||||
id: string,
|
||||
task: number,
|
||||
): Promise<UserSolution | undefined> => {
|
||||
switch (exercise?.type) {
|
||||
case "speaking":
|
||||
return {...(await evaluateSpeakingExercise(exercise, exercise.id, solution, id)), id} as UserSolution;
|
||||
return {...(await evaluateSpeakingExercise(exercise, exercise.id, solution, id, task)), id} as UserSolution;
|
||||
case "interactiveSpeaking":
|
||||
return {...(await evaluateInteractiveSpeakingExercise(exercise.id, solution, id)), id} as UserSolution;
|
||||
default:
|
||||
@@ -66,6 +67,7 @@ const evaluateSpeakingExercise = async (
|
||||
exerciseId: string,
|
||||
solution: UserSolution,
|
||||
id: string,
|
||||
task: number,
|
||||
): Promise<UserSolution | undefined> => {
|
||||
const formData = new FormData();
|
||||
|
||||
@@ -81,6 +83,7 @@ const evaluateSpeakingExercise = async (
|
||||
`${exercise.text.replaceAll("\n", "")}` + (exercise.prompts.length > 0 ? `You should talk about: ${exercise.prompts.join(", ")}` : "");
|
||||
formData.append("question", evaluationQuestion);
|
||||
formData.append("id", id);
|
||||
formData.append("task", task.toString());
|
||||
|
||||
const config = {
|
||||
headers: {
|
||||
|
||||
@@ -67,7 +67,7 @@ export const propagateStatusChange = (userId: string, status: UserStatus) =>
|
||||
});
|
||||
});
|
||||
|
||||
export const propagateExpiryDateChanges = (userId: string, initialExpiryDate: Date | null, subscriptionExpirationDate: Date | null) =>
|
||||
export const propagateExpiryDateChanges = (userId: string, initialExpiryDate: Date | null | undefined, subscriptionExpirationDate: Date | null) =>
|
||||
new Promise((resolve, reject) => {
|
||||
getDoc(doc(db, "users", userId))
|
||||
.then((docUser) => {
|
||||
@@ -93,6 +93,7 @@ export const propagateExpiryDateChanges = (userId: string, initialExpiryDate: Da
|
||||
.then(async (data) => {
|
||||
const filtered = data.filter((x) => {
|
||||
if (x === null) return false;
|
||||
if (!x.subscriptionExpirationDate && !initialExpiryDate) return true;
|
||||
if (x.subscriptionExpirationDate !== initialExpiryDate) return false;
|
||||
return true;
|
||||
}) as User[];
|
||||
|
||||
29
yarn.lock
29
yarn.lock
@@ -4870,13 +4870,6 @@ path-type@^4.0.0:
|
||||
resolved "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz"
|
||||
integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==
|
||||
|
||||
"paymob-react@git+https://github.com/tiago-ecrop/paymob-react-oman.git":
|
||||
version "1.0.0"
|
||||
resolved "git+https://github.com/tiago-ecrop/paymob-react-oman.git#9e7d1e86f01d29dd10192bbd371517849a264e5d"
|
||||
dependencies:
|
||||
react "^18.2.0"
|
||||
react-dom "^18.2.0"
|
||||
|
||||
picocolors@^1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz"
|
||||
@@ -5208,14 +5201,6 @@ react-dom@18.2.0:
|
||||
loose-envify "^1.1.0"
|
||||
scheduler "^0.23.0"
|
||||
|
||||
react-dom@^18.2.0:
|
||||
version "18.3.1"
|
||||
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-18.3.1.tgz#c2265d79511b57d479b3dd3fdfa51536494c5cb4"
|
||||
integrity sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==
|
||||
dependencies:
|
||||
loose-envify "^1.1.0"
|
||||
scheduler "^0.23.2"
|
||||
|
||||
react-fast-compare@^3.0.1:
|
||||
version "3.2.1"
|
||||
resolved "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-3.2.1.tgz"
|
||||
@@ -5345,13 +5330,6 @@ react@18.2.0:
|
||||
dependencies:
|
||||
loose-envify "^1.1.0"
|
||||
|
||||
react@^18.2.0:
|
||||
version "18.3.1"
|
||||
resolved "https://registry.yarnpkg.com/react/-/react-18.3.1.tgz#49ab892009c53933625bd16b2533fc754cab2891"
|
||||
integrity sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==
|
||||
dependencies:
|
||||
loose-envify "^1.1.0"
|
||||
|
||||
read-cache@^1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz"
|
||||
@@ -5557,13 +5535,6 @@ scheduler@^0.23.0:
|
||||
dependencies:
|
||||
loose-envify "^1.1.0"
|
||||
|
||||
scheduler@^0.23.2:
|
||||
version "0.23.2"
|
||||
resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.23.2.tgz#414ba64a3b282892e944cf2108ecc078d115cdc3"
|
||||
integrity sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==
|
||||
dependencies:
|
||||
loose-envify "^1.1.0"
|
||||
|
||||
seedrandom@^3.0.5:
|
||||
version "3.0.5"
|
||||
resolved "https://registry.yarnpkg.com/seedrandom/-/seedrandom-3.0.5.tgz#54edc85c95222525b0c7a6f6b3543d8e0b3aa0a7"
|
||||
|
||||
Reference in New Issue
Block a user