:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
export type PropertyType = 'String' | 'Numeric' | 'Boolean' | 'DateTime' | 'Object' | 'Array'
export const MAX_PROPERTY_NAME_LENGTH = 200
export const PROPERTY_TYPE_OPTIONS: { value: PropertyType; label: string }[] = [
{ value: 'String', label: 'String' },
{ value: 'Numeric', label: 'Numeric' },
{ value: 'Boolean', label: 'Boolean' },
{ value: 'DateTime', label: 'DateTime' },
{ value: 'Object', label: 'Object' },
{ value: 'Array', label: 'Array' },
]
function getErrorMessage(error: any, defaultMessage: string): string {
// Handle field-specific errors from DRF serializer
if (error.name) {
return error.name
}
if (error.properties) {
return error.properties
}
// Handle detail string errors
if (error.detail) {
const detail = error.detail
// Handle duplicate property name constraint
if (typeof detail === 'string' && detail.includes('unique_property_group_property_name')) {
const nameMatch = detail.match(/\(property_group_id, name\)=\([^,]+, ([^)]+)\)/)
if (nameMatch) {
return `A property named "${nameMatch[1]}" already exists in this group`
}
return 'A property with this name already exists in this group'
}
// Handle duplicate property group name constraint
if (typeof detail === 'string' && detail.includes('unique_property_group_name')) {
const nameMatch = detail.match(/\(team_id, name\)=\([^,]+, ([^)]+)\)/)
if (nameMatch) {
return `A property group named "${nameMatch[1]}" already exists`
}
return 'A property group with this name already exists'
}
// Return the detail if it's a user-friendly string
if (typeof detail === 'string' && !detail.includes('IntegrityError') && !detail.includes('Key (')) {
return detail
}
}
if (error.message && !error.message.includes('IntegrityError')) {
return error.message
}
return defaultMessage
}
export interface SchemaPropertyGroupProperty {
id: string
name: string
property_type: PropertyType
is_required: boolean
is_optional_in_types: boolean
description: string
}
export interface EventDefinitionBasic {
id: string
name: string
}
export interface SchemaPropertyGroup {
id: string
name: string
description: string
properties: SchemaPropertyGroupProperty[]
events: EventDefinitionBasic[]
created_at: string
updated_at: string
}
export interface SchemaManagementLogicProps {
key?: string
}
export interface PropertyGroupFormType {
name: string
description: string
properties: SchemaPropertyGroupProperty[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface schemaManagementLogicValues {
currentProjectId: number | string // teamLogic
editingPropertyGroup: SchemaPropertyGroup | null
filteredPropertyGroups: SchemaPropertyGroup[]
isPropertyGroupFormSubmitting: boolean
isPropertyGroupFormValid: boolean
propertyGroupForm: PropertyGroupFormType
propertyGroupFormAllErrors: Record<string, any>
propertyGroupFormChanged: boolean
propertyGroupFormErrors: DeepPartialMap<PropertyGroupFormType, ValidationErrorType>
propertyGroupFormHasErrors: boolean
propertyGroupFormManualErrors: Record<string, any>
propertyGroupFormTouched: boolean
propertyGroupFormTouches: Record<string, boolean>
propertyGroupFormValidationError: string | null
propertyGroupFormValidationErrors: DeepPartialMap<PropertyGroupFormType, ValidationErrorType>
propertyGroupModalOpen: boolean
propertyGroups: SchemaPropertyGroup[]
propertyGroupsLoading: boolean
searchTerm: string
showPropertyGroupFormErrors: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface schemaManagementLogicActions {
addPropertyToForm: () => {
value: true
}
createPropertyGroup: (data: Partial<SchemaPropertyGroup>) => Partial<SchemaPropertyGroup>
createPropertyGroupFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
createPropertyGroupSuccess: (
propertyGroups: any[],
payload?: Partial<SchemaPropertyGroup>
) => {
propertyGroups: any[]
payload?: Partial<SchemaPropertyGroup>
}
deletePropertyGroup: (id: string) => {
id: string
}
loadPropertyGroups: () => any
loadPropertyGroupsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadPropertyGroupsSuccess: (
propertyGroups: SchemaPropertyGroup[],
payload?: any
) => {
propertyGroups: SchemaPropertyGroup[]
payload?: any
}
removePropertyFromForm: (index: number) => {
index: number
}
resetPropertyGroupForm: (values?: PropertyGroupFormType) => {
values?: PropertyGroupFormType
}
setEditingPropertyGroup: (propertyGroup: SchemaPropertyGroup | null) => {
propertyGroup: SchemaPropertyGroup | null
}
setPropertyGroupFormManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
setPropertyGroupFormValue: (
key: FieldName,
value: any
) => {
name: FieldName
value: any
}
setPropertyGroupFormValues: (values: DeepPartial<PropertyGroupFormType>) => {
values: DeepPartial<PropertyGroupFormType>
}
setPropertyGroupModalOpen: (open: boolean) => {
open: boolean
}
setSearchTerm: (searchTerm: string) => {
searchTerm: string
}
submitPropertyGroupForm: () => {
value: boolean
}
submitPropertyGroupFormFailure: (
error: Error,
errors: Record<string, any>
) => {
error: Error
errors: Record<string, any>
}
submitPropertyGroupFormRequest: (propertyGroupForm: PropertyGroupFormType) => {
propertyGroupForm: PropertyGroupFormType
}
submitPropertyGroupFormSuccess: (propertyGroupForm: PropertyGroupFormType) => {
propertyGroupForm: PropertyGroupFormType
}
touchPropertyGroupFormField: (key: string) => {
key: string
}
updatePropertyGroup: ({ id, data }: { data: Partial<SchemaPropertyGroup>; id: string }) => {
id: string
data: Partial<SchemaPropertyGroup>
}
updatePropertyGroupFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
updatePropertyGroupSuccess: (
propertyGroups: any[],
payload?: {
id: string
data: Partial<SchemaPropertyGroup>
}
) => {
propertyGroups: any[]
payload?: {
id: string
data: Partial<SchemaPropertyGroup>
}
}
updatePropertyInForm: (
index: number,
updates: Partial<SchemaPropertyGroupProperty>
) => {
index: number
updates: Partial<SchemaPropertyGroupProperty>
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface schemaManagementLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
filteredPropertyGroups: (propertyGroups: SchemaPropertyGroup[], searchTerm: string) => SchemaPropertyGroup[]
propertyGroupFormValidationError: (propertyGroupForm: PropertyGroupFormType) => string | null
}
}
export type schemaManagementLogicType = MakeLogicType<
schemaManagementLogicValues,
schemaManagementLogicActions,
SchemaManagementLogicProps,
schemaManagementLogicMeta
>
export const schemaManagementLogic = kea<schemaManagementLogicType>([
path(['scenes', 'data-management', 'schema', 'schemaManagementLogic']),
props({} as SchemaManagementLogicProps),
key((props) => props.key || 'default'),
connect(() => ({
values: [teamLogic, ['currentProjectId']],
})),
actions({
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
setPropertyGroupModalOpen: (open: boolean) => ({ open }),
setEditingPropertyGroup: (propertyGroup: SchemaPropertyGroup | null) => ({ propertyGroup }),
deletePropertyGroup: (id: string) => ({ id }),
addPropertyToForm: true,
updatePropertyInForm: (index: number, updates: Partial<SchemaPropertyGroupProperty>) => ({ index, updates }),
removePropertyFromForm: (index: number) => ({ index }),
}),
loaders(({ values }) => ({
propertyGroups: [
[] as SchemaPropertyGroup[],
{
loadPropertyGroups: async () => {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
const response = await api.get(`api/projects/${values.currentProjectId}/schema_property_groups/`)
return response.results || response || []
},
createPropertyGroup: async (data: Partial<SchemaPropertyGroup>) => {
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
const response = await api.create(
`api/projects/${values.currentProjectId}/schema_property_groups/`,
data
)
lemonToast.success('Property group created')
return [response, ...values.propertyGroups]
} catch (error: any) {
const errorMessage = getErrorMessage(error, 'Failed to create property group')
lemonToast.error(errorMessage)
throw new Error(errorMessage)
}
},
updatePropertyGroup: async ({ id, data }: { id: string; data: Partial<SchemaPropertyGroup> }) => {
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
const response = await api.update(
`api/projects/${values.currentProjectId}/schema_property_groups/${id}/`,
data
)
lemonToast.success('Property group updated')
return values.propertyGroups.map((pg) => (pg.id === id ? response : pg))
} catch (error: any) {
const errorMessage = getErrorMessage(error, 'Failed to update property group')
lemonToast.error(errorMessage)
throw new Error(errorMessage)
}
},
},
],
})),
forms(({ actions, values }) => ({
propertyGroupForm: {
options: { showErrorsOnTouch: true },
defaults: { name: '', description: '', properties: [] } as PropertyGroupFormType,
errors: ({ name }) => ({
name: !name?.trim() ? 'Property group name is required' : undefined,
}),
submit: async (formValues) => {
// Check for validation errors
const validationError = values.propertyGroupFormValidationError
if (validationError) {
lemonToast.error(validationError)
throw new Error(validationError)
}
const data = {
name: formValues.name,
description: formValues.description,
properties: formValues.properties.map((p) => ({ ...p, name: p.name.trim() })),
}
try {
if (values.editingPropertyGroup) {
await actions.updatePropertyGroup({ id: values.editingPropertyGroup.id, data })
} else {
await actions.createPropertyGroup(data)
}
actions.setPropertyGroupModalOpen(false)
} catch (error) {
// Error is already handled by the loaders
throw error
}
},
},
})),
reducers({
searchTerm: [
'',
{
setSearchTerm: (_, { searchTerm }) => searchTerm,
},
],
propertyGroupModalOpen: [
false,
{
setPropertyGroupModalOpen: (_, { open }) => open,
},
],
editingPropertyGroup: [
null as SchemaPropertyGroup | null,
{
setEditingPropertyGroup: (_, { propertyGroup }) => propertyGroup,
setPropertyGroupModalOpen: (state, { open }) => (open ? state : null),
},
],
propertyGroupForm: [
{ name: '', description: '', properties: [] } as PropertyGroupFormType,
{
addPropertyToForm: (state) => ({
...state,
properties: [
...state.properties,
{
id: `new-${Date.now()}`,
name: '',
property_type: 'String' as PropertyType,
is_required: false,
is_optional_in_types: false,
description: '',
},
],
}),
updatePropertyInForm: (state, { index, updates }) => ({
...state,
properties: state.properties.map((prop, i) => (i === index ? { ...prop, ...updates } : prop)),
}),
removePropertyFromForm: (state, { index }) => ({
...state,
properties: state.properties.filter((_, i) => i !== index),
}),
setEditingPropertyGroup: (_, { propertyGroup }) => ({
name: propertyGroup?.name || '',
description: propertyGroup?.description || '',
properties: propertyGroup?.properties || [],
}),
setPropertyGroupModalOpen: (state, { open }) =>
open ? state : { name: '', description: '', properties: [] },
},
],
}),
selectors({
filteredPropertyGroups: [
(s) => [s.propertyGroups, s.searchTerm],
(propertyGroups: SchemaPropertyGroup[], searchTerm: string): SchemaPropertyGroup[] => {
if (!searchTerm) {
return propertyGroups
}
const lowerSearchTerm = searchTerm.toLowerCase()
return propertyGroups.filter(
(pg) =>
pg.name.toLowerCase().includes(lowerSearchTerm) ||
pg.description.toLowerCase().includes(lowerSearchTerm) ||
pg.properties.some((prop) => prop.name.toLowerCase().includes(lowerSearchTerm))
)
},
],
propertyGroupFormValidationError: [
(s) => [s.propertyGroupForm],
(form: PropertyGroupFormType): string | null => {
if (form.properties.length === 0) {
return null
}
const emptyProperties = form.properties.filter((prop) => !prop.name || !prop.name.trim())
if (emptyProperties.length > 0) {
return 'All properties must have a name'
}
const tooLongProperties = form.properties.filter(
(prop) => prop.name && prop.name.trim().length > MAX_PROPERTY_NAME_LENGTH
)
if (tooLongProperties.length > 0) {
return `Property names must be ${MAX_PROPERTY_NAME_LENGTH} characters or less`
}
return null
},
],
}),
listeners(({ actions, values }) => ({
deletePropertyGroup: async ({ id }) => {
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
await api.delete(`api/projects/${values.currentProjectId}/schema_property_groups/${id}/`)
actions.loadPropertyGroups()
lemonToast.success('Property group deleted')
} catch (error: any) {
const errorMessage = getErrorMessage(error, 'Failed to delete property group')
lemonToast.error(errorMessage)
}
},
})),
afterMount(({ actions }) => {
actions.loadPropertyGroups()
}),
])