инициализация элементов

This commit is contained in:
2025-07-28 09:00:50 +03:00
parent 0a77199642
commit 4c6deb4563
15 changed files with 249 additions and 271 deletions

View File

@@ -1,53 +0,0 @@
import { Input } from '@/component/ui/input'
import { ElementDefinition } from '@/entitiy/element/model/interface'
import { Hash } from 'lucide-react'
interface NumberConfig {
placeholder?: string
required?: boolean
targetCells: any[]
}
export const numberDefinition: ElementDefinition<NumberConfig, number> = {
type: 'number',
label: 'Число',
icon: <Hash className="h-4 w-4" />,
version: 1,
defaultConfig: {
placeholder: '',
required: false,
targetCells: [],
},
mapToCells: config => config.targetCells || [],
mapToCellValues: (config, value) => {
const cells = config.targetCells || []
return cells.map(target => ({ target, value: value || 0 }))
},
Editor: () => (
<div className="text-sm text-gray-600">
Дополнительные настройки отсутствуют
</div>
),
Preview: ({ config }) => (
<div className="space-y-3">
<div className="text-sm font-medium text-gray-700">Предпросмотр</div>
<div className="rounded-lg border border-gray-200 bg-white p-4">
<Input
type="number"
placeholder={config.placeholder || '0'}
disabled
className="w-full"
/>
</div>
</div>
),
Render: ({ config, value, onChange }) => (
<Input
type="number"
placeholder={config.placeholder || '0'}
value={value || ''}
onChange={e => onChange?.(parseFloat(e.target.value) || 0)}
required={config.required}
/>
),
}

View File

@@ -1,5 +0,0 @@
export { textDefinition } from '@/entitiy/element/model/implementations/TextElement'
export { buttonGroupDefinition } from '../../entitiy/element/model/implementations/ButtonGroup'
export { dateDefinition } from '../../entitiy/element/model/implementations/DateElement'
export { numberDefinition } from './NumberElement'
export { selectDefinition } from './SelectElement'

View File

@@ -1,39 +0,0 @@
import { Input } from '@/component/ui/input'
import { ElementDefinition } from '@/entitiy/element/model/interface'
import { ExtraSettingsBadge } from '@/entitiy/element/ui/extraSettingsBadge'
import { Calendar } from 'lucide-react'
interface DateConfig {
required?: boolean
targetCells: any[]
}
export const dateDefinition: ElementDefinition<DateConfig, string> = {
type: 'date',
label: 'Дата',
icon: <Calendar className="h-4 w-4" />,
version: 1,
defaultConfig: {
required: false,
targetCells: [],
},
mapToCells: config => config.targetCells || [],
mapToCellValues: (config, value) => {
const cells = config.targetCells || []
return cells.map(target => ({ target, value: value || '' }))
},
Editor: () => <ExtraSettingsBadge />,
Preview: () => (
<div className="space-y-3">
<Input type="date" className="w-full" />
</div>
),
Render: ({ config, value, onChange }) => (
<Input
type="date"
value={value || ''}
onChange={e => onChange?.(e.target.value)}
required={config.required}
/>
),
}

View File

