Compare commits
No commits in common. "c4328b7698fceab0149bd26118d48bf098a7be74" and "2b86322b751f478af0823e564cac7834c2823f31" have entirely different histories.
c4328b7698
...
2b86322b75
@ -1,64 +1,101 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import React, { useState, useEffect } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Box, VStack, Spinner, Center, useToast } from '@chakra-ui/react';
|
import { Container, Tabs, TabList, TabPanels, Tab, TabPanel, useToast, Spinner, Center } from '@chakra-ui/react';
|
||||||
import { UserProfile } from './UserProfile';
|
import { UserProfile } from './UserProfile';
|
||||||
import { Shop } from './Shop';
|
import { Shop } from './Shop';
|
||||||
import { TransferBalance } from './TransferBalance';
|
import { TransferBalance } from './TransferBalance';
|
||||||
import { auth, getProfile, getShopItems, purchaseItem, transferBalance } from '../utils/api';
|
import * as api from '../utils/api';
|
||||||
import { IUser } from '../../backend/models/User';
|
import { IUser } from '../../backend/models/User';
|
||||||
import { IShopItem } from '../../backend/models/ShopItem';
|
import { IShopItem } from '../../backend/models/ShopItem';
|
||||||
import { isDemoMode, getDemoWebApp } from '../utils/demo';
|
|
||||||
|
|
||||||
type SafeUser = Omit<IUser, keyof Document>;
|
type SafeUser = Omit<IUser, keyof Document>;
|
||||||
|
|
||||||
export default function MainApp() {
|
export function MainApp() {
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
|
||||||
const [user, setUser] = useState<SafeUser | null>(null);
|
const [user, setUser] = useState<SafeUser | null>(null);
|
||||||
const [shopItems, setShopItems] = useState<IShopItem[]>([]);
|
const [shopItems, setShopItems] = useState<IShopItem[]>([]);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
|
|
||||||
const initApp = async () => {
|
useEffect(() => {
|
||||||
try {
|
const initApp = async () => {
|
||||||
setIsLoading(true);
|
try {
|
||||||
|
setIsLoading(true);
|
||||||
let webApp;
|
// Динамически импортируем SDK только на клиенте
|
||||||
if (isDemoMode()) {
|
|
||||||
webApp = getDemoWebApp();
|
|
||||||
} else {
|
|
||||||
const WebApp = (await import('@twa-dev/sdk')).default;
|
const WebApp = (await import('@twa-dev/sdk')).default;
|
||||||
webApp = WebApp;
|
|
||||||
|
const initData = WebApp.initData;
|
||||||
|
if (!initData) {
|
||||||
|
throw new Error('Приложение должно быть открыто в Telegram');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Авторизуем пользователя
|
||||||
|
const authData = await api.auth(
|
||||||
|
WebApp.initDataUnsafe.user?.id.toString() || '',
|
||||||
|
WebApp.initDataUnsafe.user?.username || ''
|
||||||
|
);
|
||||||
|
setUser(authData.user);
|
||||||
|
|
||||||
|
// Загружаем предметы магазина
|
||||||
|
const items = await api.getShopItems();
|
||||||
|
setShopItems(items);
|
||||||
|
} catch (error: any) {
|
||||||
|
toast({
|
||||||
|
title: 'Ошибка инициализации',
|
||||||
|
description: error.message,
|
||||||
|
status: 'error',
|
||||||
|
duration: 5000,
|
||||||
|
isClosable: true,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Авторизация пользователя
|
initApp();
|
||||||
const { user: telegramUser } = webApp.initDataUnsafe;
|
}, []);
|
||||||
const authResponse = await auth(telegramUser.id.toString(), telegramUser.username || 'anonymous');
|
|
||||||
|
|
||||||
// Получение данных пользователя и магазина
|
const handlePurchase = async (itemId: string) => {
|
||||||
const [profileData, shopData] = await Promise.all([
|
try {
|
||||||
getProfile(),
|
const result = await api.purchaseItem(itemId);
|
||||||
getShopItems()
|
setUser(result.user);
|
||||||
]);
|
|
||||||
|
|
||||||
setUser(profileData as SafeUser);
|
|
||||||
setShopItems(shopData);
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error('Initialization error:', error);
|
|
||||||
toast({
|
toast({
|
||||||
title: 'Ошибка инициализации',
|
title: 'Покупка успешна!',
|
||||||
description: error.message || 'Произошла ошибка при загрузке приложения',
|
status: 'success',
|
||||||
status: 'error',
|
duration: 3000,
|
||||||
duration: 5000,
|
isClosable: true,
|
||||||
|
});
|
||||||
|
} catch (error: any) {
|
||||||
|
toast({
|
||||||
|
title: 'Ошибка покупки',
|
||||||
|
description: error.response?.data?.error || 'Произошла ошибка',
|
||||||
|
status: 'error',
|
||||||
|
duration: 3000,
|
||||||
isClosable: true,
|
isClosable: true,
|
||||||
});
|
});
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
const handleTransfer = async (recipientUsername: string, amount: number) => {
|
||||||
initApp();
|
try {
|
||||||
}, []);
|
const result = await api.transferBalance(recipientUsername, amount);
|
||||||
|
setUser(prev => prev ? { ...prev, balance: result.balance } : null);
|
||||||
|
toast({
|
||||||
|
title: 'Перевод выполнен',
|
||||||
|
status: 'success',
|
||||||
|
duration: 3000,
|
||||||
|
isClosable: true,
|
||||||
|
});
|
||||||
|
} catch (error: any) {
|
||||||
|
toast({
|
||||||
|
title: 'Ошибка перевода',
|
||||||
|
description: error.response?.data?.error || 'Произошла ошибка',
|
||||||
|
status: 'error',
|
||||||
|
duration: 3000,
|
||||||
|
isClosable: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
@ -69,73 +106,45 @@ export default function MainApp() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return (
|
return null;
|
||||||
<Center h="100vh">
|
|
||||||
<Box p={4} textAlign="center">
|
|
||||||
Пожалуйста, авторизуйтесь через Telegram или используйте демо-режим
|
|
||||||
</Box>
|
|
||||||
</Center>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<VStack spacing={6} p={4}>
|
<Container maxW="container.xl" py={8}>
|
||||||
<UserProfile
|
<Tabs isFitted variant="enclosed">
|
||||||
username={user.username}
|
<TabList mb="1em">
|
||||||
level={user.level}
|
<Tab>Профиль</Tab>
|
||||||
experience={user.experience}
|
<Tab>Магазин</Tab>
|
||||||
balance={user.balance}
|
<Tab>Перевод</Tab>
|
||||||
achievements={user.achievements}
|
</TabList>
|
||||||
/>
|
|
||||||
<Shop
|
<TabPanels>
|
||||||
items={shopItems}
|
<TabPanel>
|
||||||
userBalance={user.balance}
|
<UserProfile
|
||||||
onPurchase={async (item: IShopItem) => {
|
username={user.username}
|
||||||
try {
|
level={user.level}
|
||||||
const response = await purchaseItem(item._id.toString());
|
experience={user.experience}
|
||||||
setUser(response.user as SafeUser);
|
balance={user.balance}
|
||||||
toast({
|
achievements={user.achievements}
|
||||||
title: 'Успешная покупка',
|
/>
|
||||||
description: `Вы приобрели ${item.name}`,
|
</TabPanel>
|
||||||
status: 'success',
|
|
||||||
duration: 3000,
|
<TabPanel>
|
||||||
isClosable: true,
|
<Shop
|
||||||
});
|
items={shopItems}
|
||||||
} catch (error: any) {
|
userBalance={user.balance}
|
||||||
toast({
|
onPurchase={handlePurchase}
|
||||||
title: 'Ошибка покупки',
|
/>
|
||||||
description: error.message || 'Произошла ошибка при покупке',
|
</TabPanel>
|
||||||
status: 'error',
|
|
||||||
duration: 3000,
|
<TabPanel>
|
||||||
isClosable: true,
|
<TransferBalance
|
||||||
});
|
userBalance={user.balance}
|
||||||
}
|
onTransfer={handleTransfer}
|
||||||
}}
|
/>
|
||||||
/>
|
</TabPanel>
|
||||||
<TransferBalance
|
</TabPanels>
|
||||||
userBalance={user.balance}
|
</Tabs>
|
||||||
onTransfer={async (username, amount) => {
|
</Container>
|
||||||
try {
|
|
||||||
const response = await transferBalance(username, amount);
|
|
||||||
setUser(prev => ({ ...prev!, balance: response.balance } as SafeUser));
|
|
||||||
toast({
|
|
||||||
title: 'Успешный перевод',
|
|
||||||
description: `Вы перевели ${amount} монет пользователю ${username}`,
|
|
||||||
status: 'success',
|
|
||||||
duration: 3000,
|
|
||||||
isClosable: true,
|
|
||||||
});
|
|
||||||
} catch (error: any) {
|
|
||||||
toast({
|
|
||||||
title: 'Ошибка перевода',
|
|
||||||
description: error.message || 'Произошла ошибка при переводе',
|
|
||||||
status: 'error',
|
|
||||||
duration: 3000,
|
|
||||||
isClosable: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</VStack>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
@ -1,23 +1,34 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Box, SimpleGrid, Button, Text, Image, useToast } from '@chakra-ui/react';
|
import {
|
||||||
|
Box,
|
||||||
|
Grid,
|
||||||
|
Text,
|
||||||
|
Button,
|
||||||
|
Image,
|
||||||
|
VStack,
|
||||||
|
useToast,
|
||||||
|
useColorModeValue,
|
||||||
|
} from '@chakra-ui/react';
|
||||||
import { IShopItem } from '../../backend/models/ShopItem';
|
import { IShopItem } from '../../backend/models/ShopItem';
|
||||||
|
|
||||||
interface ShopProps {
|
interface ShopProps {
|
||||||
items: IShopItem[];
|
items: IShopItem[];
|
||||||
userBalance: number;
|
userBalance: number;
|
||||||
onPurchase: (item: IShopItem) => Promise<void>;
|
onPurchase: (itemId: string) => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Shop({ items, userBalance, onPurchase }: ShopProps) {
|
export const Shop: React.FC<ShopProps> = ({ items, userBalance, onPurchase }) => {
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
|
const bgColor = useColorModeValue('white', 'gray.800');
|
||||||
|
const borderColor = useColorModeValue('gray.200', 'gray.700');
|
||||||
|
|
||||||
const handlePurchase = async (item: IShopItem) => {
|
const handlePurchase = async (item: IShopItem) => {
|
||||||
if (userBalance < item.price) {
|
if (userBalance < item.price) {
|
||||||
toast({
|
toast({
|
||||||
title: 'Недостаточно средств',
|
title: 'Недостаточно средств',
|
||||||
description: `Для покупки ${item.name} нужно ${item.price} монет`,
|
description: 'У вас недостаточно Campfire монет для покупки этого предмета',
|
||||||
status: 'error',
|
status: 'error',
|
||||||
duration: 3000,
|
duration: 3000,
|
||||||
isClosable: true,
|
isClosable: true,
|
||||||
@ -25,46 +36,74 @@ export function Shop({ items, userBalance, onPurchase }: ShopProps) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await onPurchase(item);
|
try {
|
||||||
|
await onPurchase(item.id);
|
||||||
|
toast({
|
||||||
|
title: 'Покупка успешна!',
|
||||||
|
description: `Вы приобрели ${item.name}`,
|
||||||
|
status: 'success',
|
||||||
|
duration: 3000,
|
||||||
|
isClosable: true,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
toast({
|
||||||
|
title: 'Ошибка при покупке',
|
||||||
|
description: 'Произошла ошибка при совершении покупки',
|
||||||
|
status: 'error',
|
||||||
|
duration: 3000,
|
||||||
|
isClosable: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box w="100%">
|
<Box p={4}>
|
||||||
<Text fontSize="2xl" mb={4}>Магазин</Text>
|
<Text fontSize="2xl" fontWeight="bold" mb={4}>
|
||||||
<Text mb={4}>Ваш баланс: {userBalance} монет</Text>
|
Магазин
|
||||||
<SimpleGrid columns={[1, 2, 3]} spacing={6}>
|
</Text>
|
||||||
|
<Text mb={4}>
|
||||||
|
Ваш баланс: {userBalance} 🔥
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
<Grid templateColumns={['1fr', 'repeat(2, 1fr)', 'repeat(3, 1fr)']} gap={4}>
|
||||||
{items.map((item) => (
|
{items.map((item) => (
|
||||||
<Box
|
<Box
|
||||||
key={item._id.toString()}
|
key={item.id}
|
||||||
|
p={4}
|
||||||
borderWidth="1px"
|
borderWidth="1px"
|
||||||
borderRadius="lg"
|
borderRadius="lg"
|
||||||
overflow="hidden"
|
borderColor={borderColor}
|
||||||
p={4}
|
bg={bgColor}
|
||||||
>
|
>
|
||||||
{item.imageUrl && (
|
<VStack spacing={3}>
|
||||||
<Image
|
{item.imageUrl && (
|
||||||
src={item.imageUrl}
|
<Image
|
||||||
alt={item.name}
|
src={item.imageUrl}
|
||||||
height="200px"
|
alt={item.name}
|
||||||
width="100%"
|
boxSize="100px"
|
||||||
objectFit="cover"
|
objectFit="cover"
|
||||||
mb={4}
|
borderRadius="md"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<Text fontSize="xl" mb={2}>{item.name}</Text>
|
<Text fontWeight="bold">{item.name}</Text>
|
||||||
<Text mb={2}>{item.description}</Text>
|
<Text fontSize="sm" color="gray.500">
|
||||||
<Text mb={4} color="green.500">{item.price} монет</Text>
|
{item.description}
|
||||||
<Button
|
</Text>
|
||||||
colorScheme="blue"
|
<Text color="green.500" fontWeight="bold">
|
||||||
onClick={() => handlePurchase(item)}
|
{item.price} 🔥
|
||||||
isDisabled={userBalance < item.price}
|
</Text>
|
||||||
w="100%"
|
<Button
|
||||||
>
|
colorScheme="blue"
|
||||||
Купить
|
width="full"
|
||||||
</Button>
|
onClick={() => handlePurchase(item)}
|
||||||
|
isDisabled={userBalance < item.price}
|
||||||
|
>
|
||||||
|
Купить
|
||||||
|
</Button>
|
||||||
|
</VStack>
|
||||||
</Box>
|
</Box>
|
||||||
))}
|
))}
|
||||||
</SimpleGrid>
|
</Grid>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
}
|
};
|
@ -1,39 +0,0 @@
|
|||||||
// Демо данные для тестирования без Telegram
|
|
||||||
const demoUser = {
|
|
||||||
id: 'demo_user',
|
|
||||||
first_name: 'Demo',
|
|
||||||
username: 'demo_user',
|
|
||||||
language_code: 'ru'
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isDemoMode = () => {
|
|
||||||
return typeof window !== 'undefined' && new URLSearchParams(window.location.search).has('demo');
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getDemoWebApp = () => {
|
|
||||||
return {
|
|
||||||
initData: 'demo_mode',
|
|
||||||
initDataUnsafe: {
|
|
||||||
user: demoUser,
|
|
||||||
start_param: 'demo'
|
|
||||||
},
|
|
||||||
platform: 'demo',
|
|
||||||
colorScheme: 'light',
|
|
||||||
themeParams: {
|
|
||||||
bg_color: '#ffffff',
|
|
||||||
text_color: '#000000',
|
|
||||||
hint_color: '#999999',
|
|
||||||
link_color: '#2481cc',
|
|
||||||
button_color: '#2481cc',
|
|
||||||
button_text_color: '#ffffff'
|
|
||||||
},
|
|
||||||
isExpanded: true,
|
|
||||||
viewportHeight: window.innerHeight,
|
|
||||||
viewportStableHeight: window.innerHeight,
|
|
||||||
headerColor: '#ffffff',
|
|
||||||
backgroundColor: '#ffffff',
|
|
||||||
ready: () => {},
|
|
||||||
expand: () => {},
|
|
||||||
close: () => {}
|
|
||||||
};
|
|
||||||
};
|
|
@ -8,11 +8,11 @@ export interface IAchievement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface IInventoryItem {
|
export interface IInventoryItem {
|
||||||
itemId: mongoose.Types.ObjectId;
|
itemId: string;
|
||||||
name: string;
|
name: string;
|
||||||
description: string;
|
description: string;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
imageUrl: string;
|
imageUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IUser extends Document {
|
export interface IUser extends Document {
|
||||||
@ -23,7 +23,6 @@ export interface IUser extends Document {
|
|||||||
balance: number;
|
balance: number;
|
||||||
achievements: IAchievement[];
|
achievements: IAchievement[];
|
||||||
inventory: IInventoryItem[];
|
inventory: IInventoryItem[];
|
||||||
addAchievement: (achievement: IAchievement) => Promise<void>;
|
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
}
|
}
|
||||||
@ -41,7 +40,7 @@ const UserSchema: Schema = new Schema({
|
|||||||
dateUnlocked: { type: Date, default: Date.now }
|
dateUnlocked: { type: Date, default: Date.now }
|
||||||
}],
|
}],
|
||||||
inventory: [{
|
inventory: [{
|
||||||
itemId: { type: Schema.Types.ObjectId, ref: 'ShopItem' },
|
itemId: String,
|
||||||
name: String,
|
name: String,
|
||||||
description: String,
|
description: String,
|
||||||
quantity: Number,
|
quantity: Number,
|
||||||
@ -75,7 +74,9 @@ UserSchema.methods.addAchievement = async function(achievement: IAchievement) {
|
|||||||
// Награда за достижение
|
// Награда за достижение
|
||||||
this.balance += 50;
|
this.balance += 50;
|
||||||
await this.save();
|
await this.save();
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default mongoose.model<IUser>('User', UserSchema);
|
export default mongoose.model<IUser>('User', UserSchema);
|
Loading…
Reference in New Issue
Block a user