-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuser.tsx
272 lines (254 loc) · 8.07 KB
/
user.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import { getUserSettingsFromEmail } from "@/koala/auth-helpers";
import { prismaClient } from "@/koala/prisma-client";
import { trpc } from "@/koala/trpc-config";
import { getLessonMeta } from "@/koala/trpc-routes/get-next-quizzes";
import {
Button,
Card,
Container,
Group,
NumberInput,
Paper,
Radio,
Stack,
Text,
Title,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { UnwrapPromise } from "@prisma/client/runtime/library";
import { GetServerSidePropsContext } from "next";
import { getSession, signOut } from "next-auth/react";
import React, { useState } from "react";
const ONE_DAY = 24 * 60 * 60 * 1000;
const ONE_WEEK = 7 * ONE_DAY;
export async function getServerSideProps(context: GetServerSidePropsContext) {
async function getUserCardStatistics(userId: string) {
const today = Date.now();
const oneWeekAgo = today - ONE_WEEK;
const yesterday = today - ONE_DAY;
const tomorrow = today + ONE_DAY;
const BASE_QUERY = {
Card: {
userId: userId,
flagged: { not: true },
},
};
const cardsDueNext24Hours = await prismaClient.quiz.count({
where: {
...BASE_QUERY,
nextReview: {
lt: tomorrow,
},
firstReview: {
gt: 0,
},
},
});
const newCardsLast24Hours = await prismaClient.quiz.count({
where: {
...BASE_QUERY,
firstReview: {
gte: yesterday,
},
},
});
const newCardsLastWeek = await prismaClient.quiz.count({
where: {
...BASE_QUERY,
firstReview: {
gte: oneWeekAgo,
},
},
});
const uniqueCardsLast24Hours = await prismaClient.quiz.count({
where: {
...BASE_QUERY,
lastReview: {
gte: yesterday,
},
},
});
const uniqueCardsLastWeek = await prismaClient.quiz.count({
where: {
...BASE_QUERY,
lastReview: {
gte: oneWeekAgo,
},
},
});
const statistics = {
...(await getLessonMeta(userId)),
uniqueCardsLast24Hours,
uniqueCardsLastWeek,
newCardsLast24Hours,
newCardsLastWeek,
cardsDueNext24Hours,
globalUsers: await prismaClient.user.count(),
};
return statistics;
}
const session = await getSession({ req: context.req });
const userSettings = await getUserSettingsFromEmail(session?.user?.email);
return {
props: {
userSettings: JSON.parse(JSON.stringify(userSettings)),
stats: await getUserCardStatistics(userSettings.userId),
},
};
}
type Props = UnwrapPromise<ReturnType<typeof getServerSideProps>>["props"];
export default function UserSettingsPage(props: Props) {
const { userSettings } = props;
const [settings, setSettings] = useState(userSettings);
const editUserSettings = trpc.editUserSettings.useMutation();
const lr = trpc.levelReviews.useMutation();
const handleChange = (value: number | string, name: string) => {
setSettings({ ...settings, [name]: parseFloat(String(value)) });
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
editUserSettings
.mutateAsync({
...settings,
updatedAt: new Date(settings.updatedAt),
})
.then(
() => {
location.reload();
},
(error: unknown) => {
notifications.show({
title: "Error",
message: `Error: ${JSON.stringify(error).slice(0, 100)}`,
color: "red",
});
},
);
};
const stats = props.stats;
const labels: [keyof typeof stats, string][] = [
["totalCards", "Total cards studied"],
["newCards", "New cards in deck"],
["quizzesDue", "Cards due now"],
["cardsDueNext24Hours", "Cards due next 24 hours"],
["newCardsLast24Hours", "New cards studied last 24 hours"],
["newCardsLastWeek", "New cards studied this week"],
["uniqueCardsLast24Hours", "Cards studied last 24 hours"],
["uniqueCardsLastWeek", "Cards studied this week"],
["globalUsers", "Active Koala users"],
];
return (
<Container size="sm" mt="xl">
<Stack gap="xl">
<Title order={1}>User Settings</Title>
<Paper withBorder p="md" radius="md">
<form onSubmit={handleSubmit}>
<Stack gap="md">
<NumberInput
label="Audio playback speed percentage"
description="Adjust how quickly audio is played back (50% - 200%)"
id="playbackSpeed"
name="playbackSpeed"
value={settings.playbackSpeed}
onChange={(value) => handleChange(value, "playbackSpeed")}
min={0.5}
max={2}
step={0.02}
required
/>
<NumberInput
label="Max new quizzes per day"
description="Maximum number of new quizzes (usually 2 per card) in a 24-hour period"
id="cardsPerDayMax"
name="cardsPerDayMax"
value={settings.cardsPerDayMax}
onChange={(value) => handleChange(value, "cardsPerDayMax")}
min={1}
required
/>
<Radio.Group
label="Playback your voice after recording?"
description="Listening to your own voice is a good way to improve pronunciation"
id="playbackPercentage"
name="playbackPercentage"
value={String(settings.playbackPercentage)}
onChange={(value) => handleChange(value, "playbackPercentage")}
required
>
<Radio value="1" label="Always" />
<Radio value="0.125" label="Sometimes" />
<Radio value="0" label="Never" />
</Radio.Group>
<Group justify="flex-end" mt="md">
<Button type="submit">Save Settings</Button>
</Group>
</Stack>
</form>
</Paper>
<Stack gap="md">
<Title order={2}>Statistics</Title>
<Text size="sm">
Here are some insights into your learning progress and the user
base.
</Text>
<Card withBorder shadow="xs" p="md" radius="md">
<Stack gap="xs">
{labels.map(([key, label]) => (
<Group key={key} gap="xs">
<Text fw={500}>{label}:</Text>
<Text>{stats[key]}</Text>
</Group>
))}
</Stack>
</Card>
</Stack>
<Stack gap="md">
<Card withBorder shadow="xs" p="md" radius="md">
<Button
onClick={(event) => {
event.preventDefault();
signOut();
location.assign("/");
}}
>
Log Out
</Button>
</Card>
<Title order={2}>Level Reviews</Title>
<Text size="sm">
If you have too many cards due, you can level your review schedule.
This will evenly distribute older cards over the next 7 days.
<br />
<strong>This operation is irreversible.</strong>
</Text>
<Card withBorder shadow="xs" p="md" radius="md">
<Button
variant="outline"
color="red"
onClick={() =>
lr.mutateAsync({}).then(
({ count }) => {
notifications.show({
title: "Success",
message: `Leveled ${count} cards.`,
color: "green",
});
},
() => {
notifications.show({
title: "Error",
message: "Error leveling cards.",
color: "red",
});
},
)
}
>
Level Reviews
</Button>
</Card>
</Stack>
</Stack>
</Container>
);
}