@@ -31,6 +31,26 @@ export const selectDefinition: ElementDefinition<SelectConfig, string> = {
options: [],
targetCells: [],
},
getInitialValue: config => {
// Проверяем доступность localStorage (может не быть в SSR)
if (typeof window === 'undefined' || !window.localStorage) {
return ''
}
const elementId = (config as any).id || config.placeholder || 'default'
const storageKey = `select_${elementId}`
const value = localStorage.getItem(storageKey) || ''
// Добавляем отладочную информацию
console.log('SelectElement getInitialValue:', {
elementId,
storageKey,
value,
config,
})
return value
},
mapToCells: config => config.targetCells || [],
mapToCellValues: (config, value) => {
const cells = config.targetCells || []

View File

@@ -8,7 +8,7 @@ import {
SelectValue,
} from '@/component/ui/select'
import { CellTarget } from '@/type/template'
import { Building2 } from 'lucide-react'
import { Building2, Calendar } from 'lucide-react'
import { useLaboratories, useLaboratoryConditions } from './hooks'
import { ConditionMapping, VerificationConditionsConfig } from './types'
@@ -33,7 +33,7 @@ export function VerificationConditionsEditor({
return config.targetCells || []
}
// Обновить маппинг для конкретного условия
// Обновить маппинг для конкретного условия (включая дату поверки)
const updateConditionMapping = (
conditionId: string,
conditionName: string,
@@ -94,6 +94,24 @@ export function VerificationConditionsEditor({
const targetCells = getAvailableTargetCells()
// Создаем список всех условий включая дату поверки
const allConditions = [
// Дата поверки как первый элемент
{
id: 'verification_date',
name: 'Дата поверки',
unit: '',
isDate: true,
},
// Условия из лаборатории
...(labData?.conditionTypes || []).map(ct => ({
id: ct.id,
name: ct.name,
unit: ct.unit,
isDate: false,
})),
]
return (
<div className="space-y-4">
{/* Компактный выбор лаборатории */}
@@ -128,30 +146,38 @@ export function VerificationConditionsEditor({
</div>
</div>
{/* Маппинг условий */}
{labData && targetCells.length > 0 && (
{/* Маппинг условий (включая дату поверки) */}
{targetCells.length > 0 && (
<div className="space-y-3">
<Label className="text-sm font-medium text-gray-700">
Маппинг условий поверки
Маппинг условий и даты поверки
</Label>
<div className="space-y-2">
{labData.conditionTypes.map(conditionType => {
const selectedCell = getSelectedTargetCell(conditionType.id)
const occupiedCells = getOccupiedTargetCells(conditionType.id)
{allConditions.map(condition => {
const selectedCell = getSelectedTargetCell(condition.id)
const occupiedCells = getOccupiedTargetCells(condition.id)
return (
<div
key={conditionType.id}
key={condition.id}
className="flex items-center justify-between gap-3 rounded-md border border-gray-200 bg-gray-50/50 px-3 py-2"
>
{/* Информация об условии */}
<div className="flex items-center gap-2">
{condition.isDate && (
<Calendar className="h-4 w-4 text-green-600" />
)}
<span className="text-sm font-medium text-gray-900">
{conditionType.name}
{condition.name}
</span>
<Badge variant="secondary" className="px-2 py-0.5 text-xs">
{conditionType.unit}
{condition.unit && (
<Badge
variant="secondary"
className="px-2 py-0.5 text-xs"
>
{condition.unit}
</Badge>
)}
</div>
{/* Компактный селектор ячейки */}
@@ -159,8 +185,8 @@ export function VerificationConditionsEditor({
value={selectedCell || 'UNSELECTED'}
onValueChange={value =>
updateConditionMapping(
conditionType.id,
conditionType.name,
condition.id,
condition.name,
value === 'UNSELECTED' ? undefined : value
)
}
@@ -186,7 +212,7 @@ export function VerificationConditionsEditor({
)
})}
{labData.conditionTypes.length === 0 && (
{allConditions.length === 1 && (
<div className="rounded-md border border-dashed border-gray-300 py-4 text-center">
<p className="text-xs text-gray-500">
У выбранной лаборатории нет настроенных типов условий

View File

@@ -42,7 +42,7 @@ export function VerificationConditionsRender({
onSave,
}: VerificationConditionsRenderProps) {
const [selectedDate, setSelectedDate] = useState(
config.selectedDate || new Date().toISOString().split('T')[0]
value?.date || config.selectedDate || new Date().toISOString().split('T')[0]
)
const [editDialogOpen, setEditDialogOpen] = useState(false)
const [editingConditions, setEditingConditions] = useState<
@@ -79,8 +79,34 @@ export function VerificationConditionsRender({
}
}, [dailyCondition, hasConditions, onChange, selectedDate, value?.conditions])
// Синхронизация selectedDate с внешним value.date
useEffect(() => {
if (value?.date && value.date !== selectedDate) {
setSelectedDate(value.date)
}
}, [value?.date, selectedDate])
// Инициализация значения если оно не установлено
useEffect(() => {
if (!value && onChange) {
onChange({
date: selectedDate,
conditions: {},
})
}
}, [value, onChange, selectedDate])
const handleDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSelectedDate(event.target.value)
const newDate = event.target.value
setSelectedDate(newDate)
// Обновляем значение даты в value
if (onChange) {
onChange({
date: newDate,
conditions: value?.conditions || {},
})
}
}
const handleOpenEditDialog = (isCreating = false) => {

View File

@@ -9,6 +9,40 @@ import { VerificationConditionsEditor } from './VerificationConditionsEditor'
import { VerificationConditionsPreview } from './VerificationConditionsPreview'
import { VerificationConditionsRender } from './VerificationConditionsRender'
// Форматирование даты как в функции ДАТАПРОТОКОЛА
const formatVerificationDate = (dateStr: string): string => {
try {
const months = [
'',
'января',
'февраля',
'марта',
'апреля',
'мая',
'июня',
'июля',
'августа',
'сентября',
'октября',
'ноября',
'декабря',
]
const dateObj = new Date(dateStr)
if (isNaN(dateObj.getTime())) {
return 'Неверный формат даты'
}
const day = dateObj.getDate().toString().padStart(2, '0')
const month = months[dateObj.getMonth() + 1]
const year = dateObj.getFullYear()
return `${day} ${month} ${year}`
} catch (e) {
return 'Неверный формат даты'
}
}
export const verificationConditionsElementDefinition: ElementDefinition<
VerificationConditionsConfig & { targetCells?: CellTarget[] },
VerificationConditionsValue
@@ -56,28 +90,40 @@ export const verificationConditionsElementDefinition: ElementDefinition<
config,
value: VerificationConditionsValue
): Array<{ target: CellTarget; value: any }> => {
if (!config.conditionMappings || !config.targetCells || !value.conditions) {
if (!config.conditionMappings || !config.targetCells) {
return []
}
return config.conditionMappings
.filter(mapping => {
const conditionValue = value.conditions[mapping.conditionKey]
// Записываем только непустые значения
return (
conditionValue !== undefined &&
conditionValue !== null &&
String(conditionValue).trim() !== ''
)
})
.map(mapping => {
const targetCell = config.targetCells?.[mapping.cellIndex]
if (!targetCell) return null
// Обработка даты поверки
if (mapping.conditionKey === 'verification_date') {
if (value.date) {
return {
target: targetCell,
value: value.conditions[mapping.conditionKey],
value: formatVerificationDate(value.date),
}
}
return null
}
// Обработка остальных условий
const conditionValue = value.conditions?.[mapping.conditionKey]
if (
conditionValue !== undefined &&
conditionValue !== null &&
String(conditionValue).trim() !== ''
) {
return {
target: targetCell,
value: conditionValue,
}
}
return null
})
.filter(Boolean) as Array<{ target: CellTarget; value: any }>
},

View File

@@ -13,7 +13,7 @@ export interface VerificationConditionsConfig {
selectedLaboratoryId?: string
// Выбранная дата
selectedDate?: string
// Маппинг условий в ячейки
// Маппинг условий в ячейки (включая дату поверки)
conditionMappings?: ConditionMapping[]
// Показывать ли единицы измерения
showUnits?: boolean

View File

@@ -1,10 +1,8 @@
import { textDefinition } from '@/component/BasicElements'
import { numberDefinition } from '@/component/BasicElements/NumberElement'
import { selectDefinition } from '@/component/BasicElements/SelectElement'
import { verificationConditionsElementDefinition as verificationConditionsDefinition } from '@/component/VerificationConditionsElement/definition'
import { buttonGroupDefinition } from '@/entitiy/element/model/implementations/ButtonGroup'
import { dateDefinition } from '@/entitiy/element/model/implementations/DateElement'
import { selectDefinition } from '@/entitiy/element/model/implementations/SelectElement'
import { standardsDefinition } from '@/entitiy/element/model/implementations/StandardsElement/definition'
import { textDefinition } from '@/entitiy/element/model/implementations/TextElement'
import { verificationConditionsElementDefinition as verificationConditionsDefinition } from '@/entitiy/element/model/implementations/VerificationConditionsElement/definition'
import { CellTarget } from '@/type/template'
import { ReactNode } from 'react'
@@ -64,8 +62,6 @@ export function getElementDefinition(
export const elementDefinitions = {
text: textDefinition,
select: selectDefinition,
number: numberDefinition,
date: dateDefinition,
standards: standardsDefinition,
verification_conditions: verificationConditionsDefinition,
button_group: buttonGroupDefinition,
@@ -76,8 +72,6 @@ export type ElementType = keyof typeof elementDefinitions
export function initializeElementRegistry() {
registerElement('text', textDefinition)
registerElement('select', selectDefinition)
registerElement('number', numberDefinition)
registerElement('date', dateDefinition)
registerElement('button_group', buttonGroupDefinition)
registerElement('standards', standardsDefinition)
registerElement('verification_conditions', verificationConditionsDefinition)

View File

@@ -16,61 +16,6 @@ interface ProtocolFormProps {
onBack: () => void
}
interface FormElementProps {
element: TemplateElement
value: any
onChange: (value: any) => void
}
const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
// Получаем определение элемента из реестра
const elementDefinition = getElementDefinition(element.type)
// Если определение элемента не найдено, показываем ошибку
if (!elementDefinition) {
return (
<div className="rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700">
Элемент типа "{element.type}" не найден в реестре
</div>
)
}
const renderElement = () => (
<elementDefinition.Render
config={element as any}
value={value}
onChange={onChange}
/>
)
return (
<div className="relative space-y-3">
{/* Показываем индикатор ячеек для всех элементов */}
{element.targetCells && element.targetCells.length > 0 && (
<div className="group/cells absolute right-0 top-0">
<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>
)}
{/* Рендер элемента через единый интерфейс */}
{renderElement()}
</div>
)
}
const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
const [formData, setFormData] = useState<Record<string, any>>({})
const [showSpreadsheet, setShowSpreadsheet] = useState(false)
@@ -79,23 +24,22 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
const toast = useToast()
const navigate = useNavigate()
// Инициализация значений для специальных элементов
// Инициализация начальных значений формы (только один раз)
useEffect(() => {
if (!isInitialized && template.elements.length > 0) {
const initialData: Record<string, any> = {}
template.elements.forEach(element => {
// Получаем определение элемента
const elementDefinition = getElementDefinition(element.type)
if (elementDefinition?.getInitialValue) {
// Используем метод getInitialValue для получения начального значения
const initialValue = elementDefinition.getInitialValue(element as any)
if (initialValue !== undefined) {
if (initialValue !== undefined && initialValue !== '') {
initialData[element.id] = initialValue
}
}
})
console.log('Инициализация формы:', initialData)
if (Object.keys(initialData).length > 0) {
setFormData(initialData)
}
@@ -104,26 +48,21 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
}
}, [template.elements, isInitialized])
const handleFieldChange = (elementId: string, value: any) => {
setFormData(prev => ({
...prev,
[elementId]: value,
}))
// Универальная функция синхронизации всех данных формы с движком
const syncFormDataToEngine = () => {
if (!engineRef.current) return
// Прямо обновляем движок, чтобы формулы пересчитались
if (engineRef.current) {
const element = template.elements.find(el => el.id === elementId)
if (element) {
// Получаем определение элемента
console.log('Синхронизация всех данных формы с движком:', formData)
template.elements.forEach(element => {
const value = formData[element.id]
if (value !== undefined) {
const elementDefinition = getElementDefinition(element.type)
if (elementDefinition) {
// Используем единый интерфейс для получения пар ячейка-значение
const cellValues = elementDefinition.mapToCellValues(
element as any,
value
)
// Записываем все значения в соответствующие ячейки
cellValues.forEach(({ target, value: cellValue }) => {
const { row, col } = cellAddressToCoordinates(target.cell)
engineRef.current.setCellValueWithoutRecalc(
@@ -133,24 +72,34 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
cellValue
)
})
}
}
})
engineRef.current.debouncedRecalc()
}
// Синхронизация с движком только когда он готов и есть данные
useEffect(() => {
if (
isInitialized &&
engineRef.current &&
Object.keys(formData).length > 0
) {
syncFormDataToEngine()
}
}
}, [isInitialized, formData, template.elements])
const handleFieldChange = (elementId: string, value: any) => {
// Обновляем только состояние формы
setFormData(prev => ({
...prev,
[elementId]: value,
}))
}
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(),
@@ -163,43 +112,14 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
return
}
// 1. Записываем ВСЕ значения формы в движок (поверх текущих)
template.elements.forEach(el => {
let value = formData[el.id]
if (value === undefined || value === null) value = ''
// Убеждаемся что все данные записаны в движок перед сохранением
syncFormDataToEngine()
// Получаем определение элемента
const elementDefinition = getElementDefinition(el.type)
if (elementDefinition) {
// Используем единый интерфейс для получения пар ячейка-значение
const cellValues = elementDefinition.mapToCellValues(el as any, value)
// Небольшая задержка чтобы пересчёт завершился
await new Promise(resolve => setTimeout(resolve, 100))
// Записываем все значения в соответствующие ячейки
cellValues.forEach(({ target, value: cellValue }) => {
const { row, col } = cellAddressToCoordinates(target.cell)
if (target.sheet === 'Calculations') {
toast.warning('Обнаружен лист Calculations')
}
const sheetName =
target.sheet === 'R' || target.sheet === 'Calculations'
? 'R'
: 'L'
engineRef.current.setCellValueWithoutRecalc(
sheetName,
row,
col,
cellValue
)
})
}
})
// 2. Пересчитываем формулы
engineRef.current.recalculate()
// 3. Получаем изменения только левого листа относительно базового файла
// Получаем изменения только левого листа относительно базового файла
const allModified = engineRef.current?.getAllModifiedCells() || {}
// Преобразуем в конечные (вычисленные) значения
const cellsToUpdate: Record<string, any> = {}
const modifiedLeft = allModified['L'] || {}
Object.keys(modifiedLeft).forEach(cellAddress => {
@@ -223,6 +143,7 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
file_id: latestFile.id,
template_id: template.id,
}
console.log('body', body)
const resp = await fetch('/api/protocols/', {
method: 'POST',
@@ -240,7 +161,6 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
// Получаем значение из ячейки R!A1 для имени файла
const filenameFromCell = engineRef.current.getCellValue('R', 0, 0) // R!A1
console.log(filenameFromCell)
let filename = 'Измените R!A1.xlsx'
if (
@@ -248,16 +168,12 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
typeof filenameFromCell === 'string' &&
filenameFromCell.trim()
) {
// Очищаем имя файла от недопустимых символов
const cleanName = filenameFromCell.trim().replace(/[<>:"/\\|?*]/g, '_')
filename = `${cleanName}.xlsx`
}
// Если сервер передал имя файла в заголовке Content-Disposition, игнорируем его
// и используем строго значение из R!A1
const contentDisposition = resp.headers.get('content-disposition')
if (contentDisposition) {
// Оставляем возможность переопределения только если R!A1 пуста
if (!filenameFromCell || !filenameFromCell.toString().trim()) {
const matches = contentDisposition.match(
/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
@@ -373,6 +289,7 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
templateId={template.id}
onEngineReady={engine => {
engineRef.current = engine
// Синхронизация произойдёт автоматически через useEffect
}}
enableAutoSave={false}
/>
@@ -458,14 +375,6 @@ export const ProtocolCreation: FC = () => {
}
}, [templateId, templates])
const handleProtocolSave = (data: Record<string, any>) => {
toast.success(`Протокол "${data.protocolName}" сохранен!`)
}
const handleBack = () => {
navigate('/templates')
}
if (!selectedTemplate) {
return (
<div className="flex h-screen items-center justify-center">
@@ -488,8 +397,62 @@ export const ProtocolCreation: FC = () => {
return (
<ProtocolForm
template={selectedTemplate}
onSave={handleProtocolSave}
onBack={handleBack}
onSave={() => {
toast.info(`Подождите, Excel файл создаётся...`)
}}
onBack={() => {
navigate('/templates')
}}
/>
)
}
interface FormElementProps {
element: TemplateElement
value: any
onChange: (value: any) => void
}
const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
const elementDefinition = getElementDefinition(element.type)
if (!elementDefinition) {
return (
<div className="rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700">
Элемент типа "{element.type}" не найден в реестре
</div>
)
}
const renderElement = () => (
<elementDefinition.Render
config={element as any}
value={value}
onChange={onChange}
/>
)
return (
<div className="relative space-y-3">
{/* Показываем индикатор ячеек для всех элементов */}
{element.targetCells && element.targetCells.length > 0 && (
<div className="group/cells absolute right-0 top-0">
<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>
)}
{renderElement()}
</div>
)
}