add dbiz, add history
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { canUseWritingCheck, recordWritingCheckUsage } from "@/utils/rate-limiter"
|
||||
import { useAuthStore } from "@/store/auth-store"
|
||||
import { supabase } from "@/lib/supabase"
|
||||
@@ -8,51 +8,119 @@ import type { WritingFeedback } from "@/types"
|
||||
const AUTH_DAILY_LIMIT = 10
|
||||
const GUEST_DAILY_LIMIT = 3
|
||||
|
||||
async function callEdgeFunction(content: string): Promise<WritingFeedback> {
|
||||
const { data, error } = await supabase.functions.invoke<WritingFeedback>("writing-check", {
|
||||
body: { content },
|
||||
const SUPABASE_URL = import.meta.env.VITE_SUPABASE_URL as string
|
||||
const SUPABASE_ANON_KEY = (
|
||||
import.meta.env.VITE_SUPABASE_ANON_KEY || import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY
|
||||
) as string
|
||||
|
||||
// Calls the edge function and streams SSE chunks, invoking onChunk for each text piece.
|
||||
// Accumulates the full response, then extracts and parses the JSON object.
|
||||
async function callEdgeFunction(
|
||||
content: string,
|
||||
onChunk?: (text: string) => void,
|
||||
): Promise<WritingFeedback> {
|
||||
const { data: { session } } = await supabase.auth.getSession()
|
||||
|
||||
const res = await fetch(`${SUPABASE_URL}/functions/v1/writing-check-dbiz`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
apikey: SUPABASE_ANON_KEY,
|
||||
Authorization: `Bearer ${session?.access_token ?? SUPABASE_ANON_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({ content }),
|
||||
})
|
||||
|
||||
if (error) {
|
||||
// The Supabase SDK wraps non-2xx responses in a generic FunctionsHttpError.
|
||||
// Try to parse the actual error body returned by the edge function.
|
||||
try {
|
||||
const body = await (error as unknown as { context: Response }).context.json()
|
||||
if (body?.error) throw new Error(body.error)
|
||||
} catch {
|
||||
// ignore parse failure, fall through to generic message
|
||||
}
|
||||
throw new Error("Đã có lỗi khi chấm bài. Vui lòng thử lại.")
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
throw new Error(body?.error ?? "Đã có lỗi khi chấm bài. Vui lòng thử lại.")
|
||||
}
|
||||
|
||||
if (!data) throw new Error("Phản hồi từ AI không hợp lệ. Vui lòng thử lại.")
|
||||
const reader = res.body!.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ""
|
||||
let accumulated = ""
|
||||
|
||||
return data
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split("\n")
|
||||
buffer = lines.pop() ?? ""
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith("data: ")) continue
|
||||
const payload = line.slice(6).trim()
|
||||
if (payload === "[DONE]") continue
|
||||
|
||||
let event: { text?: string; error?: string }
|
||||
try {
|
||||
event = JSON.parse(payload)
|
||||
} catch {
|
||||
continue // skip malformed SSE lines
|
||||
}
|
||||
|
||||
if (event.error) throw new Error(event.error)
|
||||
if (event.text) {
|
||||
accumulated += event.text
|
||||
onChunk?.(event.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract the outermost JSON object from the accumulated stream
|
||||
const start = accumulated.indexOf("{")
|
||||
const end = accumulated.lastIndexOf("}")
|
||||
if (start === -1 || end === -1) {
|
||||
throw new Error("Phản hồi từ AI không hợp lệ. Vui lòng thử lại.")
|
||||
}
|
||||
|
||||
const raw = JSON.parse(accumulated.slice(start, end + 1))
|
||||
|
||||
// Normalize: model sometimes returns array fields as a plain string
|
||||
const toArray = (v: unknown): string[] => {
|
||||
if (Array.isArray(v)) return v
|
||||
if (typeof v === "string" && v.length > 0) return [v]
|
||||
return []
|
||||
}
|
||||
|
||||
return {
|
||||
...raw,
|
||||
grammar: toArray(raw.grammar),
|
||||
vocabulary: toArray(raw.vocabulary),
|
||||
improvedVersion: raw.improved_version ?? raw.improvedVersion ?? "",
|
||||
} as WritingFeedback
|
||||
}
|
||||
|
||||
export function useWritingCheck() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async (content: string): Promise<WritingFeedback> => {
|
||||
mutationFn: async ({
|
||||
content,
|
||||
onChunk,
|
||||
}: {
|
||||
content: string
|
||||
onChunk?: (text: string) => void
|
||||
}): Promise<WritingFeedback> => {
|
||||
const user = useAuthStore.getState().user
|
||||
|
||||
if (user) {
|
||||
// Server-side rate limit for authenticated users (10/day)
|
||||
const usedToday = await countTodayWritingSubmissions(user.id)
|
||||
if (usedToday >= AUTH_DAILY_LIMIT) {
|
||||
throw new Error(`Bạn đã dùng hết ${AUTH_DAILY_LIMIT} lần kiểm tra hôm nay. Quay lại vào ngày mai!`)
|
||||
}
|
||||
} else {
|
||||
// localStorage rate limit for guests (3/day)
|
||||
if (!canUseWritingCheck()) {
|
||||
throw new Error(`Bạn đã dùng hết ${GUEST_DAILY_LIMIT} lần kiểm tra hôm nay. Đăng ký để được 10 lần/ngày!`)
|
||||
}
|
||||
}
|
||||
|
||||
const feedback = await callEdgeFunction(content)
|
||||
const feedback = await callEdgeFunction(content, onChunk)
|
||||
|
||||
if (user) {
|
||||
// Save submission to DB (fire-and-forget)
|
||||
saveWritingSubmission(user.id, content, feedback)
|
||||
queryClient.invalidateQueries({ queryKey: ["writing-history"] })
|
||||
} else {
|
||||
recordWritingCheckUsage()
|
||||
}
|
||||
|
||||
14
src/hooks/use-writing-history.ts
Normal file
14
src/hooks/use-writing-history.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { useAuthStore } from "@/store/auth-store"
|
||||
import { fetchWritingHistory } from "@/lib/progress-service"
|
||||
import type { WritingSubmission } from "@/types"
|
||||
|
||||
export function useWritingHistory() {
|
||||
const user = useAuthStore((s) => s.user)
|
||||
return useQuery<WritingSubmission[]>({
|
||||
queryKey: ["writing-history", user?.id],
|
||||
queryFn: () => fetchWritingHistory(user!.id) as Promise<WritingSubmission[]>,
|
||||
enabled: !!user,
|
||||
staleTime: 30_000,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user