daily quiz entries store in db correctly
This commit is contained in:
@@ -17,26 +17,49 @@ export type AvatarCondition = {
|
||||
export type DailyQuizSubmission = {
|
||||
date: string;
|
||||
answers: DailyQuizAnswers;
|
||||
journal: string;
|
||||
condition: AvatarCondition;
|
||||
};
|
||||
|
||||
export const WELLNESS_SCALE_MAX = 5;
|
||||
|
||||
export const SLEEP_HOURS_MIN = 0.5;
|
||||
export const SLEEP_HOURS_MAX = 12;
|
||||
export const SLEEP_HOURS_STEP = 0.5;
|
||||
export const DEFAULT_SLEEP_HOURS = 7.5;
|
||||
|
||||
export const defaultDailyQuizAnswers: DailyQuizAnswers = {
|
||||
feeling: 3,
|
||||
stress: 3,
|
||||
energy: 3,
|
||||
sleepLength: 3,
|
||||
sleepLength: DEFAULT_SLEEP_HOURS,
|
||||
sleepQuality: 3,
|
||||
};
|
||||
|
||||
export function clampSleepHours(hours: number) {
|
||||
const stepped = Math.round(hours / SLEEP_HOURS_STEP) * SLEEP_HOURS_STEP;
|
||||
return Math.min(SLEEP_HOURS_MAX, Math.max(SLEEP_HOURS_MIN, stepped));
|
||||
}
|
||||
|
||||
export function formatSleepHours(hours: number) {
|
||||
return hours === 1 ? "1 hour" : `${hours} hours`;
|
||||
}
|
||||
|
||||
function sleepHoursToWellnessScore(hours: number) {
|
||||
const score =
|
||||
1 + ((clampSleepHours(hours) - SLEEP_HOURS_MIN) / (SLEEP_HOURS_MAX - SLEEP_HOURS_MIN)) * 4;
|
||||
|
||||
return clampStat(Math.round(score));
|
||||
}
|
||||
|
||||
export function computeAvatarCondition(
|
||||
answers: DailyQuizAnswers,
|
||||
): AvatarCondition {
|
||||
const { feeling, stress, energy, sleepLength, sleepQuality } = answers;
|
||||
|
||||
const wellnessAverage = (feeling + energy + (WELLNESS_SCALE_MAX + 1 - stress)) / 3;
|
||||
const sleepAverage = (sleepLength + sleepQuality) / 2;
|
||||
const sleepScore = sleepHoursToWellnessScore(sleepLength);
|
||||
const sleepAverage = (sleepScore + sleepQuality) / 2;
|
||||
const health = Math.round((wellnessAverage + sleepAverage) / 2);
|
||||
const energyLevel = Math.round((energy + sleepQuality) / 2);
|
||||
|
||||
@@ -44,7 +67,7 @@ export function computeAvatarCondition(
|
||||
|
||||
if (energyLevel >= 4 && feeling >= 4 && health >= 4) {
|
||||
avatarMood = "happy";
|
||||
} else if (energy <= 2 || sleepLength <= 2 || sleepQuality <= 2) {
|
||||
} else if (energy <= 2 || sleepLength < 6 || sleepQuality <= 2) {
|
||||
avatarMood = "tired";
|
||||
}
|
||||
|
||||
@@ -82,11 +105,19 @@ export function normalizeDailyQuizAnswers(
|
||||
: value;
|
||||
};
|
||||
|
||||
const normalizeSleepLength = (value: number | undefined) => {
|
||||
if (value === undefined) {
|
||||
return defaultDailyQuizAnswers.sleepLength;
|
||||
}
|
||||
|
||||
return clampSleepHours(value);
|
||||
};
|
||||
|
||||
return {
|
||||
feeling: scaleValue(answers.feeling ?? answers.mood, defaultDailyQuizAnswers.feeling),
|
||||
stress: scaleValue(answers.stress, defaultDailyQuizAnswers.stress),
|
||||
energy: scaleValue(answers.energy, defaultDailyQuizAnswers.energy),
|
||||
sleepLength: scaleValue(answers.sleepLength, defaultDailyQuizAnswers.sleepLength),
|
||||
sleepLength: normalizeSleepLength(answers.sleepLength),
|
||||
sleepQuality: scaleValue(
|
||||
answers.sleepQuality,
|
||||
defaultDailyQuizAnswers.sleepQuality,
|
||||
|
||||
@@ -6,69 +6,142 @@ import {
|
||||
type DailyQuizSubmission,
|
||||
} from "@/lib/avatar-state";
|
||||
import { notifyHabitPetDataUpdated } from "@/lib/app-events";
|
||||
const STORAGE_KEY = "habit-pet-daily-quiz";
|
||||
import { createClient } from "@/lib/supabase/client";
|
||||
|
||||
type DailyEntryRow = {
|
||||
entry_date: string;
|
||||
mood: number;
|
||||
stress: number;
|
||||
energy: number;
|
||||
sleep_hours: number;
|
||||
sleep_quality: number;
|
||||
journal: string | null;
|
||||
};
|
||||
|
||||
export function getTodayDateKey(date = new Date()) {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function normalizeSubmission(
|
||||
submission: DailyQuizSubmission,
|
||||
): DailyQuizSubmission {
|
||||
const answers = normalizeDailyQuizAnswers(submission.answers);
|
||||
function mapRowToSubmission(row: DailyEntryRow): DailyQuizSubmission {
|
||||
const answers = normalizeDailyQuizAnswers({
|
||||
feeling: row.mood,
|
||||
stress: row.stress,
|
||||
energy: row.energy,
|
||||
sleepLength: Number(row.sleep_hours),
|
||||
sleepQuality: row.sleep_quality,
|
||||
});
|
||||
|
||||
return {
|
||||
...submission,
|
||||
date: row.entry_date,
|
||||
answers,
|
||||
journal: row.journal ?? "",
|
||||
condition: computeAvatarCondition(answers),
|
||||
};
|
||||
}
|
||||
|
||||
export function getDailyQuizSubmission(): DailyQuizSubmission | null {
|
||||
if (typeof window === "undefined") {
|
||||
async function getAuthenticatedUserId() {
|
||||
const supabase = createClient();
|
||||
const {
|
||||
data: { user },
|
||||
error,
|
||||
} = await supabase.auth.getUser();
|
||||
|
||||
if (error || !user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return normalizeSubmission(JSON.parse(raw) as DailyQuizSubmission);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return user.id;
|
||||
}
|
||||
|
||||
export function hasCompletedDailyQuizToday() {
|
||||
const submission = getDailyQuizSubmission();
|
||||
return submission?.date === getTodayDateKey();
|
||||
export async function getDailyEntryForToday(): Promise<DailyQuizSubmission | null> {
|
||||
const userId = await getAuthenticatedUserId();
|
||||
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const supabase = createClient();
|
||||
const entryDate = getTodayDateKey();
|
||||
const { data, error } = await supabase
|
||||
.from("daily_entries")
|
||||
.select(
|
||||
"entry_date, mood, stress, energy, sleep_hours, sleep_quality, journal",
|
||||
)
|
||||
.eq("user_id", userId)
|
||||
.eq("entry_date", entryDate)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
throw new Error(error.message);
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return mapRowToSubmission(data as DailyEntryRow);
|
||||
}
|
||||
|
||||
export function saveDailyQuizSubmission(
|
||||
export async function getDailyQuizSubmission() {
|
||||
return getDailyEntryForToday();
|
||||
}
|
||||
|
||||
export async function hasCompletedDailyQuizToday() {
|
||||
const entry = await getDailyEntryForToday();
|
||||
return entry !== null;
|
||||
}
|
||||
|
||||
export async function saveDailyEntry(
|
||||
answers: DailyQuizAnswers,
|
||||
): DailyQuizSubmission {
|
||||
const submission: DailyQuizSubmission = {
|
||||
date: getTodayDateKey(),
|
||||
answers,
|
||||
condition: computeAvatarCondition(answers),
|
||||
};
|
||||
journal: string,
|
||||
): Promise<DailyQuizSubmission> {
|
||||
const userId = await getAuthenticatedUserId();
|
||||
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(submission));
|
||||
if (!userId) {
|
||||
throw new Error("You must be signed in to save your daily check-in.");
|
||||
}
|
||||
|
||||
const supabase = createClient();
|
||||
const entryDate = getTodayDateKey();
|
||||
const normalizedAnswers = normalizeDailyQuizAnswers(answers);
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from("daily_entries")
|
||||
.upsert(
|
||||
{
|
||||
user_id: userId,
|
||||
entry_date: entryDate,
|
||||
mood: normalizedAnswers.feeling,
|
||||
stress: normalizedAnswers.stress,
|
||||
energy: normalizedAnswers.energy,
|
||||
sleep_hours: normalizedAnswers.sleepLength,
|
||||
sleep_quality: normalizedAnswers.sleepQuality,
|
||||
journal,
|
||||
},
|
||||
{ onConflict: "user_id,entry_date" },
|
||||
)
|
||||
.select(
|
||||
"entry_date, mood, stress, energy, sleep_hours, sleep_quality, journal",
|
||||
)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
throw new Error(error.message);
|
||||
}
|
||||
|
||||
const submission = mapRowToSubmission(data as DailyEntryRow);
|
||||
notifyHabitPetDataUpdated();
|
||||
|
||||
return submission;
|
||||
}
|
||||
|
||||
export function getAvatarConditionForToday(): AvatarCondition | null {
|
||||
const submission = getDailyQuizSubmission();
|
||||
|
||||
if (!submission || submission.date !== getTodayDateKey()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return submission.condition;
|
||||
export async function saveDailyQuizSubmission(
|
||||
answers: DailyQuizAnswers,
|
||||
journal = "",
|
||||
) {
|
||||
return saveDailyEntry(answers, journal);
|
||||
}
|
||||
|
||||
export async function getAvatarConditionForToday(): Promise<AvatarCondition | null> {
|
||||
const entry = await getDailyEntryForToday();
|
||||
return entry?.condition ?? null;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { DailyQuizAnswers } from "@/lib/avatar-state";
|
||||
import { getDailyQuizSubmission, getTodayDateKey } from "@/lib/daily-quiz-storage";
|
||||
import { getDailyEntryForToday } from "@/lib/daily-quiz-storage";
|
||||
import {
|
||||
catalogHabitIds,
|
||||
getCatalogEntry,
|
||||
@@ -23,14 +23,9 @@ export type DailyTask = Habit & {
|
||||
reason: DailyTaskReason;
|
||||
};
|
||||
|
||||
function getQuizAnswersForToday(): DailyQuizAnswers | null {
|
||||
const submission = getDailyQuizSubmission();
|
||||
|
||||
if (!submission || submission.date !== getTodayDateKey()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return submission.answers;
|
||||
async function getQuizAnswersForToday(): Promise<DailyQuizAnswers | null> {
|
||||
const entry = await getDailyEntryForToday();
|
||||
return entry?.answers ?? null;
|
||||
}
|
||||
|
||||
function getCatalogTaskReason(
|
||||
@@ -54,7 +49,7 @@ function getCatalogTaskReason(
|
||||
|
||||
export async function getDailyTasks(): Promise<DailyTask[]> {
|
||||
const preferences = getProfilePreferences();
|
||||
const quizAnswers = getQuizAnswersForToday();
|
||||
const quizAnswers = await getQuizAnswersForToday();
|
||||
|
||||
const selectedCatalogIds = habitCatalog
|
||||
.map((entry) => {
|
||||
|
||||
@@ -50,7 +50,7 @@ export const habitCatalog: HabitCatalogEntry[] = [
|
||||
label: "Wind down before bed",
|
||||
focusTopics: ["Sleep"],
|
||||
suggestedByQuiz: (answers) =>
|
||||
answers.sleepLength <= 2 || answers.sleepQuality <= 2,
|
||||
answers.sleepLength < 7 || answers.sleepQuality <= 2,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
import { createClient } from "@/lib/supabase/client";
|
||||
|
||||
export type JournalEntry = {
|
||||
entryDate: string;
|
||||
content: string;
|
||||
};
|
||||
|
||||
const LOCAL_STORAGE_KEY = "habit-pet-journal";
|
||||
|
||||
export function getTodayDateKey(date = new Date()) {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function getLocalJournalEntry(entryDate = getTodayDateKey()): JournalEntry | null {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const raw = window.localStorage.getItem(LOCAL_STORAGE_KEY);
|
||||
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const entry = JSON.parse(raw) as JournalEntry;
|
||||
return entry.entryDate === entryDate ? entry : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveLocalJournalEntry(content: string, entryDate = getTodayDateKey()) {
|
||||
const entry: JournalEntry = { entryDate, content };
|
||||
window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(entry));
|
||||
return entry;
|
||||
}
|
||||
|
||||
export async function getJournalEntryForToday(): Promise<JournalEntry | null> {
|
||||
const entryDate = getTodayDateKey();
|
||||
const supabase = createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
|
||||
if (!user) {
|
||||
return getLocalJournalEntry(entryDate);
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from("journal_entries")
|
||||
.select("entry_date, content")
|
||||
.eq("user_id", user.id)
|
||||
.eq("entry_date", entryDate)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
console.error("Failed to load journal entry:", error.message);
|
||||
return getLocalJournalEntry(entryDate);
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
entryDate: data.entry_date,
|
||||
content: data.content,
|
||||
};
|
||||
}
|
||||
|
||||
export async function saveJournalEntry(content: string): Promise<JournalEntry> {
|
||||
const entryDate = getTodayDateKey();
|
||||
const supabase = createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
|
||||
if (!user) {
|
||||
return saveLocalJournalEntry(content, entryDate);
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from("journal_entries")
|
||||
.upsert(
|
||||
{
|
||||
user_id: user.id,
|
||||
entry_date: entryDate,
|
||||
content,
|
||||
updated_at: new Date().toISOString(),
|
||||
},
|
||||
{ onConflict: "user_id,entry_date" },
|
||||
)
|
||||
.select("entry_date, content")
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
console.error("Failed to save journal entry:", error.message);
|
||||
return saveLocalJournalEntry(content, entryDate);
|
||||
}
|
||||
|
||||
return {
|
||||
entryDate: data.entry_date,
|
||||
content: data.content,
|
||||
};
|
||||
}
|
||||
|
||||
export function hasJournalEntryToday(entry: JournalEntry | null) {
|
||||
return entry?.entryDate === getTodayDateKey() && entry.content.trim().length > 0;
|
||||
}
|
||||
Reference in New Issue
Block a user