All files / src/stores entities.ts

81.91% Statements 77/94
83.33% Branches 40/48
61.53% Functions 8/13
83.51% Lines 76/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299                                                                                                                                                                            8x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x     16x 2x     16x     12x 12x     16x 2x     14x 14x 14x 14x 14x 14x 2x   14x 2x     14x 11x     11x 1x       10x   3x 3x       3x 3x 3x     7x 5x   2x   7x 7x 7x   7x     3x     3x 3x 3x 3x 3x   3x   14x 13x           3x         3x 1x               1x 1x     2x 2x   2x 2x                               3x 3x     3x   3x                                                     4x 4x     4x 4x         4x       4x       1x     1x     1x         189x                                          
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'
import {
  ENTITY_SCHEMA,
  type FormDefinition,
  type WorkflowDefinition
} from '@/schemas/entity-schema'
 
export interface EntityField {
  fieldId?: string // Stable internal identifier for the field (auto-generated if not provided)
  name: string | Record<string, string>
  type?:
    | 'text'
    | 'number'
    | 'email'
    | 'password'
    | 'select'
    | 'date'
    | 'boolean'
    | 'textarea'
    | 'image'
    | 'image_set'
    | 'workflow'
    | 'user'
    | 'entity_ref'
  length?: number
  mandatory?: boolean
  unique?: boolean
  disabled?: boolean
  options?: string[] | { value: string; label: string }[]
  placeholder?: string
  defaultValue?: any
  maxImages?: number // For image_set: maximum number of images
  minWidth?: number // For image/image_set: minimum width in pixels
  maxWidth?: number // For image/image_set: maximum width in pixels
  minHeight?: number // For image/image_set: minimum height in pixels
  maxHeight?: number // For image/image_set: maximum height in pixels
  aspectRatio?: string // For image/image_set: expected ratio (e.g. 1:1, 4:3, 16:9)
  resizeMaxWidth?: number // For image/image_set: auto-resize down to this max width
  resizeMaxHeight?: number // For image/image_set: auto-resize down to this max height
  cropEnabled?: boolean // For image/image_set: enable crop step before upload
  workflowDefinition?: WorkflowDefinition // For workflow type fields
  reference?: {
    kind: 'user' | 'entity'
    entityId?: string
    displayFormId?: string
    allowLinked?: boolean
    allowPublic?: boolean
    multiple?: boolean
    minValues?: number
    maxValues?: number
  }
}
 
export interface Entity {
  id: string
  flowId: string
  visibility: 'flow-members' | 'public'
  isPublic: string // Deprecated, kept for backward compatibility
  name: string | Record<string, string>
  description?: string | Record<string, string>
  fields: EntityField[]
  defaultLanguage?: string
  enabledLanguages?: string[]
  picture?: string
  icon?: string
  publicPermissions?: string[]
  forms?: import('@/schemas/entity-schema').FormDefinition[]
  forkedFromEntityId?: string
  forkedFromFlowId?: string
  forkedAt?: string
  forkedBy?: string
  forkedByCurrentFlow?: boolean
  linked?: boolean
  linkedByCurrentFlow?: boolean
  sourceFlowId?: string
  linkedAt?: string
  archivedAt?: string | null
  sourceFlowName?: string
  sourceSnapshotVersion?: string
  createdBy: string
  createdAt: string
  updatedAt: string
}
 
