diff --git a/.env b/.env new file mode 100644 index 0000000..8216693 --- /dev/null +++ b/.env @@ -0,0 +1,3 @@ +VITE_API_KEY=test +VITE_API_PUBLIC_KEY=ruspet_public_key_2026 +VITE_API_PRIVATE_KEY=ruspet_private_key_SUPER_SECRET_2026 \ No newline at end of file diff --git a/.gitea/workflows/deploy-frontend.yml b/.gitea/workflows/deploy-frontend.yml new file mode 100644 index 0000000..42a6f91 --- /dev/null +++ b/.gitea/workflows/deploy-frontend.yml @@ -0,0 +1,104 @@ +name: Deploy Manager Frontend + +on: + push: + branches: [main] + +env: + REPO_DIR: "/workspace/manager_orders_app" + REPO_URL: "https://72.56.235.246.nip.io/gitea/romanskijdev/manager_orders_app.git" # Укажите точную ссылку на ваш репозиторий в Gitea + BUILD_DIR: "/var/www/znzt.ruspet.tw1.ru" + +jobs: + build-and-deploy: + runs-on: self-hosted + timeout-minutes: 15 + + steps: + - name: 📋 Deployment Info + run: | + echo "════════════════════════════════════════" + echo "🚀 Starting Manager App deployment" + echo "════════════════════════════════════════" + echo "Branch: ${{ github.ref }}" + echo "Commit: ${{ github.sha }}" + echo "Author: ${{ github.actor }}" + echo "Time: $(date '+%Y-%m-%d %H:%M:%S')" + echo "Runner: $(hostname)" + echo "════════════════════════════════════════" + + - name: 📦 Checkout + run: | + git config --global --add safe.directory "$REPO_DIR" + if [ -d "$REPO_DIR/.git" ]; then + echo "📦 Updating existing repo..." + cd "$REPO_DIR" + git fetch origin + git reset --hard origin/main + else + echo "📦 Cloning repo..." + git clone "$REPO_URL" "$REPO_DIR" + fi + + - name: 💾 Cache node_modules + uses: actions/cache@v3 + with: + path: | + ~/.npm + $REPO_DIR/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-node- + + - name: 📥 Install dependencies + run: | + cd "$REPO_DIR" + npm ci + + - name: 🔨 Build + run: | + cd "$REPO_DIR" + npm run build + echo "✅ Build completed" + ls -la dist/ + + - name: 📤 Deploy to web server + run: | + echo "📤 Deploying to $BUILD_DIR..." + sudo mkdir -p "$BUILD_DIR" + sudo rm -rf "$BUILD_DIR"/* + sudo cp -r "$REPO_DIR/dist/"* "$BUILD_DIR/" + sudo chown -R www-data:www-data "$BUILD_DIR" + sudo chmod -R 755 "$BUILD_DIR" + echo "✅ Frontend deployed successfully" + + - name: ✅ Verify deployment + run: | + echo "🔍 Verifying deployment..." + if [ -f "$BUILD_DIR/index.html" ]; then + echo "✅ index.html exists" + ls -lh "$BUILD_DIR/index.html" + echo "✅ Deployment verified successfully" + else + echo "❌ index.html not found" + exit 1 + fi + + - name: 📊 Deployment Summary + if: always() + run: | + echo "════════════════════════════════════════" + echo "📊 DEPLOYMENT SUMMARY" + echo "════════════════════════════════════════" + echo "Status: ${{ job.status }}" + echo "Branch: ${{ github.ref }}" + echo "Commit: ${{ github.sha }}" + echo "Duration: $SECONDS seconds" + echo "════════════════════════════════════════" + + if [ "${{ job.status }}" == "success" ]; then + echo "✅ Manager app deployment completed!" + echo "🌐 Available at: https://znzt.ruspet.tw1.ru" + else + echo "❌ Manager app deployment failed!" + fi \ No newline at end of file diff --git a/index.html b/index.html index 7687076..cf2f98d 100644 --- a/index.html +++ b/index.html @@ -1,10 +1,10 @@ - + - manager-orders-app + Заказ товаров на месяц
diff --git a/package-lock.json b/package-lock.json index ad089e8..77a9506 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "@mantine/core": "^9.5.2", "@mantine/dates": "^9.5.2", + "@mantine/form": "^9.5.2", "@mantine/hooks": "^9.5.2", "@mantine/notifications": "^9.5.2", "@tabler/icons-react": "^3.46.0", @@ -615,6 +616,20 @@ "react-dom": "^19.2.0" } }, + "node_modules/@mantine/form": { + "version": "9.5.2", + "resolved": "https://registry.npmjs.org/@mantine/form/-/form-9.5.2.tgz", + "integrity": "sha512-9zWyAvEIn5QGfDa7Mxf+iCeEnUHtIam2avY8Csx6PsHqWmRSl9eYfQFrofv6FcR6eAbVUzQHzL/gpqZ3BzPt9g==", + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "fast-deep-equal": "^3.1.3", + "klona": "^2.0.6" + }, + "peerDependencies": { + "react": "^19.2.0" + } + }, "node_modules/@mantine/hooks": { "version": "9.5.2", "resolved": "https://registry.npmjs.org/@mantine/hooks/-/hooks-9.5.2.tgz", @@ -922,6 +937,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, "node_modules/@tabler/icons": { "version": "3.46.0", "resolved": "https://registry.npmjs.org/@tabler/icons/-/icons-3.46.0.tgz", @@ -1858,7 +1879,6 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, "license": "MIT" }, "node_modules/fast-json-stable-stringify": { @@ -2280,6 +2300,15 @@ "json-buffer": "3.0.1" } }, + "node_modules/klona": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/klona/-/klona-2.0.6.tgz", + "integrity": "sha512-dhG34DXATL5hSxJbIexCft8FChFXtmskoZYnoPWjXQuebWYCNkVeV3KkGegCK9CP1oswI/vQibS2GY7Em/sJJA==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, "node_modules/levn": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", diff --git a/package.json b/package.json index fd3603f..083658b 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "dependencies": { "@mantine/core": "^9.5.2", "@mantine/dates": "^9.5.2", + "@mantine/form": "^9.5.2", "@mantine/hooks": "^9.5.2", "@mantine/notifications": "^9.5.2", "@tabler/icons-react": "^3.46.0", diff --git a/src/App.tsx b/src/App.tsx index 9ca8e8d..c57d672 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,122 +1,23 @@ -import { useState } from 'react' -import heroImg from './assets/hero.png' -import reactLogo from './assets/react.svg' -import viteLogo from './assets/vite.svg' -import './App.css' +import { Routes, Route, Navigate } from 'react-router-dom' +import Login from './pages/Login' +import OrdersPage from './pages/OrdersPage' +import React from "react"; -function App() { - const [count, setCount] = useState(0) - - return ( - <> -
-
- - React logo - Vite logo -
-
-

