переименования папок
This commit is contained in:
739
src/page/ProtocolCreation/Page.tsx
Normal file
739
src/page/ProtocolCreation/Page.tsx
Normal file
@@ -0,0 +1,739 @@
|
||||
import DualSpreadsheet from '@/components/DualSpreadsheet/DualSpreadsheet'
|
||||
import { StandardsSelector } from '@/components/StandardsElement/StandardsSelector'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { useTemplateContext } from '@/context/TemplateContext'
|
||||
import { getElementDefinition } from '@/lib/element-registry'
|
||||
import { getLatestFileForTemplate } from '@/service/fileApiSevice'
|
||||
import { Template, TemplateElement } from '@/type/template'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Download,
|
||||
FileText,
|
||||
Grid,
|
||||
Save,
|
||||
Settings,
|
||||
Wrench,
|
||||
} from 'lucide-react'
|
||||
import { FC, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
|
||||
// Моковые данные для эталонов (такие же как в StandardsSelector)
|
||||
const mockStandards = [
|
||||
{
|
||||
id: '1',
|
||||
name: 'Эталон массы 1 кг',
|
||||
shortName: 'ЭМ-1кг',
|
||||
type: 'Масса',
|
||||
registryNumber: 'ГРСИ 12345-01',
|
||||
range: '0.5-2 кг',
|
||||
accuracy: '±0.001 г',
|
||||
certificateNumber: 'СИ-2024-001',
|
||||
validUntil: '2025-12-31',
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
name: 'Эталон длины 1 м',
|
||||
shortName: 'ЭД-1м',
|
||||
type: 'Длина',
|
||||
registryNumber: 'ГРСИ 12345-02',
|
||||
range: '0.5-2 м',
|
||||
accuracy: '±0.001 мм',
|
||||
certificateNumber: 'СИ-2024-002',
|
||||
validUntil: '2025-06-30',
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
name: 'Эталон температуры 20°C',
|
||||
shortName: 'ЭТ-20°C',
|
||||
type: 'Температура',
|
||||
registryNumber: 'ГРСИ 12345-03',
|
||||
range: '15-25°C',
|
||||
accuracy: '±0.01°C',
|
||||
certificateNumber: 'СИ-2024-003',
|
||||
validUntil: '2025-03-15',
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
name: 'Эталон давления 1 Па',
|
||||
shortName: 'ЭД-1Па',
|
||||
type: 'Давление',
|
||||
registryNumber: 'ГРСИ 12345-04',
|
||||
range: '0.5-2 Па',
|
||||
accuracy: '±0.001 Па',
|
||||
certificateNumber: 'СИ-2024-004',
|
||||
validUntil: '2025-09-20',
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
name: 'Эталон времени 1 с',
|
||||
shortName: 'ЭВ-1с',
|
||||
type: 'Время',
|
||||
registryNumber: 'ГРСИ 12345-05',
|
||||
range: '0.5-2 с',
|
||||
accuracy: '±0.000001 с',
|
||||
certificateNumber: 'СИ-2024-005',
|
||||
validUntil: '2025-12-01',
|
||||
},
|
||||
]
|
||||
|
||||
// Функция для получения данных эталона по ID
|
||||
const getStandardById = (id: string) => {
|
||||
return mockStandards.find(standard => standard.id === id)
|
||||
}
|
||||
|
||||
// Функция для получения типа эталона в сокращенном виде
|
||||
const getStandardTypeBadge = (type: string) => {
|
||||
switch (type) {
|
||||
case 'Манометр грузопоршневой':
|
||||
return 'МГП'
|
||||
case 'Калибратор давления':
|
||||
return 'КД'
|
||||
default:
|
||||
return 'МО'
|
||||
}
|
||||
}
|
||||
|
||||
interface ProtocolFormProps {
|
||||
template: Template
|
||||
onSave: (data: Record<string, any>) => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
interface FormElementProps {
|
||||
element: TemplateElement
|
||||
value: any
|
||||
onChange: (value: any) => void
|
||||
}
|
||||
|
||||
const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
|
||||
const [isStandardsDialogOpen, setIsStandardsDialogOpen] = useState(false)
|
||||
|
||||
const renderInput = () => {
|
||||
switch (element.type) {
|
||||
case 'text':
|
||||
return (
|
||||
<Input
|
||||
placeholder={element.placeholder}
|
||||
value={value || ''}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
required={element.required}
|
||||
/>
|
||||
)
|
||||
|
||||
case 'textarea':
|
||||
return (
|
||||
<Textarea
|
||||
placeholder={element.placeholder}
|
||||
value={value || ''}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
required={element.required}
|
||||
rows={3}
|
||||
/>
|
||||
)
|
||||
|
||||
case 'number':
|
||||
return (
|
||||
<Input
|
||||
type="number"
|
||||
placeholder={element.placeholder}
|
||||
value={value || ''}
|
||||
onChange={e =>
|
||||
onChange(e.target.value ? parseFloat(e.target.value) : '')
|
||||
}
|
||||
required={element.required}
|
||||
/>
|
||||
)
|
||||
|
||||
case 'date':
|
||||
return (
|
||||
<Input
|
||||
type="date"
|
||||
value={value || ''}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
required={element.required}
|
||||
/>
|
||||
)
|
||||
|
||||
case 'select':
|
||||
return (
|
||||
<Select value={value || ''} onValueChange={onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue
|
||||
placeholder={element.placeholder || 'Выберите значение'}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{element.options?.map(option => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
|
||||
case 'radio':
|
||||
return (
|
||||
<RadioGroup value={value || ''} onValueChange={onChange}>
|
||||
{element.options?.map(option => (
|
||||
<div key={option.value} className="flex items-center space-x-2">
|
||||
<RadioGroupItem
|
||||
value={option.value}
|
||||
id={`${element.id}-${option.value}`}
|
||||
/>
|
||||
<label
|
||||
htmlFor={`${element.id}-${option.value}`}
|
||||
className="text-sm font-medium"
|
||||
>
|
||||
{option.label}
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
</RadioGroup>
|
||||
)
|
||||
|
||||
case 'checkbox':
|
||||
return (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
checked={!!value}
|
||||
onCheckedChange={onChange}
|
||||
id={element.id}
|
||||
/>
|
||||
<label htmlFor={element.id} className="text-sm font-medium">
|
||||
{element.placeholder || 'Отметить'}
|
||||
</label>
|
||||
</div>
|
||||
)
|
||||
|
||||
case 'standards':
|
||||
const selectedStandards = Array.isArray(value) ? value : []
|
||||
const selectedStandardsData = selectedStandards
|
||||
.map(id => getStandardById(id))
|
||||
.filter(Boolean)
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{/* Блок с измерительными эталонами */}
|
||||
<div>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<Label className="text-sm font-medium">Эталоны</Label>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setIsStandardsDialogOpen(true)}
|
||||
className="h-7 px-2"
|
||||
>
|
||||
<Settings className="mr-1 h-3 w-3" />
|
||||
Настроить
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{selectedStandardsData.length > 0 ? (
|
||||
<div className="space-y-1.5">
|
||||
{selectedStandardsData.map(
|
||||
(standard, index) =>
|
||||
standard && (
|
||||
<div
|
||||
key={standard.id}
|
||||
className="flex items-center gap-2 rounded-md bg-muted/30 p-2 text-sm"
|
||||
>
|
||||
<div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary/10">
|
||||
<span className="text-xs font-medium text-primary">
|
||||
{index + 1}
|
||||
</span>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-xs font-medium text-foreground">
|
||||
{standard.shortName}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{standard.accuracy} • {standard.range}
|
||||
</div>
|
||||
</div>
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="shrink-0 text-xs"
|
||||
>
|
||||
<Wrench className="mr-1 h-3 w-3" />
|
||||
{getStandardTypeBadge(standard.type)}
|
||||
</Badge>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-md border border-dashed bg-muted/30 p-3 text-center text-sm text-muted-foreground">
|
||||
<Settings className="mx-auto mb-1 h-4 w-4 opacity-50" />
|
||||
Эталоны не выбраны
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<StandardsSelector
|
||||
isOpen={isStandardsDialogOpen}
|
||||
onClose={() => setIsStandardsDialogOpen(false)}
|
||||
value={selectedStandards}
|
||||
onChange={onChange}
|
||||
registryNumber={
|
||||
element.targetCells?.[0]?.displayName || 'ГРСИ 12345'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
case 'calibration-conditions':
|
||||
// Используем определение элемента из реестра для рендеринга
|
||||
const elementDefinition = getElementDefinition('calibration-conditions')
|
||||
if (elementDefinition && elementDefinition.Render) {
|
||||
return (
|
||||
<elementDefinition.Render
|
||||
config={element as any}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return null
|
||||
|
||||
case 'button-group':
|
||||
// Используем определение элемента из реестра для рендеринга
|
||||
const buttonGroupDefinition = getElementDefinition('button-group')
|
||||
if (buttonGroupDefinition && buttonGroupDefinition.Render) {
|
||||
return (
|
||||
<buttonGroupDefinition.Render
|
||||
config={element as any}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return null
|
||||
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex items-center gap-1">
|
||||
<label className="text-sm font-medium text-gray-900">
|
||||
{element.label}
|
||||
</label>
|
||||
{element.required && (
|
||||
<span className="-mt-1.5 inline-block h-1 w-1 rounded-full bg-red-500" />
|
||||
)}
|
||||
</div>
|
||||
{/* Индикатор ячеек */}
|
||||
{element.targetCells && element.targetCells.length > 0 && (
|
||||
<div className="group/cells relative">
|
||||
<Grid className="h-3 w-3 cursor-help text-gray-500 opacity-60 transition-opacity hover:opacity-100" />
|
||||
<div className="pointer-events-none absolute right-0 top-full z-50 mt-2 whitespace-nowrap rounded bg-gray-900 p-2 text-xs text-white opacity-0 shadow-lg transition-opacity group-hover/cells:opacity-100">
|
||||
<div className="mb-1 font-medium">Целевые ячейки:</div>
|
||||
{element.targetCells.map((cell, i) => (
|
||||
<div key={i} className="font-mono">
|
||||
{cell.sheet}!{cell.cell}
|
||||
{cell.displayName && (
|
||||
<span className="ml-1 text-gray-300">
|
||||
({cell.displayName})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{renderInput()}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
|
||||
const [formData, setFormData] = useState<Record<string, any>>({})
|
||||
const [showSpreadsheet, setShowSpreadsheet] = useState(false)
|
||||
const engineRef = useRef<any>(null)
|
||||
|
||||
// 👉 Хелперы для конвертации адреса ячейки
|
||||
const labelToColumn = (label: string) => {
|
||||
let col = 0
|
||||
for (let i = 0; i < label.length; i++) {
|
||||
col = col * 26 + (label.charCodeAt(i) - 64)
|
||||
}
|
||||
return col - 1 // zero-based
|
||||
}
|
||||
|
||||
const parseCellAddress = (addr: string) => {
|
||||
const match = addr.match(/([A-Z]+)(\d+)/i)
|
||||
if (!match) return { row: 0, col: 0 }
|
||||
const [, colLabel, rowNum] = match
|
||||
return {
|
||||
row: parseInt(rowNum, 10) - 1,
|
||||
col: labelToColumn(colLabel),
|
||||
}
|
||||
}
|
||||
|
||||
const handleFieldChange = (elementId: string, value: any) => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[elementId]: value,
|
||||
}))
|
||||
|
||||
// Прямо обновляем движок, чтобы формулы пересчитались
|
||||
if (engineRef.current) {
|
||||
const element = template.elements.find(el => el.id === elementId)
|
||||
if (element && element.targetCells) {
|
||||
element.targetCells.forEach(tc => {
|
||||
const { row, col } = parseCellAddress(tc.cell)
|
||||
const sheetName =
|
||||
tc.sheet === 'R' || tc.sheet === 'Calculations' ? 'R' : 'L'
|
||||
engineRef.current.setCellValueWithoutRecalc(
|
||||
sheetName,
|
||||
row,
|
||||
col,
|
||||
value
|
||||
)
|
||||
})
|
||||
engineRef.current.debouncedRecalc()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
// Ищем элемент с названием протокола (должен иметь специальный тип или название)
|
||||
const protocolNameElement = template.elements.find(
|
||||
el => el.name === 'protocolName' || el.label === 'Название протокола'
|
||||
)
|
||||
const protocolName = protocolNameElement
|
||||
? formData[protocolNameElement.id]
|
||||
: 'Новый протокол'
|
||||
|
||||
const data = {
|
||||
protocolName,
|
||||
templateId: template.id,
|
||||
formData,
|
||||
createdAt: new Date(),
|
||||
}
|
||||
onSave(data)
|
||||
|
||||
console.log(
|
||||
'[DBG] template elements',
|
||||
template.elements.map(e => ({
|
||||
id: e.id,
|
||||
label: e.label,
|
||||
target: e.targetCells,
|
||||
type: e.type,
|
||||
}))
|
||||
)
|
||||
|
||||
try {
|
||||
if (!engineRef.current) {
|
||||
alert('Движок ещё не инициализирован')
|
||||
return
|
||||
}
|
||||
|
||||
// 1. Записываем ВСЕ значения формы в движок (поверх текущих)
|
||||
template.elements.forEach(el => {
|
||||
let value = formData[el.id]
|
||||
if (value === undefined || value === null) value = ''
|
||||
|
||||
let cells =
|
||||
el.targetCells && el.targetCells.length > 0
|
||||
? el.targetCells
|
||||
: undefined
|
||||
if ((!cells || cells.length === 0) && el.type) {
|
||||
const def = getElementDefinition(el.type as any)
|
||||
if (def?.mapToCells) cells = def.mapToCells(el as any)
|
||||
}
|
||||
|
||||
cells?.forEach(tc => {
|
||||
const { row, col } = parseCellAddress(tc.cell)
|
||||
const sheetName =
|
||||
tc.sheet === 'R' || tc.sheet === 'Calculations' ? 'R' : 'L'
|
||||
console.log(
|
||||
'[DBG] write to',
|
||||
tc.cell,
|
||||
'sheet',
|
||||
sheetName,
|
||||
'value',
|
||||
value
|
||||
)
|
||||
engineRef.current.setCellValueWithoutRecalc(
|
||||
sheetName,
|
||||
row,
|
||||
col,
|
||||
value
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
// 2. Пересчитываем формулы
|
||||
engineRef.current.recalculate()
|
||||
|
||||
// 3. Получаем изменения только левого листа относительно базового файла
|
||||
const allModified = engineRef.current?.getAllModifiedCells() || {}
|
||||
// Преобразуем в конечные (вычисленные) значения
|
||||
const cellsToUpdate: Record<string, any> = {}
|
||||
const modifiedLeft = allModified['L'] || {}
|
||||
Object.keys(modifiedLeft).forEach(cellAddress => {
|
||||
const { row, col } = parseCellAddress(cellAddress)
|
||||
cellsToUpdate[cellAddress] = engineRef.current.getCellValue(
|
||||
'L',
|
||||
row,
|
||||
col
|
||||
)
|
||||
})
|
||||
|
||||
console.log('[DBG] Final cells_to_update', cellsToUpdate)
|
||||
|
||||
// Получаем последний файл для шаблона
|
||||
const latestFile = await getLatestFileForTemplate(template.id)
|
||||
if (!latestFile) {
|
||||
alert('Не найден исходный файл Excel для шаблона')
|
||||
return
|
||||
}
|
||||
|
||||
const body = {
|
||||
cells_to_update: cellsToUpdate,
|
||||
file_id: latestFile.id,
|
||||
template_id: template.id,
|
||||
}
|
||||
|
||||
console.log('[DBG] POST body', body)
|
||||
|
||||
const resp = await fetch('/api/protocols/', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
|
||||
|
||||
const result = await resp.json()
|
||||
console.log('✅ Протокол создан, ID:', result.protocol_id)
|
||||
} catch (err) {
|
||||
console.error('Ошибка при создании протокола', err)
|
||||
alert('Ошибка при создании протокола')
|
||||
}
|
||||
}
|
||||
|
||||
const handleExport = () => {
|
||||
console.log('Экспорт в Excel:', { formData })
|
||||
alert('Функция экспорта будет реализована в следующих версиях')
|
||||
}
|
||||
|
||||
const canvasSize = useMemo(() => {
|
||||
const PADDING_Y = 200
|
||||
const baseWidth = 1200
|
||||
const baseHeight = 800
|
||||
|
||||
if (template.elements.length === 0) {
|
||||
return { width: baseWidth, height: baseHeight }
|
||||
}
|
||||
|
||||
const contentHeight = Math.max(
|
||||
0,
|
||||
...template.elements.map(
|
||||
el => (el.layout?.y || 0) + (el.layout?.height || 0)
|
||||
)
|
||||
)
|
||||
|
||||
return {
|
||||
width: baseWidth,
|
||||
height: Math.max(baseHeight, contentHeight + PADDING_Y),
|
||||
}
|
||||
}, [template.elements])
|
||||
|
||||
// Проверяем есть ли кнопка сохранения (есть ли название протокола)
|
||||
const protocolNameElement = template.elements.find(
|
||||
el => el.name === 'protocolName' || el.label === 'Название протокола'
|
||||
)
|
||||
const canSave = protocolNameElement
|
||||
? !!formData[protocolNameElement.id]?.trim()
|
||||
: false
|
||||
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-gray-50">
|
||||
{/* Заголовок */}
|
||||
<div className="shrink-0 border-b border-gray-200 bg-white p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" onClick={onBack}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Назад
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-gray-800">
|
||||
Создание протокола: {template.name}
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant={showSpreadsheet ? 'default' : 'outline'}
|
||||
onClick={() => setShowSpreadsheet(!showSpreadsheet)}
|
||||
>
|
||||
<Grid className="mr-2 h-4 w-4" />
|
||||
{showSpreadsheet ? 'Скрыть таблицы' : 'Показать таблицы'}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={handleExport}>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Экспорт в Excel
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={!canSave}>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
Сохранить протокол
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Основное содержимое */}
|
||||
<div className="flex-1 overflow-hidden">
|
||||
{/* Всегда монтируем DualSpreadsheet, скрываем/показываем через hidden */}
|
||||
<div className={`${showSpreadsheet ? 'block' : 'hidden'} h-full`}>
|
||||
<DualSpreadsheet
|
||||
templateData={
|
||||
template.excelData ? { report: template.excelData } : {}
|
||||
}
|
||||
mergedCells={template.mergedCells || []}
|
||||
templateId={template.id}
|
||||
onEngineReady={engine => (engineRef.current = engine)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Форма */}
|
||||
<div
|
||||
className={`${showSpreadsheet ? 'hidden' : 'block'} h-full overflow-auto`}
|
||||
>
|
||||
<div
|
||||
className="relative mx-auto my-8"
|
||||
style={{ width: canvasSize.width, height: canvasSize.height }}
|
||||
>
|
||||
{template.elements.map(element => {
|
||||
const layout = element.layout || {
|
||||
x: 50,
|
||||
y: 50,
|
||||
width: 300,
|
||||
height: 80,
|
||||
}
|
||||
return (
|
||||
<div
|
||||
key={element.id}
|
||||
className="absolute"
|
||||
style={{
|
||||
left: layout.x,
|
||||
top: layout.y,
|
||||
width: layout.width,
|
||||
minHeight: layout.height,
|
||||
zIndex: layout.zIndex || 1,
|
||||
}}
|
||||
>
|
||||
<FormElement
|
||||
element={element}
|
||||
value={formData[element.id]}
|
||||
onChange={value => handleFieldChange(element.id, value)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{template.elements.length === 0 && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="text-center text-gray-400">
|
||||
<FileText className="mx-auto mb-4 h-16 w-16" />
|
||||
<h3 className="mb-2 text-lg font-medium text-gray-900">
|
||||
Нет элементов формы
|
||||
</h3>
|
||||
<p className="mb-4 text-gray-600">
|
||||
В этом шаблоне пока не созданы элементы формы
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => window.history.back()}
|
||||
>
|
||||
Настроить шаблон
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const ProtocolCreation: FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const { templateId } = useParams<{ templateId?: string }>()
|
||||
const { templates } = useTemplateContext()
|
||||
const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(
|
||||
null
|
||||
)
|
||||
|
||||
// Автоматически выбираем шаблон если передан ID в URL
|
||||
useEffect(() => {
|
||||
if (templateId && templates.length > 0) {
|
||||
const template = templates.find(t => t.id === templateId)
|
||||
if (template) {
|
||||
setSelectedTemplate(template)
|
||||
}
|
||||
}
|
||||
}, [templateId, templates])
|
||||
|
||||
const handleProtocolSave = (data: Record<string, any>) => {
|
||||
console.log('Сохранение протокола:', data)
|
||||
// Здесь будет логика сохранения протокола
|
||||
alert(`Протокол "${data.protocolName}" сохранен!`)
|
||||
navigate('/templates')
|
||||
}
|
||||
|
||||
const handleBack = () => {
|
||||
navigate('/templates')
|
||||
}
|
||||
|
||||
if (!selectedTemplate) {
|
||||
return (
|
||||
<div className="flex h-screen items-center justify-center">
|
||||
<div className="text-center">
|
||||
<FileText className="mx-auto mb-4 h-16 w-16 text-gray-400" />
|
||||
<h3 className="mb-2 text-lg font-medium text-gray-900">
|
||||
Шаблон не найден
|
||||
</h3>
|
||||
<p className="mb-4 text-gray-600">
|
||||
Перейдите к списку шаблонов для выбора
|
||||
</p>
|
||||
<Button onClick={() => navigate('/templates')}>
|
||||
К списку шаблонов
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ProtocolForm
|
||||
template={selectedTemplate}
|
||||
onSave={handleProtocolSave}
|
||||
onBack={handleBack}
|
||||
/>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user