Initial commit: Vue 3 Gold Land frontend
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
let bootstrapped = false
|
||||
|
||||
export function isAppBootstrapped() {
|
||||
return bootstrapped
|
||||
}
|
||||
|
||||
export function markAppBootstrapped() {
|
||||
bootstrapped = true
|
||||
}
|
||||
|
||||
export function resetAppBootstrap() {
|
||||
bootstrapped = false
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
const TOKEN_KEY = 'gold-land-auth-token'
|
||||
|
||||
let authToken: string | null = null
|
||||
|
||||
export function getAuthToken(): string | null {
|
||||
if (authToken) return authToken
|
||||
try {
|
||||
return localStorage.getItem(TOKEN_KEY)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function setAuthToken(token: string | null) {
|
||||
authToken = token
|
||||
try {
|
||||
if (token) localStorage.setItem(TOKEN_KEY, token)
|
||||
else localStorage.removeItem(TOKEN_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
token: string
|
||||
user: {
|
||||
id: string
|
||||
name: string
|
||||
username: string
|
||||
}
|
||||
me: import('./client').MeResponse
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
user: {
|
||||
id: string
|
||||
name: string
|
||||
level: number
|
||||
xp: number
|
||||
maxXp: number
|
||||
coins: number
|
||||
missionProgress: number
|
||||
missionTarget: number
|
||||
}
|
||||
wallet: {
|
||||
cash: number
|
||||
goldGrams: number
|
||||
}
|
||||
progress: {
|
||||
completedChallenges: string[]
|
||||
completedLessons: string[]
|
||||
completedGames: string[]
|
||||
claimedRewards: string[]
|
||||
ownedItems: string[]
|
||||
mapLevels: Array<{
|
||||
id: number
|
||||
title: string
|
||||
stars: number
|
||||
maxStars: number
|
||||
status: 'completed' | 'current' | 'unlocked' | 'locked'
|
||||
lessonRoute?: string
|
||||
x: number
|
||||
y: number
|
||||
}>
|
||||
totalStars: number
|
||||
maxStars: number
|
||||
}
|
||||
achievements: Array<{
|
||||
id: string
|
||||
title: string
|
||||
description: string
|
||||
icon: string
|
||||
unlocked: boolean
|
||||
}>
|
||||
transactions: Array<{
|
||||
id: string
|
||||
type: 'income' | 'expense'
|
||||
title: string
|
||||
amount: number
|
||||
unit: 'تومان' | 'سکه' | 'گرم'
|
||||
date: string
|
||||
}>
|
||||
market: {
|
||||
selectedRange: '1d' | '7d' | '30d' | '90d' | '1y'
|
||||
}
|
||||
}
|
||||
|
||||
export interface MarketGoldResponse {
|
||||
currentPrice: number
|
||||
dailyChangePercent: number
|
||||
range: string
|
||||
history: number[]
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface DailyChallengeResponse {
|
||||
id: string
|
||||
question: string
|
||||
coinReward: number
|
||||
xpReward: number
|
||||
completed: boolean
|
||||
options: Array<{ id: string; label: string; icon: string; color: string }>
|
||||
}
|
||||
|
||||
export interface DailyChallengeCompleteResponse extends MeResponse {
|
||||
feedback: string
|
||||
alreadyCompleted: boolean
|
||||
}
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_URL ?? '/api'
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(init?.headers as Record<string, string> | undefined),
|
||||
}
|
||||
|
||||
const token = getAuthToken()
|
||||
if (token) headers.Authorization = `Bearer ${token}`
|
||||
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(`${API_BASE}${path}`, {
|
||||
...init,
|
||||
headers,
|
||||
})
|
||||
} catch {
|
||||
throw new Error('اتصال به سرور برقرار نشد. لطفاً backend را اجرا کنید.')
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ error: 'خطای سرور' }))
|
||||
throw new Error(body.error ?? 'خطای سرور')
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>
|
||||
}
|
||||
|
||||
export const api = {
|
||||
login: (username: string, password: string) =>
|
||||
request<AuthResponse>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username, password }),
|
||||
}),
|
||||
register: (username: string, password: string, name?: string) =>
|
||||
request<AuthResponse>('/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username, password, name }),
|
||||
}),
|
||||
getMe: () => request<MeResponse>('/me'),
|
||||
updateProfile: (name: string) =>
|
||||
request<MeResponse>('/me/profile', { method: 'PATCH', body: JSON.stringify({ name }) }),
|
||||
updatePassword: (currentPassword: string, newPassword: string) =>
|
||||
request<{ ok: true }>('/me/password', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ currentPassword, newPassword }),
|
||||
}),
|
||||
buyGold: (grams: number) =>
|
||||
request<MeResponse>('/wallet/gold/buy', { method: 'POST', body: JSON.stringify({ grams }) }),
|
||||
sellGold: (grams: number) =>
|
||||
request<MeResponse>('/wallet/gold/sell', { method: 'POST', body: JSON.stringify({ grams }) }),
|
||||
getMarketGold: (range: string) => request<MarketGoldResponse>(`/market/gold?range=${range}`),
|
||||
setMarketRange: (range: MeResponse['market']['selectedRange']) =>
|
||||
request<MeResponse>('/market/preferences', { method: 'PATCH', body: JSON.stringify({ range }) }),
|
||||
getDailyChallenge: () => request<DailyChallengeResponse>('/challenges/daily'),
|
||||
completeDailyChallenge: (optionId: string) =>
|
||||
request<DailyChallengeCompleteResponse>('/challenges/daily/complete', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ optionId }),
|
||||
}),
|
||||
completeGame: (gameId: string) =>
|
||||
request<MeResponse>(`/games/${gameId}/complete`, { method: 'POST', body: '{}' }),
|
||||
purchaseProduct: (productId: string) =>
|
||||
request<MeResponse>('/store/purchases', { method: 'POST', body: JSON.stringify({ productId }) }),
|
||||
completeLesson: (lessonId: string) =>
|
||||
request<MeResponse>(`/lessons/${lessonId}/complete`, { method: 'POST', body: '{}' }),
|
||||
completeMapLevel: (levelId: number, stars: number) =>
|
||||
request<MeResponse>(`/map/levels/${levelId}/complete`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ stars }),
|
||||
}),
|
||||
getGoldLandProgress: () => request<import('@/modules/gold-land/types/goldLand.types').GoldLandProgressResponse>('/gold-land/progress'),
|
||||
getGoldLandLevel: (levelId: number) =>
|
||||
request<import('@/modules/gold-land/types/goldLand.types').LevelDetailResponse>(
|
||||
`/gold-land/levels/${levelId}`,
|
||||
),
|
||||
startGoldLandLevel: (levelId: number) =>
|
||||
request<{ levelId: number; status: string }>(`/gold-land/levels/${levelId}/start`, {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
}),
|
||||
completeGoldLandLevel: (
|
||||
levelId: number,
|
||||
answers: import('@/modules/gold-land/types/goldLand.types').LessonSubmissionAnswer[],
|
||||
durationMs?: number,
|
||||
) =>
|
||||
request<import('@/modules/gold-land/types/goldLand.types').CompleteLevelResponse>(
|
||||
`/gold-land/levels/${levelId}/complete`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ answers, durationMs }),
|
||||
},
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { api, type MeResponse } from '@/api/client'
|
||||
import { useGamesStore } from '@/stores/games'
|
||||
import { useMarketStore } from '@/stores/market'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import { useWalletStore } from '@/stores/wallet'
|
||||
|
||||
export function applyMeResponse(data: MeResponse) {
|
||||
const userStore = useUserStore()
|
||||
const walletStore = useWalletStore()
|
||||
const gamesStore = useGamesStore()
|
||||
const marketStore = useMarketStore()
|
||||
|
||||
userStore.$patch({
|
||||
name: data.user.name,
|
||||
level: data.user.level,
|
||||
xp: data.user.xp,
|
||||
maxXp: data.user.maxXp,
|
||||
coins: data.user.coins,
|
||||
missionProgress: data.user.missionProgress,
|
||||
missionTarget: data.user.missionTarget,
|
||||
completedChallenges: [...data.progress.completedChallenges],
|
||||
completedLessons: [...data.progress.completedLessons],
|
||||
achievements: data.achievements.map((a) => ({ ...a })),
|
||||
})
|
||||
|
||||
walletStore.$patch({
|
||||
cash: data.wallet.cash,
|
||||
goldGrams: data.wallet.goldGrams,
|
||||
transactions: data.transactions.map((t) => ({ ...t })),
|
||||
})
|
||||
|
||||
gamesStore.$patch({
|
||||
completedGames: [...data.progress.completedGames],
|
||||
claimedRewards: [...data.progress.claimedRewards],
|
||||
ownedItems: [...data.progress.ownedItems],
|
||||
mapLevels: data.progress.mapLevels.map((l) => ({ ...l })),
|
||||
totalStars: data.progress.totalStars,
|
||||
maxStars: data.progress.maxStars,
|
||||
})
|
||||
|
||||
marketStore.$patch({
|
||||
selectedRange: data.market.selectedRange,
|
||||
})
|
||||
}
|
||||
|
||||
export async function bootstrapFromServer() {
|
||||
const data = await api.getMe()
|
||||
applyMeResponse(data)
|
||||
return data
|
||||
}
|
||||
|
||||
export async function syncMarketQuote(range: string) {
|
||||
const marketStore = useMarketStore()
|
||||
const quote = await api.getMarketGold(range)
|
||||
marketStore.$patch({
|
||||
currentPrice: quote.currentPrice,
|
||||
dailyChange: quote.dailyChangePercent,
|
||||
priceHistoryCache: {
|
||||
...marketStore.priceHistoryCache,
|
||||
[quote.range]: quote.history,
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user