Refactor user initialization and balance retrieval logic
- Updated the `InitUser` component to handle session state more effectively by incorporating a loading state. - Removed the unused `useAuthQuery` hook and adjusted the balance initialization logic to only proceed when the session is confirmed. - Enhanced the `getBalance` query with improved error handling and logging for better debugging. - Modified the `initBalance` mutation to return an object indicating whether a new balance was created, improving clarity in the initialization process.
This commit is contained in:
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
import { authClient } from "@/lib/auth-client";
|
import { authClient } from "@/lib/auth-client";
|
||||||
import { useMutation } from "convex/react";
|
import { useMutation } from "convex/react";
|
||||||
import { useAuthQuery } from "@/hooks/use-auth-query";
|
|
||||||
import { api } from "@/convex/_generated/api";
|
import { api } from "@/convex/_generated/api";
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
@@ -15,32 +14,28 @@ import { toast } from "@/lib/toast";
|
|||||||
*/
|
*/
|
||||||
export function InitUser() {
|
export function InitUser() {
|
||||||
const t = useTranslations('toasts');
|
const t = useTranslations('toasts');
|
||||||
const { data: session } = authClient.useSession();
|
const { data: session, isPending: isSessionPending } = authClient.useSession();
|
||||||
|
|
||||||
const balance = useAuthQuery(api.credits.getBalance);
|
|
||||||
const initBalance = useMutation(api.credits.initBalance);
|
const initBalance = useMutation(api.credits.initBalance);
|
||||||
const initStartedRef = useRef(false);
|
const initStartedRef = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (
|
if (isSessionPending || !session?.user) {
|
||||||
!session?.user ||
|
|
||||||
!balance ||
|
|
||||||
balance.balance !== 0 ||
|
|
||||||
balance.monthlyAllocation !== 0
|
|
||||||
) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (initStartedRef.current) return;
|
if (initStartedRef.current) return;
|
||||||
initStartedRef.current = true;
|
initStartedRef.current = true;
|
||||||
|
|
||||||
void initBalance()
|
void initBalance()
|
||||||
.then(() => {
|
.then((result) => {
|
||||||
toast.success(t('auth.initialSetupTitle'), t('auth.initialSetupDesc'));
|
if (result.created) {
|
||||||
|
toast.success(t('auth.initialSetupTitle'), t('auth.initialSetupDesc'));
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
initStartedRef.current = false;
|
initStartedRef.current = false;
|
||||||
});
|
});
|
||||||
}, [t, session?.user, balance, initBalance]);
|
}, [t, initBalance, isSessionPending, session?.user]);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,25 +60,54 @@ const PERFORMANCE_LOG_THRESHOLD_MS = 250;
|
|||||||
export const getBalance = query({
|
export const getBalance = query({
|
||||||
args: {},
|
args: {},
|
||||||
handler: async (ctx) => {
|
handler: async (ctx) => {
|
||||||
const user = await optionalAuth(ctx);
|
const startedAt = Date.now();
|
||||||
if (!user) {
|
|
||||||
return { balance: 0, reserved: 0, available: 0, monthlyAllocation: 0 };
|
|
||||||
}
|
|
||||||
const balance = await ctx.db
|
|
||||||
.query("creditBalances")
|
|
||||||
.withIndex("by_user", (q) => q.eq("userId", user.userId))
|
|
||||||
.unique();
|
|
||||||
|
|
||||||
if (!balance) {
|
try {
|
||||||
return { balance: 0, reserved: 0, available: 0, monthlyAllocation: 0 };
|
console.info("[credits.getBalance] start", {
|
||||||
}
|
durationMs: Date.now() - startedAt,
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
const user = await optionalAuth(ctx);
|
||||||
balance: balance.balance,
|
console.info("[credits.getBalance] auth resolved", {
|
||||||
reserved: balance.reserved,
|
durationMs: Date.now() - startedAt,
|
||||||
available: balance.balance - balance.reserved,
|
userId: user?.userId ?? null,
|
||||||
monthlyAllocation: balance.monthlyAllocation,
|
});
|
||||||
};
|
|
||||||
|
if (!user) {
|
||||||
|
return { balance: 0, reserved: 0, available: 0, monthlyAllocation: 0 };
|
||||||
|
}
|
||||||
|
const balance = await ctx.db
|
||||||
|
.query("creditBalances")
|
||||||
|
.withIndex("by_user", (q) => q.eq("userId", user.userId))
|
||||||
|
.unique();
|
||||||
|
|
||||||
|
console.info("[credits.getBalance] balance query resolved", {
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
userId: user.userId,
|
||||||
|
foundBalance: Boolean(balance),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!balance) {
|
||||||
|
return { balance: 0, reserved: 0, available: 0, monthlyAllocation: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
balance: balance.balance,
|
||||||
|
reserved: balance.reserved,
|
||||||
|
available: balance.balance - balance.reserved,
|
||||||
|
monthlyAllocation: balance.monthlyAllocation,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
const identity = await ctx.auth.getUserIdentity();
|
||||||
|
console.error("[credits.getBalance] failed", {
|
||||||
|
durationMs: Date.now() - startedAt,
|
||||||
|
hasIdentity: Boolean(identity),
|
||||||
|
identityIssuer: identity?.issuer ?? null,
|
||||||
|
identitySubject: identity?.subject ?? null,
|
||||||
|
message: error instanceof Error ? error.message : String(error),
|
||||||
|
});
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -295,7 +324,9 @@ export const initBalance = mutation({
|
|||||||
.withIndex("by_user", (q) => q.eq("userId", user.userId))
|
.withIndex("by_user", (q) => q.eq("userId", user.userId))
|
||||||
.unique();
|
.unique();
|
||||||
|
|
||||||
if (existing) return existing._id;
|
if (existing) {
|
||||||
|
return { balanceId: existing._id, created: false };
|
||||||
|
}
|
||||||
|
|
||||||
// Free-Tier Credits als Startguthaben
|
// Free-Tier Credits als Startguthaben
|
||||||
const balanceId = await ctx.db.insert("creditBalances", {
|
const balanceId = await ctx.db.insert("creditBalances", {
|
||||||
@@ -324,7 +355,7 @@ export const initBalance = mutation({
|
|||||||
description: "Startguthaben — Free Tier",
|
description: "Startguthaben — Free Tier",
|
||||||
});
|
});
|
||||||
|
|
||||||
return balanceId;
|
return { balanceId, created: true };
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user