export const useEntitiesStore = defineStore('entities', () => {
  const entities = ref<Entity[]>([])
  const currentEntity = ref<Entity | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)
  const nextToken = ref<string | null>(null)
  const hasMore = ref(true)
  const total = ref(0)
  const filteredTotal = ref(0)
  const searchQuery = ref('')
  let latestFetchRequestId = 0
 
  async function fetchEntities(reset = true, search?: string) {
    if (search !== undefined) {
      searchQuery.value = search
    }
 
    if (reset) {
      // Do NOT clear entities.value eagerly — it causes a visible flash.
      // Entities are replaced atomically when the response arrives below.
      nextToken.value = null
      hasMore.value = true
    }
 
    if ((!reset && loading.value) || (!reset && !hasMore.value)) {
      return
    }
 
    const requestId = ++latestFetchRequestId
    loading.value = true
    error.value = null
    try {
      const params: any = { limit: 30 }
      if (searchQuery.value.trim()) {
        params.search = searchQuery.value.trim()
      }
      if (!reset && nextToken.value) {
        params.nextToken = nextToken.value
      }
 
      const response = await api.get('/v1/entities', { params })
      const data = response.data
 
      // A newer request has started: ignore stale response.
      if (requestId !== latestFetchRequestId) {
        return
      }
 
      // Handle both old format (array) and new format (object with items)
      if (Array.isArray(data)) {
        // Old format - no pagination
        if (reset) {
          entities.value = data
        } else E{
          entities.value = [...entities.value, ...data]
        }
        hasMore.value = false
        filteredTotal.value = data.length
        total.value = data.length
      } else {
        // New format with pagination
        if (reset) {
          entities.value = data.items
        } else {
          entities.value = [...entities.value, ...data.items]
        }
        nextToken.value = data.nextToken
        hasMore.value = data.hasMore
        filteredTotal.value =
          typeof data.filteredTotal === 'number' ? data.filteredTotal : entities.value.length
        total.value = typeof data.total === 'number' ? data.total : filteredTotal.value
      }
    } catch (err: any) {
      Iif (requestId !== latestFetchRequestId) {
        return
      }
      error.value = err.response?.data?.error || err.message || 'Failed to fetch entities'
      Eif (reset) {
        entities.value = []
        filteredTotal.value = 0
        total.value = 0
      }
      throw err
    } finally {
      if (requestId === latestFetchRequestId) {
        loading.value = false
      }
    }
  }
 
  async function loadMore() {
    await fetchEntities(false)
  }
 
  async function fetchEntity(id: string) {
    // Check if requesting system entity schema
    if (id === 'entity') {
      const systemEntity = {
        ...ENTITY_SCHEMA,
        flowId: 'SYSTEM',
        isPublic: 'false', // Backward compatibility
        createdBy: 'SYSTEM',
        createdAt: '2026-01-01T00:00:00Z',
        updatedAt: '2026-01-01T00:00:00Z'
      } as any as Entity // Cast to Entity type (system schema has extended field types)
      currentEntity.value = systemEntity
      return systemEntity
    }
 
    const response = await api.get(`/v1/entities/${id}`)
    const entity = response.data
 
    currentEntity.value = entity
    return entity
  }
 
  async function createEntity(data: {
    name: string | Record<string, string>
    fields: any[]
    visibility?: 'flow-members' | 'public'
    isPublic?: boolean // Deprecated, kept for backward compatibility
    description?: string | Record<string, string>
    forms?: FormDefinition[]
    picture?: string
    icon?: string
    publicPermissions?: string[]
    defaultLanguage?: string
    enabledLanguages?: string[]
  }) {
    const response = await api.post('/v1/entities', data)
    const newEntity = response.data
 
    // Add new entity to the beginning of the list
    entities.value.unshift(newEntity)
 
    return newEntity
  }
 
  async function forkEntity(
    entityId: string,
    data?: { name?: string | Record<string, string>; visibility?: 'flow-members' | 'public' }
  ) {
    const response = await api.post(`/v1/entities/${entityId}/fork`, data ?? {})
    const forkedEntity = response.data
 
    entities.value.unshift(forkedEntity)
    return forkedEntity
  }
 
  async function linkEntity(entityId: string) {
    const response = await api.post(`/v1/entities/${entityId}/link`)
    const linkedEntity = response.data
    entities.value.unshift(linkedEntity)
    return linkedEntity
  }
 
  async function unlinkEntity(entityId: string) {
    await api.delete(`/v1/entities/${entityId}/link`)
    entities.value = entities.value.filter((e) => e.id !== entityId)
  }
 
  async function updateEntity(id: string, data: Partial<Entity>) {
    const response = await api.put(`/v1/entities/${id}`, data)
    const updatedEntity = response.data
 
    // Replace the entity in the array
    const index = entities.value.findIndex((e) => e.id === id)
    Iif (index !== -1) {
      entities.value[index] = updatedEntity
    }
 
    // Update currentEntity if it's the one being updated
    Iif (currentEntity.value?.id === id) {
      currentEntity.value = updatedEntity
    }
 
    return updatedEntity
  }
 
  async function deleteEntity(id: string) {
    await api.delete(`/v1/entities/${id}`)
 
    // Remove entity from local list
    entities.value = entities.value.filter((e) => e.id !== id)
 
    // Clear currentEntity if it's the one being deleted
    Iif (currentEntity.value?.id === id) {
      currentEntity.value = null
    }
  }
 
  return {
    entities,
    currentEntity,
    loading,
    error,
    nextToken,
    hasMore,
    total,
    filteredTotal,
    searchQuery,
    fetchEntities,
    loadMore,
    fetchEntity,
    createEntity,
    forkEntity,
    linkEntity,
    unlinkEntity,
    updateEntity,
    deleteEntity
  }
})