Get started

-

- Edit src/App.tsx and save to test HMR -

-
- -
- -
- -
-
- -

Documentation

-

Your questions, answered

- -
-
- -

Connect with us

-

Join the Vite community

- -
-
- -
-
- - ) +function ProtectedRoute({ children }: { children: React.ReactNode }) { + const token = localStorage.getItem('token') + if (!token) return + return <>{children} } -export default App +export default function App() { + return ( + + } /> + + + + } /> + + ) +} \ No newline at end of file diff --git a/src/api/client.ts b/src/api/client.ts new file mode 100644 index 0000000..5cfda61 --- /dev/null +++ b/src/api/client.ts @@ -0,0 +1,59 @@ +import axios from 'axios' +import CryptoJS from 'crypto-js' + +// Функция генерации HMAC подписи +function generateHmacSignature(publicKey: string, timestamp: string, privateKey: string): string { + const message = publicKey + ":" + timestamp + const hash = CryptoJS.HmacSHA256(message, privateKey) + return hash.toString(CryptoJS.enc.Hex) +} + +function getOrCreateDeviceId(): string { + let deviceId = localStorage.getItem('device_id') + if (!deviceId) { + deviceId = crypto.randomUUID() + localStorage.setItem('device_id', deviceId) + } + return deviceId +} + +const apiClient = axios.create({ + baseURL: import.meta.env.VITE_API_BASE_URL || '/api', + headers: { + 'Content-Type': 'application/json', + }, +}) + +apiClient.interceptors.request.use(async (config) => { + const token = localStorage.getItem('token') + if (token) { + config.headers.Authorization = `Bearer ${token}` + } + + const publicKey = import.meta.env.VITE_API_PUBLIC_KEY || '' + const privateKey = import.meta.env.VITE_API_PRIVATE_KEY || '' + const timestamp = Math.floor(Date.now() / 1000).toString() + + if (publicKey && privateKey) { + const signature = generateHmacSignature(publicKey, timestamp, privateKey) + config.headers.ApiKey = signature + } + + config.headers['X-Timestamp'] = timestamp + config.headers['x-device-id'] = getOrCreateDeviceId() + + return config +}) + +apiClient.interceptors.response.use( + (response) => response, + (error) => { + if (error.response?.status === 401) { + localStorage.removeItem('token') + window.location.href = '/login' + } + return Promise.reject(error) + } +) + +export default apiClient \ No newline at end of file diff --git a/src/api/monthlyOrders.ts b/src/api/monthlyOrders.ts new file mode 100644 index 0000000..692bd4d --- /dev/null +++ b/src/api/monthlyOrders.ts @@ -0,0 +1,12 @@ +import apiClient from './client' +import type {FrontendOrderMatrix, MonthlyOrderClient} from "../types/orders.ts"; + +export const monthlyOrdersApi = { + // Получение матрицы (клиенты из гугла + номенклатура + черновики из БД) + getMatrix: () => + apiClient.get<{ data: FrontendOrderMatrix }>('/monthly-orders/matrix'), + + // Сохранение заказов (черновик или отправка) + saveOrders: (orders: MonthlyOrderClient[]) => + apiClient.post<{ data: string }>('/monthly-orders/save', { orders }), +} \ No newline at end of file diff --git a/src/main.tsx b/src/main.tsx index bef5202..663e45a 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,10 +1,21 @@ -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import './index.css' -import App from './App.tsx' +import React from 'react' +import ReactDOM from 'react-dom/client' +import { BrowserRouter } from 'react-router-dom' +import { MantineProvider } from '@mantine/core' // 👈 Импортируем провайдер +import '@mantine/core/styles.css' // 👈 Обязательно подключаем стили Mantine! +import { Notifications } from '@mantine/notifications' // если используете нотификации +import '@mantine/notifications/styles.css' -createRoot(document.getElementById('root')!).render( - - - , -) +import App from './App' + +ReactDOM.createRoot(document.getElementById('root')!).render( + + + {/* Обязательно оборачиваем приложение в MantineProvider */} + + + + + + , +) \ No newline at end of file diff --git a/src/pages/Login.tsx b/src/pages/Login.tsx new file mode 100644 index 0000000..b0f07bf --- /dev/null +++ b/src/pages/Login.tsx @@ -0,0 +1,78 @@ +import { useState } from 'react' +import { TextInput, PasswordInput, Button, Paper, Title, Container, Stack, Text, Alert } from '@mantine/core' +import { useNavigate } from 'react-router-dom' +import apiClient from "../api/client.ts"; +import {useForm} from "@mantine/form"; + +export default function Login() { + const [error, setError] = useState(null) + const [loading, setLoading] = useState(false) + const navigate = useNavigate() + + const form = useForm({ + initialValues: { + login: '', + password: '', + }, + }) + + const handleSubmit = async (values: typeof form.values) => { + setLoading(true) + setError(null) + try { + // Используем стандартный эндпоинт логина бэкенда + const response = await apiClient.post('/auth/login', values) + const token = response.data.token || response.data.data?.token + + if (token) { + localStorage.setItem('token', token) + navigate('/') + } else { + setError('Не удалось получить токен авторизации') + } + } catch (err: any) { + setError(err.response?.data?.error_description || 'Ошибка входа. Проверьте логин и пароль.') + } finally { + setLoading(false) + } + } + + return ( + + Заказ товаров на месяц + + Войдите под своей учетной записью менеджера + + + +
+ + {error && ( + + {error} + + )} + + + + + + + +
+
+
+ ) +} \ No newline at end of file diff --git a/src/pages/OrdersPage.tsx b/src/pages/OrdersPage.tsx new file mode 100644 index 0000000..364f119 --- /dev/null +++ b/src/pages/OrdersPage.tsx @@ -0,0 +1,341 @@ +import React, { useState, useEffect } from 'react' +import { + Box, Table, Title, Text, Paper, Stack, Button, Group, + NumberInput, Select, Textarea, Badge, LoadingOverlay, Card, Divider +} from '@mantine/core' +import { useMediaQuery } from '@mantine/hooks' +import { notifications } from '@mantine/notifications' +import { IconDeviceFloppy, IconLock } from '@tabler/icons-react' +import type {FrontendOrderMatrix, MonthlyOrderClient, NomenclatureItem} from "../types/orders.ts"; +import {monthlyOrdersApi} from "../api/monthlyOrders.ts"; + +export default function OrdersPage() { + const [data, setData] = useState(null) + const [loading, setLoading] = useState(true) + const [saving, setSaving] = useState(false) + const [editableOrders, setEditableOrders] = useState>({}) + + const isMobile = useMediaQuery('(max-width: 768px)') + const [activeClientName, setActiveClientName] = useState(null) + + const loadData = async (preserveActive = false) => { + try { + setLoading(true) + const res = await monthlyOrdersApi.getMatrix() + const matrix = res.data.data + setData(matrix) + + const initialMap: Record = {} + matrix.clients.forEach((c, idx) => { + const clientName = c.google_data.name + if (!preserveActive && idx === 0) { + setActiveClientName(clientName) + } + + if (c.db_order) { + initialMap[clientName] = { ...c.db_order } + } else { + initialMap[clientName] = { + client_name: clientName, + items: [], + manager_comment: '', + decade: '1 декада', + delivery: 'Самовывоз', + payment_form: 'Безналичная', + } + } + }) + setEditableOrders(initialMap) + } catch { + notifications.show({ title: 'Ошибка', message: 'Не удалось загрузить данные заказов', color: 'red' }) + } finally { + setLoading(false) + } + } + + useEffect(() => { + loadData(false) + }, []) + + const handleQuantityChange = (clientName: string, nomName: string, nomType: string, qty: number | null) => { + setEditableOrders(prev => { + const currentOrder = prev[clientName] || { client_name: clientName, items: [] } + const items = [...(currentOrder.items || [])] + + const existingIndex = items.findIndex(i => i.nomenclature_name === nomName) + if (existingIndex >= 0) { + if (qty === null || qty === 0) { + items.splice(existingIndex, 1) + } else { + items[existingIndex].quantity = qty + } + } else if (qty !== null && qty > 0) { + items.push({ nomenclature_name: nomName, nomenclature_type: nomType, quantity: qty }) + } + + return { + ...prev, + [clientName]: { ...currentOrder, items } + } + }) + } + + const validateBeforeSave = (): boolean => { + for (const [clientName, order] of Object.entries(editableOrders)) { + const hasItems = order.items && order.items.length > 0 + if (hasItems && (!order.manager_comment || order.manager_comment.trim() === '')) { + notifications.show({ + title: 'Внимание', + message: `Для клиента "${clientName}" указан заказ, но не заполнен обязательный комментарий!`, + color: 'yellow' + }) + return false + } + } + return true + } + + const handleSave = async () => { + if (!validateBeforeSave()) return + + try { + setSaving(true) + const ordersArray = Object.values(editableOrders) + await monthlyOrdersApi.saveOrders(ordersArray) + notifications.show({ title: 'Успешно', message: 'Изменения сохранены', color: 'green' }) + loadData(true) // Сохраняем текущего выбранного клиента при перезагрузке + } catch { + notifications.show({ title: 'Ошибка', message: 'Не удалось сохранить заказы', color: 'red' }) + } finally { + setSaving(false) + } + } + + if (loading) return + if (!data) return Нет данных + + return ( + + +
+ Заказ товаров на месяц + {data.settings?.deadline_date && ( + + Дедлайн: {new Date(data.settings.deadline_date).toLocaleString()} + + )} +
+ + + {data.is_locked ? ( + }> + Прием закрыт + + ) : ( + + )} + +
+ + {isMobile ? ( + + setEditableOrders((prev) => ({ + ...prev, + [clientName]: { ...prev[clientName], decade: v } + }))} + placeholder="Декада" + /> +