Added znzt web app
This commit is contained in:
parent
0eb78da93d
commit
00e4ae9f8c
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>manager-orders-app</title>
|
||||
<title>Заказ товаров на месяц</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
139
src/App.tsx
139
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 (
|
||||
<>
|
||||
<section id="center">
|
||||
<div className="hero">
|
||||
<img src={heroImg} className="base" width="170" height="179" alt="" />
|
||||
<img src={reactLogo} className="framework" alt="React logo" />
|
||||
<img src={viteLogo} className="vite" alt="Vite logo" />
|
||||
</div>
|
||||
<div>
|
||||
<h1>Get started</h1>
|
||||
<p>
|
||||
Edit <code>src/App.tsx</code> and save to test <code>HMR</code>
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="counter"
|
||||
onClick={() => setCount((count) => count + 1)}
|
||||
>
|
||||
Count is {count}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<div className="ticks"></div>
|
||||
|
||||
<section id="next-steps">
|
||||
<div id="docs">
|
||||
<svg className="icon" role="presentation" aria-hidden="true">
|
||||
<use href="/icons.svg#documentation-icon"></use>
|
||||
</svg>
|
||||
<h2>Documentation</h2>
|
||||
<p>Your questions, answered</p>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="https://vite.dev/" target="_blank">
|
||||
<img className="logo" src={viteLogo} alt="" />
|
||||
Explore Vite
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://react.dev/" target="_blank">
|
||||
<img className="button-icon" src={reactLogo} alt="" />
|
||||
Learn more
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div id="social">
|
||||
<svg className="icon" role="presentation" aria-hidden="true">
|
||||
<use href="/icons.svg#social-icon"></use>
|
||||
</svg>
|
||||
<h2>Connect with us</h2>
|
||||
<p>Join the Vite community</p>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="https://github.com/vitejs/vite" target="_blank">
|
||||
<svg
|
||||
className="button-icon"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<use href="/icons.svg#github-icon"></use>
|
||||
</svg>
|
||||
GitHub
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://chat.vite.dev/" target="_blank">
|
||||
<svg
|
||||
className="button-icon"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<use href="/icons.svg#discord-icon"></use>
|
||||
</svg>
|
||||
Discord
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://x.com/vite_js" target="_blank">
|
||||
<svg
|
||||
className="button-icon"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<use href="/icons.svg#x-icon"></use>
|
||||
</svg>
|
||||
X.com
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://bsky.app/profile/vite.dev" target="_blank">
|
||||
<svg
|
||||
className="button-icon"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<use href="/icons.svg#bluesky-icon"></use>
|
||||
</svg>
|
||||
Bluesky
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="ticks"></div>
|
||||
<section id="spacer"></section>
|
||||
</>
|
||||
)
|
||||
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const token = localStorage.getItem('token')
|
||||
if (!token) return <Navigate to="/login" replace />
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default App
|
||||
export default function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/" element={
|
||||
<ProtectedRoute>
|
||||
<OrdersPage />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
@ -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 }),
|
||||
}
|
||||
29
src/main.tsx
29
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(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
import App from './App'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter>
|
||||
{/* Обязательно оборачиваем приложение в MantineProvider */}
|
||||
<MantineProvider defaultColorScheme="light">
|
||||
<Notifications />
|
||||
<App />
|
||||
</MantineProvider>
|
||||
</BrowserRouter>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
|
|
@ -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<string | null>(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 (
|
||||
<Container size={420} my={100}>
|
||||
<Title ta="center" fw={700}>Заказ товаров на месяц</Title>
|
||||
<Text c="dimmed" size="sm" ta="center" mt={5} mb="xl">
|
||||
Войдите под своей учетной записью менеджера
|
||||
</Text>
|
||||
|
||||
<Paper withBorder shadow="md" p={30} radius="md">
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="md">
|
||||
{error && (
|
||||
<Alert color="red" variant="light">
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<TextInput
|
||||
label="Логин"
|
||||
placeholder="Логин"
|
||||
required
|
||||
{...form.getInputProps('login')}
|
||||
/>
|
||||
|
||||
<PasswordInput
|
||||
label="Пароль"
|
||||
placeholder="Пароль"
|
||||
required
|
||||
{...form.getInputProps('password')}
|
||||
/>
|
||||
|
||||
<Button type="submit" loading={loading} fullWidth mt="xl">
|
||||
Войти
|
||||
</Button>
|
||||
</Stack>
|
||||
</form>
|
||||
</Paper>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
|
|
@ -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<FrontendOrderMatrix | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [editableOrders, setEditableOrders] = useState<Record<string, MonthlyOrderClient>>({})
|
||||
|
||||
const isMobile = useMediaQuery('(max-width: 768px)')
|
||||
const [activeClientName, setActiveClientName] = useState<string | null>(null)
|
||||
|
||||
const loadData = async (preserveActive = false) => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const res = await monthlyOrdersApi.getMatrix()
|
||||
const matrix = res.data.data
|
||||
setData(matrix)
|
||||
|
||||
const initialMap: Record<string, MonthlyOrderClient> = {}
|
||||
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 <LoadingOverlay visible />
|
||||
if (!data) return <Text>Нет данных</Text>
|
||||
|
||||
return (
|
||||
<Box p={{ base: 'xs', md: 'md' }} maw={1600} mx="auto">
|
||||
<Group justify="space-between" mb="lg">
|
||||
<div>
|
||||
<Title order={2} size="h3">Заказ товаров на месяц</Title>
|
||||
{data.settings?.deadline_date && (
|
||||
<Text size="xs" c="dimmed">
|
||||
Дедлайн: {new Date(data.settings.deadline_date).toLocaleString()}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Group>
|
||||
{data.is_locked ? (
|
||||
<Badge color="red" size="md" leftSection={<IconLock size={12} />}>
|
||||
Прием закрыт
|
||||
</Badge>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
loading={saving}
|
||||
size="sm"
|
||||
leftSection={<IconDeviceFloppy size={16} />}
|
||||
>
|
||||
Сохранить
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
{isMobile ? (
|
||||
<Stack gap="md">
|
||||
<Select
|
||||
label="Выберите клиента"
|
||||
data={data.clients.map(c => c.google_data.name)}
|
||||
value={activeClientName}
|
||||
onChange={setActiveClientName}
|
||||
/>
|
||||
|
||||
{activeClientName && (
|
||||
<ClientCardView
|
||||
clientName={activeClientName}
|
||||
nomenclatures={data.nomenclatures}
|
||||
editableOrders={editableOrders}
|
||||
setEditableOrders={setEditableOrders}
|
||||
handleQuantityChange={handleQuantityChange}
|
||||
isLocked={data.is_locked}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
) : (
|
||||
<Paper withBorder style={{ overflowX: 'auto' }}>
|
||||
<Table stickyHeader striped highlightOnHover>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th style={{ minWidth: 220, position: 'sticky', left: 0, background: 'var(--mantine-color-body)', zIndex: 2 }}>
|
||||
Номенклатура
|
||||
</Table.Th>
|
||||
{data.clients.map(c => (
|
||||
<Table.Th key={c.google_data.name} style={{ minWidth: 180, textAlign: 'center' }}>
|
||||
{c.google_data.name}
|
||||
<BlockMeta
|
||||
clientName={c.google_data.name}
|
||||
editableOrders={editableOrders}
|
||||
setEditableOrders={setEditableOrders}
|
||||
isLocked={data.is_locked}
|
||||
/>
|
||||
</Table.Th>
|
||||
))}
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{data.nomenclatures.map(nom => (
|
||||
<Table.Tr key={nom.name}>
|
||||
<Table.Td style={{ position: 'sticky', left: 0, background: 'var(--mantine-color-body)', fontWeight: 500, zIndex: 1 }}>
|
||||
{nom.name} <Text span size="xs" c="dimmed">({nom.type})</Text>
|
||||
</Table.Td>
|
||||
{data.clients.map(c => {
|
||||
const clientName = c.google_data.name
|
||||
const order = editableOrders[clientName]
|
||||
const item = order?.items?.find(i => i.nomenclature_name === nom.name)
|
||||
const qty = item ? item.quantity : ''
|
||||
|
||||
return (
|
||||
<Table.Td key={clientName} align="center">
|
||||
<NumberInput
|
||||
disabled={data.is_locked}
|
||||
value={qty === null ? '' : qty}
|
||||
onChange={(val) => handleQuantityChange(
|
||||
clientName,
|
||||
nom.name,
|
||||
nom.type,
|
||||
val === '' ? null : Number(val)
|
||||
)}
|
||||
min={0}
|
||||
size="xs"
|
||||
styles={{ input: { textAlign: 'center' } }}
|
||||
/>
|
||||
</Table.Td>
|
||||
)
|
||||
})}
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</Paper>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
interface BlockMetaProps {
|
||||
clientName: string
|
||||
editableOrders: Record<string, MonthlyOrderClient>
|
||||
setEditableOrders: React.Dispatch<React.SetStateAction<Record<string, MonthlyOrderClient>>>
|
||||
isLocked: boolean
|
||||
}
|
||||
|
||||
function BlockMeta({ clientName, editableOrders, setEditableOrders, isLocked }: BlockMetaProps) {
|
||||
const order = editableOrders[clientName] || {}
|
||||
|
||||
return (
|
||||
<Stack gap={4} mt={8}>
|
||||
<Select
|
||||
disabled={isLocked}
|
||||
size="xs"
|
||||
data={['1 декада', '2 декада', '3 декада']}
|
||||
value={order.decade || '1 декада'}
|
||||
onChange={(v) => setEditableOrders((prev) => ({
|
||||
...prev,
|
||||
[clientName]: { ...prev[clientName], decade: v }
|
||||
}))}
|
||||
placeholder="Декада"
|
||||
/>
|
||||
<Textarea
|
||||
disabled={isLocked}
|
||||
size="xs"
|
||||
placeholder="Комментарий (обязательно)"
|
||||
value={order.manager_comment || ''}
|
||||
onChange={(e) => setEditableOrders((prev) => ({
|
||||
...prev,
|
||||
[clientName]: { ...prev[clientName], manager_comment: e.currentTarget.value }
|
||||
}))}
|
||||
autosize
|
||||
minRows={1}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
interface ClientCardViewProps {
|
||||
clientName: string
|
||||
nomenclatures: NomenclatureItem[]
|
||||
editableOrders: Record<string, MonthlyOrderClient>
|
||||
setEditableOrders: React.Dispatch<React.SetStateAction<Record<string, MonthlyOrderClient>>>
|
||||
handleQuantityChange: (clientName: string, nomName: string, nomType: string, qty: number | null) => void
|
||||
isLocked: boolean
|
||||
}
|
||||
|
||||
function ClientCardView({ clientName, nomenclatures, editableOrders, setEditableOrders, handleQuantityChange, isLocked }: ClientCardViewProps) {
|
||||
const order = editableOrders[clientName] || {}
|
||||
|
||||
return (
|
||||
<Card withBorder padding="md" radius="md">
|
||||
<Text fw={700} size="lg" mb="sm">{clientName}</Text>
|
||||
|
||||
<Stack gap="sm" mb="md">
|
||||
<Select
|
||||
disabled={isLocked}
|
||||
label="Декада отправки"
|
||||
size="sm"
|
||||
data={['1 декада', '2 декада', '3 декада']}
|
||||
value={order.decade || '1 декада'}
|
||||
onChange={(v) => setEditableOrders((prev) => ({
|
||||
...prev,
|
||||
[clientName]: { ...prev[clientName], decade: v }
|
||||
}))}
|
||||
/>
|
||||
<Textarea
|
||||
disabled={isLocked}
|
||||
label="Комментарий менеджера"
|
||||
placeholder="Укажите комментарий или причину отсутствия заказа..."
|
||||
value={order.manager_comment || ''}
|
||||
onChange={(e) => setEditableOrders((prev) => ({
|
||||
...prev,
|
||||
[clientName]: { ...prev[clientName], manager_comment: e.currentTarget.value }
|
||||
}))}
|
||||
required
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Divider mb="md" label="Номенклатура товаров" labelPosition="center" />
|
||||
|
||||
<Stack gap="xs">
|
||||
{nomenclatures.map((nom) => {
|
||||
const item = order?.items?.find((i) => i.nomenclature_name === nom.name)
|
||||
const qty = item ? item.quantity : ''
|
||||
|
||||
return (
|
||||
<Group key={nom.name} justify="space-between" align="center">
|
||||
<Box style={{ flex: 1 }}>
|
||||
<Text size="sm" fw={500}>{nom.name}</Text>
|
||||
<Text size="xs" c="dimmed">{nom.type}</Text>
|
||||
</Box>
|
||||
<NumberInput
|
||||
disabled={isLocked}
|
||||
value={qty === null ? '' : qty}
|
||||
onChange={(val) => handleQuantityChange(
|
||||
clientName,
|
||||
nom.name,
|
||||
nom.type,
|
||||
val === '' ? null : Number(val)
|
||||
)}
|
||||
min={0}
|
||||
size="sm"
|
||||
style={{ width: 100 }}
|
||||
styles={{ input: { textAlign: 'center' } }}
|
||||
/>
|
||||
</Group>
|
||||
)
|
||||
})}
|
||||
</Stack>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
export interface NomenclatureItem {
|
||||
name: string
|
||||
type: string
|
||||
}
|
||||
|
||||
export interface ClientItem {
|
||||
name: string
|
||||
manager: string
|
||||
status: string
|
||||
}
|
||||
|
||||
export interface MonthlyOrderSetting {
|
||||
id?: number
|
||||
month?: number
|
||||
year?: number
|
||||
deadline_date: string | null
|
||||
assembly_time_days: number
|
||||
}
|
||||
|
||||
export interface OrderItem {
|
||||
nomenclature_name: string
|
||||
nomenclature_type: string
|
||||
quantity: number | null
|
||||
}
|
||||
|
||||
export interface MonthlyOrderClient {
|
||||
id?: number
|
||||
manager_id?: number
|
||||
month?: number
|
||||
year?: number
|
||||
client_name?: string
|
||||
manager_comment?: string | null
|
||||
custom_reason?: string | null
|
||||
free_form_comment?: string | null
|
||||
decade?: string | null
|
||||
delivery?: string | null
|
||||
conditions?: string | null
|
||||
payment_form?: string | null
|
||||
status?: string // 'draft' | 'submitted'
|
||||
items?: OrderItem[]
|
||||
}
|
||||
|
||||
export interface FrontendClientData {
|
||||
google_data: ClientItem
|
||||
db_order: MonthlyOrderClient | null
|
||||
}
|
||||
|
||||
export interface FrontendOrderMatrix {
|
||||
settings: MonthlyOrderSetting | null
|
||||
nomenclatures: NomenclatureItem[]
|
||||
clients: FrontendClientData[]
|
||||
is_locked: boolean
|
||||
}
|
||||
Loading…
Reference in New Issue