FIX - allow configurator company creation (#33)

The generic mutable-table blank template persisted incomplete company definitions before runtime domain validation. Seed valid company defaults, validate before SQL writes, and repair legacy blank entries.
This commit is contained in:
Leon.Schmidt
2026-08-23 19:20:37 +02:00
committed by GitHub
parent 312ae8a3a3
commit a12e43b624
14 changed files with 744 additions and 132 deletions
@@ -41,7 +41,7 @@ describe('Companies emergency request contract', () => {
const mockPolice = sourceBlock(
testServer,
'const companyProfiles = [',
" {\n acceptsRequests: false,\n announcement: null,",
' {\n acceptsRequests: false,\n announcement: null,',
)
expect(police).toContain('Emergency = true')
@@ -56,7 +56,7 @@ describe('Companies emergency request contract', () => {
it('authorizes configured emergency companies through the normal request gates', () => {
const validation = sourceBlock(
companiesServer,
'local function validate_configuration()',
'local function validate_configuration(configuration)',
'local function seed_companies()',
)
const payload = sourceBlock(
@@ -103,9 +103,7 @@ describe('Companies emergency request contract', () => {
'\n\nrefresh_runtime_configuration()',
)
expect(migration).toContain(
'sky-phone:companies:requestable-emergency:v1',
)
expect(migration).toContain('sky-phone:companies:requestable-emergency:v1')
expect(migration).toContain(
'if definition.Emergency and definition.AcceptsRequests then',
)
@@ -133,7 +131,9 @@ describe('Companies emergency request contract', () => {
expect(migration).toContain(
'police.AcceptsRequests = defaults.AcceptsRequests',
)
expect(migration).toContain('police.Services = copy_value(defaults.Services)')
expect(migration).toContain(
'police.Services = copy_value(defaults.Services)',
)
expect(migration).toContain('SET `config_payload` = ?')
expect(migration).toContain('`revision` = `revision` + 1')
expect(migration).toContain('INSERT IGNORE INTO `sky_phone_migrations`')
@@ -0,0 +1,109 @@
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
const companiesServer = readFileSync(
new URL('../../sky_phone/source/server/companies.lua', import.meta.url),
'utf8',
).replace(/\r\n/g, '\n')
const configuratorServer = readFileSync(
new URL(
'../../sky_phone/source/server/phone_configurator.lua',
import.meta.url,
),
'utf8',
).replace(/\r\n/g, '\n')
const englishLocale = readFileSync(
new URL('../../sky_phone/config/locales/en.lua', import.meta.url),
'utf8',
)
const germanLocale = readFileSync(
new URL('../../sky_phone/config/locales/de.lua', import.meta.url),
'utf8',
)
const spanishLocale = readFileSync(
new URL('../../sky_phone/config/locales/es.lua', import.meta.url),
'utf8',
)
describe('company configurator creation contract', () => {
it('publishes complete defaults for newly added company definitions', () => {
expect(configuratorServer).toContain(
'local function company_definition_entry_default(company_id, configuration)',
)
expect(configuratorServer).toContain(
'local function next_available_company_service_number(configuration)',
)
expect(configuratorServer).toContain(
'entryDefault = company_definition_entry_default()',
)
expect(configuratorServer).toContain('Routing = "round_robin"')
expect(configuratorServer).toContain('RequestsEnabled = true')
})
it('validates the candidate runtime config before encoding or writing SQL', () => {
const save = configuratorServer.slice(
configuratorServer.indexOf('function SkyPhoneConfigurator.Save('),
)
const validation = save.indexOf(
'SkyPhoneCompanies.ValidateConfiguration(candidate_config)',
)
const encoding = save.indexOf(
'local config_encoded = encode_payload(next_config, "config")',
)
const update = save.indexOf('UPDATE `%s`')
expect(validation).toBeGreaterThanOrEqual(0)
expect(validation).toBeLessThan(encoding)
expect(validation).toBeLessThan(update)
expect(save).toContain(
'return { success = false, error = "invalid_company_configuration" }',
)
})
it('validates into isolated registries before replacing the live company state', () => {
expect(companiesServer).toContain(
'function SkyPhoneCompanies.ValidateConfiguration(configuration)',
)
expect(companiesServer).toContain(
'local validated, validation_error = validate_configuration(configuration)',
)
expect(companiesServer).toContain('definitions = validated.definitions')
expect(companiesServer).toContain(
'definition_ids = validated.definition_ids',
)
})
it('localizes rejected company configurations in every shipped locale', () => {
for (const locale of [englishLocale, germanLocale, spanishLocale]) {
expect(locale).toContain('invalid_company_configuration =')
}
})
it('repairs company rows created by the legacy blank schema before Companies starts', () => {
const migration = configuratorServer.slice(
configuratorServer.indexOf(
'local function migrate_blank_company_definitions()',
),
configuratorServer.indexOf(
'local function migrate_police_request_defaults()',
),
)
const blankRegistration = configuratorServer.indexOf(
'Bridge.Database.AfterMigration("sky_phone", migrate_blank_company_definitions)',
)
const policeRegistration = configuratorServer.indexOf(
'Bridge.Database.AfterMigration("sky_phone", migrate_police_request_defaults)',
)
expect(migration).toContain(
'sky-phone:configurator:company-definition-defaults:v1',
)
expect(migration).toContain('company_definition_entry_default(')
expect(migration).toContain('Bridge.Database.Transaction(statements)')
expect(migration).toContain('SET `config_payload` = ?')
expect(migration).toContain('`revision` = `revision` + 1')
expect(blankRegistration).toBeGreaterThanOrEqual(0)
expect(blankRegistration).toBeLessThan(policeRegistration)
})
})
@@ -10,6 +10,10 @@ import { computed, ref } from 'vue'
import { vConfigInputWidth } from '@/directives/configInputWidth'
import type { AdminConfiguratorStructure } from '@/types/admin'
import {
blankFromConfiguratorStructure,
createMutableTableEntry,
} from '@/utils/adminConfiguratorDefaults'
import type { AdminConfiguratorDescribe } from '@/utils/adminConfiguratorDescription'
export type AdminConfigEditorLabels = {
@@ -342,40 +346,6 @@ function mapValuePath(entry: SerializedMapEntry): string {
return props.path ? `${props.path}.${entry.key}` : String(entry.key)
}
function blankFromStructure(structure: AdminConfiguratorStructure): unknown {
if (structure.kind === 'optionalString') return ''
if (structure.kind === 'value') return blankValue(structure.valueType)
if (structure.kind === 'vector') {
const axes = ['x', 'y', 'z', 'w'].slice(
0,
Number(structure.vectorType.slice(-1)),
)
return Object.fromEntries([
['__skyType', structure.vectorType],
...axes.map((axis) => [axis, 0]),
])
}
if (structure.kind === 'list') {
return structure.items.map(blankFromStructure)
}
if (structure.kind === 'map') {
return {
__skyType: 'map',
entries: structure.entries.map((entry) => ({
key: entry.key,
keyType: entry.keyType,
value: blankFromStructure(entry.structure),
})),
}
}
return Object.fromEntries(
Object.entries(structure.fields).map(([key, field]) => [
key,
blankFromStructure(field),
]),
)
}
function updateScalar(event: Event): void {
const target = event.target
if (!(target instanceof HTMLInputElement)) return
@@ -413,7 +383,7 @@ function addListRow(): void {
const value = rows.length
? blankLike(rows[0])
: listTemplate.value
? blankFromStructure(listTemplate.value)
? blankFromConfiguratorStructure(listTemplate.value)
: blankValue(newArrayKind.value)
rows.push(value)
emit('update:modelValue', rows)
@@ -476,12 +446,21 @@ function addTableField(): void {
const template = tableStructure.value?.mutableKeys
? tableStructure.value.template
: undefined
const value = template
? blankFromStructure(template)
: blankCollectionValue(
newObjectKind.value,
Object.values(tableValue.value).filter((_, index) => index < 50),
const structuredValue = tableStructure.value?.mutableKeys
? createMutableTableEntry(
tableStructure.value,
props.path,
key,
tableValue.value,
)
: undefined
const value =
structuredValue !== undefined
? structuredValue
: blankCollectionValue(
newObjectKind.value,
Object.values(tableValue.value).filter((_, index) => index < 50),
)
emit('update:modelValue', {
...tableValue.value,
[key]: value,
@@ -556,7 +535,7 @@ function addMapEntry(): void {
if (!canAddMapEntry.value || parsedNewMapKey.value === null) return
const key = parsedNewMapKey.value
const value = mapTemplate.value
? blankFromStructure(mapTemplate.value)
? blankFromConfiguratorStructure(mapTemplate.value)
: blankCollectionValue(
newMapValueKind.value,
mapEntries.value.slice(0, 50).map((entry) => entry.value),
@@ -196,9 +196,7 @@ describe('standalone admin panel contracts', () => {
expect(configuratorServer).toContain('Apps = true,')
expect(phoneServer).toContain('function SkyPhone.IsAppEnabled(app_id)')
expect(phoneServer).toContain('function SkyPhone.GetDisabledApps()')
expect(phoneServer).toContain(
'disabledApps = SkyPhone.GetDisabledApps()',
)
expect(phoneServer).toContain('disabledApps = SkyPhone.GetDisabledApps()')
expect(server).toContain('if not SkyPhone.IsAppEnabled(app_id) then')
expect(server).toContain('disabledApps = SkyPhone.GetDisabledApps()')
expect(store).toContain('disabledApps: [] as string[]')
@@ -499,7 +497,8 @@ describe('standalone admin panel contracts', () => {
expect(configuratorValueEditor).toContain('function tableFieldStructure(')
expect(configuratorValueEditor).toContain('function isFixedTableField(')
expect(configuratorValueEditor).toContain('function blankCollectionValue(')
expect(configuratorValueEditor).toContain('function blankFromStructure(')
expect(configuratorValueEditor).toContain('blankFromConfiguratorStructure')
expect(configuratorValueEditor).toContain('createMutableTableEntry(')
expect(source).toContain("'is-structured': field.type === 'json'")
expect(configuratorValueEditor).toContain('function isStructuredValue(')
expect(configuratorValueEditor).toContain(
+1
View File
@@ -138,6 +138,7 @@ export type AdminConfiguratorStructure =
template?: AdminConfiguratorStructure
}
| {
entryDefault?: unknown
fields: Record<string, AdminConfiguratorStructure>
kind: 'table'
mutableKeys?: boolean
@@ -0,0 +1,114 @@
import { describe, expect, it } from 'vitest'
import type { AdminConfiguratorStructure } from '@/types/admin'
import { createMutableTableEntry } from '@/utils/adminConfiguratorDefaults'
describe('admin configurator defaults', () => {
it('creates a usable company draft from its key and the server defaults', () => {
const entryDefault = {
AcceptsRequests: true,
Category: 'public_services',
Job: '',
LogoUrl: 'https://picsum.photos/seed/companies-new-logo/180/180',
Name: '',
ServiceLine: {
Number: '500',
Routing: 'round_robin',
},
Services: [
{
Description: '',
Id: '',
Price: '',
RequestsEnabled: true,
Title: '',
},
],
}
const structure: AdminConfiguratorStructure = {
entryDefault,
fields: {},
kind: 'table',
mutableKeys: true,
template: {
fields: {
Job: { kind: 'value', valueType: 'string' },
Name: { kind: 'value', valueType: 'string' },
},
kind: 'table',
},
}
expect(
createMutableTableEntry(
structure,
'Companies.Definitions',
'pizza_palace',
),
).toEqual({
AcceptsRequests: true,
Category: 'public_services',
Job: 'pizza_palace',
LogoUrl: 'https://picsum.photos/seed/companies-pizza_palace-logo/180/180',
Name: 'Pizza Palace',
ServiceLine: {
Number: '500',
Routing: 'round_robin',
},
Services: [
{
Description: '',
Id: 'pizza_palace',
Price: '',
RequestsEnabled: true,
Title: 'Pizza Palace',
},
],
})
expect(entryDefault).toMatchObject({
Job: '',
Name: '',
Services: [{ Id: '', Title: '' }],
})
})
it('allocates distinct service numbers for multiple unsaved companies', () => {
const structure: AdminConfiguratorStructure = {
entryDefault: {
Job: '',
LogoUrl: '',
Name: '',
ServiceLine: { Number: '500' },
},
fields: {},
kind: 'table',
mutableKeys: true,
}
const existing = {
pizzeria: { ServiceLine: { Number: '500' } },
restaurant: { ServiceLine: { Number: '501' } },
}
expect(
createMutableTableEntry(
structure,
'Companies.Definitions',
'bakery',
existing,
),
).toMatchObject({ ServiceLine: { Number: '502' } })
})
it('keeps generic mutable tables on their schema-derived blank value', () => {
const structure: AdminConfiguratorStructure = {
fields: {},
kind: 'table',
mutableKeys: true,
template: { kind: 'value', valueType: 'boolean' },
}
expect(createMutableTableEntry(structure, 'FeatureFlags', 'example')).toBe(
false,
)
})
})
@@ -0,0 +1,142 @@
import type { AdminConfiguratorStructure } from '@/types/admin'
function cloneConfiguratorValue(value: unknown): unknown {
if (Array.isArray(value)) return value.map(cloneConfiguratorValue)
if (value !== null && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value).map(([key, child]) => [
key,
cloneConfiguratorValue(child),
]),
)
}
return value
}
function blankScalar(valueType: 'boolean' | 'number' | 'string'): unknown {
if (valueType === 'boolean') return false
if (valueType === 'number') return 0
return ''
}
export function blankFromConfiguratorStructure(
structure: AdminConfiguratorStructure,
): unknown {
if (structure.kind === 'optionalString') return ''
if (structure.kind === 'value') return blankScalar(structure.valueType)
if (structure.kind === 'vector') {
const axes = ['x', 'y', 'z', 'w'].slice(
0,
Number(structure.vectorType.slice(-1)),
)
return Object.fromEntries([
['__skyType', structure.vectorType],
...axes.map((axis) => [axis, 0]),
])
}
if (structure.kind === 'list') {
return structure.items.map(blankFromConfiguratorStructure)
}
if (structure.kind === 'map') {
return {
__skyType: 'map',
entries: structure.entries.map((entry) => ({
key: entry.key,
keyType: entry.keyType,
value: blankFromConfiguratorStructure(entry.structure),
})),
}
}
return Object.fromEntries(
Object.entries(structure.fields).map(([key, field]) => [
key,
blankFromConfiguratorStructure(field),
]),
)
}
export function createMutableTableEntry(
structure: Extract<AdminConfiguratorStructure, { kind: 'table' }>,
path: string,
key: string,
entries: Record<string, unknown> = {},
): unknown {
const value =
structure.entryDefault !== undefined
? cloneConfiguratorValue(structure.entryDefault)
: structure.template
? blankFromConfiguratorStructure(structure.template)
: undefined
if (
path !== 'Companies.Definitions' ||
value === null ||
typeof value !== 'object' ||
Array.isArray(value)
) {
return value
}
const company = value as Record<string, unknown>
company.Job = key
company.Name = key
.replace(/[_-]+/g, ' ')
.replace(/\b\w/g, (character) => character.toUpperCase())
company.LogoUrl = `https://picsum.photos/seed/companies-${key}-logo/180/180`
if (Array.isArray(company.Services)) {
if (company.Services.length === 0) {
company.Services.push({
Description: '',
Id: key,
Price: '',
RequestsEnabled: true,
Title: company.Name,
})
} else {
const service = company.Services[0]
if (
service !== null &&
typeof service === 'object' &&
!Array.isArray(service) &&
!(service as Record<string, unknown>).Id
) {
const mutableService = service as Record<string, unknown>
mutableService.Id = key
mutableService.Title = company.Name
}
}
}
const serviceLine = company.ServiceLine
if (
serviceLine !== null &&
typeof serviceLine === 'object' &&
!Array.isArray(serviceLine)
) {
const mutableServiceLine = serviceLine as Record<string, unknown>
const number = String(mutableServiceLine.Number ?? '')
const numeric = Number(number)
if (/^\d+$/.test(number) && Number.isSafeInteger(numeric) && numeric > 0) {
const used = new Set(
Object.values(entries).map((entry) => {
if (entry === null || typeof entry !== 'object') return ''
const line = (entry as Record<string, unknown>).ServiceLine
if (line === null || typeof line !== 'object') return ''
return String((line as Record<string, unknown>).Number ?? '').replace(
/\D/g,
'',
)
}),
)
const maximum = 10 ** number.length - 1
for (let offset = 0; offset < maximum; offset += 1) {
const candidate = ((numeric - 1 + offset) % maximum) + 1
const formatted = String(candidate).padStart(number.length, '0')
if (!used.has(formatted)) {
mutableServiceLine.Number = formatted
break
}
}
}
}
return company
}
@@ -476,6 +476,66 @@ function emptyStructure(scope, path) {
return undefined
}
function companyDefinitionEntryDefault(definitions) {
const firstDefinition = definitions[Object.keys(definitions).sort()[0]]
const usedNumbers = new Set(
Object.values(definitions).map((definition) =>
String(definition.ServiceLine.Number).replace(/\D/g, ''),
),
)
let serviceNumber = ''
for (let offset = 0; offset < 999; offset += 1) {
const candidate = String(((499 + offset) % 999) + 1).padStart(3, '0')
if (!usedNumbers.has(candidate)) {
serviceNumber = candidate
break
}
}
return {
AcceptsRequests: true,
Address: '',
Category: firstDefinition.Category,
DefaultAvailability: 'closed',
Description: '',
District: '',
Emergency: false,
Icon: 'building',
Job: '',
Location: { __skyType: 'vector3', x: 0, y: 0, z: 0 },
LocationLabel: '',
LogoUrl: 'https://picsum.photos/seed/companies-new-logo/180/180',
Name: '',
Permissions: {
Announcement: 0,
Assign: 0,
Availability: 0,
Hours: 0,
Profile: 0,
Services: 0,
WorkQueue: 0,
},
Public: true,
ServiceLine: {
AutoContact: true,
CanCall: true,
CanMessage: false,
MinimumGrade: 0,
Number: serviceNumber,
Routing: 'round_robin',
},
Services: [
{
Description: '',
Id: '',
Price: '',
RequestsEnabled: true,
Title: '',
},
],
Verified: false,
}
}
function buildStructure(value, scope, path) {
if (scope === 'config' && path === 'Phone.Keybind') {
return { kind: 'optionalString' }
@@ -495,6 +555,7 @@ function buildStructure(value, scope, path) {
]),
)
return {
entryDefault: companyDefinitionEntryDefault(value),
fields,
kind: 'table',
mutableKeys: true,
@@ -12,6 +12,7 @@ type ConfiguratorField = {
}
type ConfiguratorStructure = {
entryDefault?: unknown
entries?: Array<{ structure: ConfiguratorStructure }>
fields?: Record<string, ConfiguratorStructure>
items?: ConfiguratorStructure[]
@@ -122,6 +123,22 @@ describe('admin configurator fixture', () => {
expect(phone?.structure?.fields?.Keybind.kind).toBe('optionalString')
expect(companyJobs?.label).toBe('Jobs')
expect(companyJobs?.structure).toMatchObject({
entryDefault: {
AcceptsRequests: true,
Category: 'public_services',
Job: '',
ServiceLine: {
Number: '500',
Routing: 'round_robin',
},
Services: [
{
Id: '',
RequestsEnabled: true,
Title: '',
},
],
},
fields: {
ambulance: { kind: 'table' },
police: { kind: 'table' },
@@ -140,9 +157,7 @@ describe('admin configurator fixture', () => {
.flatMap((section) => section.fields)
.find((field) => field.path === 'Companies.Definitions')
const police = (
companyJobs?.value as
| Record<string, Record<string, unknown>>
| undefined
companyJobs?.value as Record<string, Record<string, unknown>> | undefined
)?.police
expect(police).toMatchObject({