test+ci: 51 frontend unit-тестов (Vitest) + CI rollback на single resolve-tag
Tests (Vitest): - src/lib/dates.ts (вынесено из SchemaDrivenForm + dictionaries.$name): parseFormDate, formatIsoDate, formatIsoDateTime, extractTime, combineDateTime, localTzOffset, nowIsoLocal - src/lib/dates.test.ts (20 tests): TZ-safety, pure-date local midnight, far-future filter, round-trip parse/format, time extraction в local TZ, clear-button (null Date → '') - src/components/schema/types.test.ts (31 tests): buildSchemaJson всех 9 kinds + x-unique + x-id-source, parseSchemaJson roundtrip, diffSchemas (8 breaking detection cases), suggestVersionBump (major/minor/patch + breaking-wins-mix) CI: - Откатил dual resolve-tag (BACKEND/FRONTEND) на single resolve-tag. GitLab variable interpolation в trigger jobs не подхватывает dotenv от needs-job → admin-ui-only push не доезжал до infra. Now backwards compat path работает как раньше с UPSTREAM_IMAGE_TAG. - Backend docker jobs (maven-package + 4 docker-*) теперь без rules:changes — catch ImagePullBackOff если frontend push шёл без backend rebuild. BuildKit cache делает повторный билд идентичных layers ~30 sec. - Path-filter оставлен на maven-test (тесты не запускаются на frontend-only PR — они бэкендовые) и на docker-admin-ui (frontend-only). Run: pnpm test → 51 passed.
This commit is contained in:
@@ -21,6 +21,13 @@ import {
|
||||
type TabItem,
|
||||
} from '@nstart/ui'
|
||||
import type { CreateRecordRequest, JsonSchema } from '@/api/client'
|
||||
import {
|
||||
combineDateTime,
|
||||
extractTime,
|
||||
formatIsoDate,
|
||||
formatIsoDateTime,
|
||||
parseFormDate,
|
||||
} from '@/lib/dates'
|
||||
|
||||
type FormValues = {
|
||||
businessKey: string
|
||||
@@ -49,57 +56,6 @@ const isLocalized = (s: JsonSchema): boolean => Boolean(s['x-localized'])
|
||||
const humanize = (key: string): string =>
|
||||
key.replace(/[_-]+/g, ' ').replace(/\b\w/g, (ch) => ch.toUpperCase())
|
||||
|
||||
const parseFormDate = (s: unknown): Date | null => {
|
||||
if (typeof s !== 'string' || !s) return null
|
||||
// Pure date "YYYY-MM-DD" парсим как локальную полуночь, иначе для TZ западнее
|
||||
// UTC new Date() уедет на день назад. Для строк с временем — стандартный парс.
|
||||
const pureDate = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s)
|
||||
const d = pureDate
|
||||
? new Date(Number(pureDate[1]), Number(pureDate[2]) - 1, Number(pureDate[3]))
|
||||
: new Date(s)
|
||||
if (Number.isNaN(d.getTime())) return null
|
||||
if (d.getFullYear() >= 9999) return null
|
||||
return d
|
||||
}
|
||||
|
||||
const formatIsoDate = (d: Date): string => {
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
||||
}
|
||||
|
||||
const localTzOffset = (d: Date): string => {
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
const total = -d.getTimezoneOffset()
|
||||
const sign = total >= 0 ? '+' : '-'
|
||||
const abs = Math.abs(total)
|
||||
return `${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`
|
||||
}
|
||||
|
||||
const formatIsoDateTime = (d: Date, time: string = '00:00'): string => {
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
const [hh, mm] = time.split(':').map(Number)
|
||||
const local = new Date(d.getFullYear(), d.getMonth(), d.getDate(), hh || 0, mm || 0, 0)
|
||||
return `${formatIsoDate(local)}T${pad(local.getHours())}:${pad(local.getMinutes())}:00${localTzOffset(local)}`
|
||||
}
|
||||
|
||||
const extractTime = (s: string | undefined, fallback: string): string => {
|
||||
if (!s) return fallback
|
||||
const d = new Date(s)
|
||||
if (Number.isNaN(d.getTime())) return fallback
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
|
||||
const combineDateTime = (
|
||||
d: Date | null,
|
||||
time: string,
|
||||
_current: string,
|
||||
): string => {
|
||||
if (!d) return ''
|
||||
const safeTime = /^\d{2}:\d{2}$/.test(time) ? time : '00:00'
|
||||
return formatIsoDateTime(d, safeTime)
|
||||
}
|
||||
|
||||
const isDateFormat = (s: JsonSchema): boolean =>
|
||||
s.type === 'string' && (s.format === 'date' || s.format === 'date-time')
|
||||
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import {
|
||||
buildSchemaJson,
|
||||
diffSchemas,
|
||||
hasBreakingChanges,
|
||||
parseSchemaJson,
|
||||
suggestVersionBump,
|
||||
type PropertyDef,
|
||||
} from './types'
|
||||
|
||||
const prop = (overrides: Partial<PropertyDef>): PropertyDef => ({
|
||||
id: 'p1',
|
||||
name: 'field',
|
||||
kind: 'string',
|
||||
required: false,
|
||||
unique: false,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('buildSchemaJson', () => {
|
||||
test('добавляет $schema, type, additionalProperties:false', () => {
|
||||
const s = buildSchemaJson([])
|
||||
expect(s.$schema).toContain('json-schema.org')
|
||||
expect(s.type).toBe('object')
|
||||
expect(s.additionalProperties).toBe(false)
|
||||
})
|
||||
|
||||
test('пропускает property без имени', () => {
|
||||
const s = buildSchemaJson([prop({ name: '' })])
|
||||
expect(s.properties).toEqual({})
|
||||
})
|
||||
|
||||
test('собирает required только из required:true', () => {
|
||||
const s = buildSchemaJson([
|
||||
prop({ name: 'a', required: true }),
|
||||
prop({ name: 'b', required: false }),
|
||||
])
|
||||
expect(s.required).toEqual(['a'])
|
||||
})
|
||||
|
||||
test('emit string поле с min/max/pattern', () => {
|
||||
const s = buildSchemaJson([prop({
|
||||
name: 'code',
|
||||
kind: 'string',
|
||||
minLength: 1,
|
||||
maxLength: 32,
|
||||
pattern: '^[A-Z]+$',
|
||||
})])
|
||||
const f = s.properties!.code
|
||||
expect(f.type).toBe('string')
|
||||
expect(f.minLength).toBe(1)
|
||||
expect(f.maxLength).toBe(32)
|
||||
expect(f.pattern).toBe('^[A-Z]+$')
|
||||
})
|
||||
|
||||
test('emit enum поле с string values', () => {
|
||||
const s = buildSchemaJson([prop({ name: 'status', kind: 'enum', enumValues: ['ACTIVE', 'INACTIVE'] })])
|
||||
const f = s.properties!.status
|
||||
expect(f.type).toBe('string')
|
||||
expect(f.enum).toEqual(['ACTIVE', 'INACTIVE'])
|
||||
})
|
||||
|
||||
test('emit localized как object с x-localized + patternProperties', () => {
|
||||
const s = buildSchemaJson([prop({ name: 'name', kind: 'localized' })])
|
||||
const f = s.properties!.name as Record<string, unknown>
|
||||
expect(f.type).toBe('object')
|
||||
expect(f['x-localized']).toBe(true)
|
||||
expect(f.patternProperties).toBeDefined()
|
||||
})
|
||||
|
||||
test('emit date / datetime через format', () => {
|
||||
const s = buildSchemaJson([
|
||||
prop({ name: 'launch', kind: 'date' }),
|
||||
prop({ name: 'epoch', kind: 'datetime' }),
|
||||
])
|
||||
expect(s.properties!.launch.format).toBe('date')
|
||||
expect(s.properties!.epoch.format).toBe('date-time')
|
||||
})
|
||||
|
||||
test('x-unique=true emit\'ит x-unique в schema', () => {
|
||||
const s = buildSchemaJson([prop({ name: 'code', kind: 'string', unique: true })])
|
||||
expect((s.properties!.code as Record<string, unknown>)['x-unique']).toBe(true)
|
||||
})
|
||||
|
||||
test('x-id-source emit\'ится в root schema', () => {
|
||||
const s = buildSchemaJson(
|
||||
[prop({ name: 'code', kind: 'string' })],
|
||||
'code',
|
||||
)
|
||||
expect((s as Record<string, unknown>)['x-id-source']).toBe('code')
|
||||
})
|
||||
|
||||
test('пустой idSource не emit\'ится', () => {
|
||||
const s = buildSchemaJson([prop({ name: 'code', kind: 'string' })])
|
||||
expect((s as Record<string, unknown>)['x-id-source']).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseSchemaJson roundtrip', () => {
|
||||
test('build → parse возвращает эквивалентный набор properties', () => {
|
||||
const original: PropertyDef[] = [
|
||||
prop({ id: '1', name: 'code', kind: 'string', required: true, minLength: 1, maxLength: 32 }),
|
||||
prop({ id: '2', name: 'name', kind: 'localized', required: true }),
|
||||
prop({ id: '3', name: 'status', kind: 'enum', enumValues: ['ACTIVE'] }),
|
||||
prop({ id: '4', name: 'mass', kind: 'number', minimum: 0, maximum: 100 }),
|
||||
prop({ id: '5', name: 'enabled', kind: 'boolean' }),
|
||||
prop({ id: '6', name: 'tags', kind: 'array_string', uniqueItems: true }),
|
||||
prop({ id: '7', name: 'launched', kind: 'date' }),
|
||||
prop({ id: '8', name: 'epoch', kind: 'datetime' }),
|
||||
]
|
||||
const json = buildSchemaJson(original, 'code')
|
||||
const parsed = parseSchemaJson(json)
|
||||
|
||||
expect(parsed.idSource).toBe('code')
|
||||
expect(parsed.properties).toHaveLength(original.length)
|
||||
|
||||
const byName = (key: string) => parsed.properties.find((p) => p.name === key)!
|
||||
expect(byName('code').kind).toBe('string')
|
||||
expect(byName('code').required).toBe(true)
|
||||
expect(byName('code').minLength).toBe(1)
|
||||
expect(byName('name').kind).toBe('localized')
|
||||
expect(byName('status').kind).toBe('enum')
|
||||
expect(byName('status').enumValues).toEqual(['ACTIVE'])
|
||||
expect(byName('mass').kind).toBe('number')
|
||||
expect(byName('mass').minimum).toBe(0)
|
||||
expect(byName('enabled').kind).toBe('boolean')
|
||||
expect(byName('tags').kind).toBe('array_string')
|
||||
expect(byName('tags').uniqueItems).toBe(true)
|
||||
expect(byName('launched').kind).toBe('date')
|
||||
expect(byName('epoch').kind).toBe('datetime')
|
||||
})
|
||||
|
||||
test('сохраняет x-unique через roundtrip', () => {
|
||||
const json = buildSchemaJson([prop({ name: 'code', kind: 'string', unique: true })])
|
||||
const parsed = parseSchemaJson(json)
|
||||
expect(parsed.properties[0].unique).toBe(true)
|
||||
})
|
||||
|
||||
test('пустой schema → пустой результат', () => {
|
||||
expect(parseSchemaJson(undefined)).toEqual({ properties: [], idSource: undefined })
|
||||
})
|
||||
})
|
||||
|
||||
describe('diffSchemas — breaking detection', () => {
|
||||
test('identical schemas → нет изменений', () => {
|
||||
const s = buildSchemaJson([prop({ name: 'a', kind: 'string' })])
|
||||
expect(diffSchemas(s, s)).toEqual([])
|
||||
})
|
||||
|
||||
test('removed property → breaking', () => {
|
||||
const before = buildSchemaJson([prop({ name: 'a', kind: 'string' })])
|
||||
const after = buildSchemaJson([])
|
||||
const changes = diffSchemas(before, after)
|
||||
expect(changes).toHaveLength(1)
|
||||
expect(changes[0].severity).toBe('breaking')
|
||||
expect(changes[0].field).toBe('a')
|
||||
})
|
||||
|
||||
test('type changed → breaking', () => {
|
||||
const before = buildSchemaJson([prop({ name: 'a', kind: 'string' })])
|
||||
const after = buildSchemaJson([prop({ name: 'a', kind: 'integer' })])
|
||||
const changes = diffSchemas(before, after)
|
||||
expect(changes.some((c) => c.severity === 'breaking' && c.reason.includes('type'))).toBe(true)
|
||||
})
|
||||
|
||||
test('became required → breaking', () => {
|
||||
const before = buildSchemaJson([prop({ name: 'a', kind: 'string', required: false })])
|
||||
const after = buildSchemaJson([prop({ name: 'a', kind: 'string', required: true })])
|
||||
expect(diffSchemas(before, after).some((c) => c.severity === 'breaking' && c.reason === 'now required')).toBe(true)
|
||||
})
|
||||
|
||||
test('became optional → compatible', () => {
|
||||
const before = buildSchemaJson([prop({ name: 'a', kind: 'string', required: true })])
|
||||
const after = buildSchemaJson([prop({ name: 'a', kind: 'string', required: false })])
|
||||
expect(diffSchemas(before, after).some((c) => c.severity === 'compatible' && c.reason === 'now optional')).toBe(true)
|
||||
})
|
||||
|
||||
test('enum value removed → breaking', () => {
|
||||
const before = buildSchemaJson([prop({ name: 's', kind: 'enum', enumValues: ['A', 'B'] })])
|
||||
const after = buildSchemaJson([prop({ name: 's', kind: 'enum', enumValues: ['A'] })])
|
||||
expect(diffSchemas(before, after).some((c) => c.severity === 'breaking' && c.reason.includes('enum'))).toBe(true)
|
||||
})
|
||||
|
||||
test('enum value added → compatible', () => {
|
||||
const before = buildSchemaJson([prop({ name: 's', kind: 'enum', enumValues: ['A'] })])
|
||||
const after = buildSchemaJson([prop({ name: 's', kind: 'enum', enumValues: ['A', 'B'] })])
|
||||
expect(diffSchemas(before, after).some((c) => c.severity === 'compatible' && c.reason.includes('enum'))).toBe(true)
|
||||
})
|
||||
|
||||
test('maxLength tightened → breaking', () => {
|
||||
const before = buildSchemaJson([prop({ name: 'a', kind: 'string', maxLength: 100 })])
|
||||
const after = buildSchemaJson([prop({ name: 'a', kind: 'string', maxLength: 50 })])
|
||||
expect(diffSchemas(before, after).some((c) => c.severity === 'breaking' && c.reason.includes('maxLength'))).toBe(true)
|
||||
})
|
||||
|
||||
test('новое required поле → breaking', () => {
|
||||
const before = buildSchemaJson([])
|
||||
const after = buildSchemaJson([prop({ name: 'new', kind: 'string', required: true })])
|
||||
expect(diffSchemas(before, after).some((c) => c.severity === 'breaking' && c.reason.includes('new required'))).toBe(true)
|
||||
})
|
||||
|
||||
test('новое optional поле → compatible', () => {
|
||||
const before = buildSchemaJson([])
|
||||
const after = buildSchemaJson([prop({ name: 'new', kind: 'string', required: false })])
|
||||
expect(diffSchemas(before, after).some((c) => c.severity === 'compatible' && c.reason.includes('new optional'))).toBe(true)
|
||||
})
|
||||
|
||||
test('hasBreakingChanges детектит хотя бы одно breaking', () => {
|
||||
const before = buildSchemaJson([prop({ name: 'a', kind: 'string' })])
|
||||
const after = buildSchemaJson([])
|
||||
expect(hasBreakingChanges(diffSchemas(before, after))).toBe(true)
|
||||
})
|
||||
|
||||
test('compatible-only changes: hasBreakingChanges=false', () => {
|
||||
const before = buildSchemaJson([])
|
||||
const after = buildSchemaJson([prop({ name: 'new', kind: 'string', required: false })])
|
||||
expect(hasBreakingChanges(diffSchemas(before, after))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('suggestVersionBump', () => {
|
||||
test('breaking → major bump', () => {
|
||||
expect(suggestVersionBump('1.2.3', [{ severity: 'breaking', field: 'a', reason: 'removed' }]))
|
||||
.toBe('2.0.0')
|
||||
})
|
||||
|
||||
test('compatible-only → minor bump', () => {
|
||||
expect(suggestVersionBump('1.2.3', [{ severity: 'compatible', field: 'a', reason: 'added' }]))
|
||||
.toBe('1.3.0')
|
||||
})
|
||||
|
||||
test('metadata-only → patch bump', () => {
|
||||
expect(suggestVersionBump('1.2.3', [{ severity: 'metadata', field: 'a', reason: 'description' }]))
|
||||
.toBe('1.2.4')
|
||||
})
|
||||
|
||||
test('пустой changes → версия не меняется', () => {
|
||||
expect(suggestVersionBump('1.2.3', [])).toBe('1.2.3')
|
||||
})
|
||||
|
||||
test('default 1.0.0 если current undefined', () => {
|
||||
expect(suggestVersionBump(undefined, [{ severity: 'breaking', field: 'x', reason: 'removed' }]))
|
||||
.toBe('2.0.0')
|
||||
})
|
||||
|
||||
test('mix of breaking + compatible → major (breaking побеждает)', () => {
|
||||
expect(suggestVersionBump('1.0.0', [
|
||||
{ severity: 'compatible', field: 'a', reason: 'added' },
|
||||
{ severity: 'breaking', field: 'b', reason: 'removed' },
|
||||
])).toBe('2.0.0')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import {
|
||||
combineDateTime,
|
||||
extractTime,
|
||||
formatIsoDate,
|
||||
formatIsoDateTime,
|
||||
localTzOffset,
|
||||
nowIsoLocal,
|
||||
parseFormDate,
|
||||
} from './dates'
|
||||
|
||||
describe('parseFormDate', () => {
|
||||
test('возвращает null для не-строки и пустой строки', () => {
|
||||
expect(parseFormDate(null)).toBeNull()
|
||||
expect(parseFormDate(undefined)).toBeNull()
|
||||
expect(parseFormDate(123)).toBeNull()
|
||||
expect(parseFormDate('')).toBeNull()
|
||||
})
|
||||
|
||||
test('pure-date YYYY-MM-DD парсится как локальная полуночь (без TZ-сдвига)', () => {
|
||||
const d = parseFormDate('2026-05-08')!
|
||||
expect(d.getFullYear()).toBe(2026)
|
||||
expect(d.getMonth()).toBe(4) // май = 4 (zero-indexed)
|
||||
expect(d.getDate()).toBe(8)
|
||||
expect(d.getHours()).toBe(0)
|
||||
expect(d.getMinutes()).toBe(0)
|
||||
})
|
||||
|
||||
test('ISO datetime с offset парсится корректно', () => {
|
||||
const d = parseFormDate('2026-05-08T14:30:00+03:00')!
|
||||
expect(d).toBeInstanceOf(Date)
|
||||
expect(Number.isNaN(d.getTime())).toBe(false)
|
||||
})
|
||||
|
||||
test('far-future (year >= 9999) возвращает null', () => {
|
||||
expect(parseFormDate('9999-12-31T23:59:59Z')).toBeNull()
|
||||
expect(parseFormDate('10000-01-01')).toBeNull()
|
||||
})
|
||||
|
||||
test('невалидная строка → null', () => {
|
||||
expect(parseFormDate('not-a-date')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatIsoDate', () => {
|
||||
test('форматирует Date как YYYY-MM-DD в local TZ', () => {
|
||||
const d = new Date(2026, 4, 8) // 8 мая 2026 local
|
||||
expect(formatIsoDate(d)).toBe('2026-05-08')
|
||||
})
|
||||
|
||||
test('паддит month/day двумя цифрами', () => {
|
||||
const d = new Date(2026, 0, 5)
|
||||
expect(formatIsoDate(d)).toBe('2026-01-05')
|
||||
})
|
||||
})
|
||||
|
||||
describe('localTzOffset', () => {
|
||||
test('возвращает offset в формате ±HH:mm', () => {
|
||||
const off = localTzOffset(new Date())
|
||||
expect(off).toMatch(/^[+-]\d{2}:\d{2}$/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatIsoDateTime', () => {
|
||||
test('собирает ISO с временем по умолчанию 00:00', () => {
|
||||
const d = new Date(2026, 4, 8) // 8 мая 2026 local
|
||||
const iso = formatIsoDateTime(d)
|
||||
expect(iso).toMatch(/^2026-05-08T00:00:00[+-]\d{2}:\d{2}$/)
|
||||
})
|
||||
|
||||
test('применяет переданное время', () => {
|
||||
const d = new Date(2026, 4, 8)
|
||||
const iso = formatIsoDateTime(d, '14:30')
|
||||
expect(iso).toMatch(/^2026-05-08T14:30:00[+-]\d{2}:\d{2}$/)
|
||||
})
|
||||
|
||||
test('round-trip: parse → format не меняет дату/время', () => {
|
||||
const orig = formatIsoDateTime(new Date(2026, 4, 8), '14:30')
|
||||
const parsed = parseFormDate(orig)!
|
||||
expect(parsed.getFullYear()).toBe(2026)
|
||||
expect(parsed.getMonth()).toBe(4)
|
||||
expect(parsed.getDate()).toBe(8)
|
||||
expect(parsed.getHours()).toBe(14)
|
||||
expect(parsed.getMinutes()).toBe(30)
|
||||
})
|
||||
})
|
||||
|
||||
describe('extractTime', () => {
|
||||
test('возвращает HH:mm из ISO datetime', () => {
|
||||
// 14:30 в local TZ — формируем явно через formatIsoDateTime
|
||||
const iso = formatIsoDateTime(new Date(2026, 4, 8), '14:30')
|
||||
expect(extractTime(iso, '00:00')).toBe('14:30')
|
||||
})
|
||||
|
||||
test('возвращает fallback для пустой строки', () => {
|
||||
expect(extractTime(undefined, '23:59')).toBe('23:59')
|
||||
expect(extractTime('', '00:00')).toBe('00:00')
|
||||
})
|
||||
|
||||
test('возвращает fallback для невалидной строки', () => {
|
||||
expect(extractTime('garbage', '12:34')).toBe('12:34')
|
||||
})
|
||||
|
||||
test('паддит часы и минуты двумя цифрами', () => {
|
||||
const iso = formatIsoDateTime(new Date(2026, 4, 8), '05:07')
|
||||
expect(extractTime(iso, '00:00')).toBe('05:07')
|
||||
})
|
||||
})
|
||||
|
||||
describe('combineDateTime', () => {
|
||||
test('null Date → пустая строка (для clear button)', () => {
|
||||
expect(combineDateTime(null, '14:30', 'previous')).toBe('')
|
||||
})
|
||||
|
||||
test('собирает ISO datetime из Date + HH:mm', () => {
|
||||
const d = new Date(2026, 4, 8)
|
||||
const iso = combineDateTime(d, '14:30', '')
|
||||
expect(iso).toMatch(/^2026-05-08T14:30:00[+-]\d{2}:\d{2}$/)
|
||||
})
|
||||
|
||||
test('защитный fallback на 00:00 при невалидном time', () => {
|
||||
const d = new Date(2026, 4, 8)
|
||||
const iso = combineDateTime(d, 'invalid', '')
|
||||
expect(iso).toMatch(/^2026-05-08T00:00:00[+-]\d{2}:\d{2}$/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('nowIsoLocal', () => {
|
||||
test('возвращает ISO datetime в local TZ', () => {
|
||||
const iso = nowIsoLocal()
|
||||
expect(iso).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:00[+-]\d{2}:\d{2}$/)
|
||||
})
|
||||
|
||||
test('parsable обратно в Date', () => {
|
||||
const iso = nowIsoLocal()
|
||||
const d = parseFormDate(iso)
|
||||
expect(d).not.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Helpers для работы с датами в формах. Все функции делают TZ-aware преобразования
|
||||
* чтобы избежать day-shift на 1 при парсинге/форматировании в timezones отличных
|
||||
* от UTC.
|
||||
*/
|
||||
|
||||
/** Парсит ISO-строку в Date. Pure-date "YYYY-MM-DD" → local midnight, иначе new Date(s). */
|
||||
export const parseFormDate = (s: unknown): Date | null => {
|
||||
if (typeof s !== 'string' || !s) return null
|
||||
const pureDate = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s)
|
||||
const d = pureDate
|
||||
? new Date(Number(pureDate[1]), Number(pureDate[2]) - 1, Number(pureDate[3]))
|
||||
: new Date(s)
|
||||
if (Number.isNaN(d.getTime())) return null
|
||||
if (d.getFullYear() >= 9999) return null
|
||||
return d
|
||||
}
|
||||
|
||||
/** Возвращает дату как "YYYY-MM-DD" в локальном TZ. */
|
||||
export const formatIsoDate = (d: Date): string => {
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
||||
}
|
||||
|
||||
/** Локальный TZ offset в формате ±HH:mm для ISO строк. */
|
||||
export const localTzOffset = (d: Date): string => {
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
const total = -d.getTimezoneOffset()
|
||||
const sign = total >= 0 ? '+' : '-'
|
||||
const abs = Math.abs(total)
|
||||
return `${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`
|
||||
}
|
||||
|
||||
/** ISO-8601 datetime в local TZ: "2026-05-08T23:59:00+03:00". */
|
||||
export const formatIsoDateTime = (d: Date, time: string = '00:00'): string => {
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
const [hh, mm] = time.split(':').map(Number)
|
||||
const local = new Date(d.getFullYear(), d.getMonth(), d.getDate(), hh || 0, mm || 0, 0)
|
||||
return `${formatIsoDate(local)}T${pad(local.getHours())}:${pad(local.getMinutes())}:00${localTzOffset(local)}`
|
||||
}
|
||||
|
||||
/** Извлекает HH:mm из ISO datetime в local TZ. */
|
||||
export const extractTime = (s: string | undefined, fallback: string): string => {
|
||||
if (!s) return fallback
|
||||
const d = new Date(s)
|
||||
if (Number.isNaN(d.getTime())) return fallback
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
|
||||
/** Собирает Date + HH:mm в local-TZ ISO datetime. null Date → пустая строка. */
|
||||
export const combineDateTime = (
|
||||
d: Date | null,
|
||||
time: string,
|
||||
_current: string,
|
||||
): string => {
|
||||
if (!d) return ''
|
||||
const safeTime = /^\d{2}:\d{2}$/.test(time) ? time : '00:00'
|
||||
return formatIsoDateTime(d, safeTime)
|
||||
}
|
||||
|
||||
/** "Сейчас" как local-TZ ISO datetime. Используется как default validFrom при Edit. */
|
||||
export const nowIsoLocal = (): string => {
|
||||
const d = new Date()
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${formatIsoDate(d)}T${pad(d.getHours())}:${pad(d.getMinutes())}:00${localTzOffset(d)}`
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import type { CreateRecordRequest, FlattenedRecord } from '@/api/client'
|
||||
import { SchemaDrivenForm } from '@/components/form/SchemaDrivenForm'
|
||||
import { DictionaryEditorDialog } from '@/components/schema/DictionaryEditorDialog'
|
||||
import { RecordHistoryDrawer } from '@/components/record/RecordHistoryDrawer'
|
||||
import { nowIsoLocal } from '@/lib/dates'
|
||||
|
||||
export const Route = createFileRoute('/dictionaries/$name')({
|
||||
component: DictionaryDetail,
|
||||
@@ -323,16 +324,6 @@ function DictionaryDetail() {
|
||||
)
|
||||
}
|
||||
|
||||
const nowIsoLocal = (): string => {
|
||||
const d = new Date()
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
const off = -d.getTimezoneOffset()
|
||||
const sign = off >= 0 ? '+' : '-'
|
||||
const abs = Math.abs(off)
|
||||
const tz = `${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:00${tz}`
|
||||
}
|
||||
|
||||
const toIsoDate = (iso: string | undefined): string => {
|
||||
if (!iso) return ''
|
||||
const d = new Date(iso)
|
||||
|
||||
Reference in New Issue
Block a user