All files / src/stores packs.ts

89.09% Statements 98/110
80% Branches 60/75
91.3% Functions 21/23
90.52% Lines 86/95

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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430                                                                                    2x                                                                                                                                                                                                                                                                                                                                       4x 107x 107x 107x 107x     107x 107x 107x 107x 107x 107x 107x 107x 107x       107x     11x 10x 10x 10x 11x 11x 11x 11x 11x 5x 10x 10x         9x 8x 11x 11x   1x 1x   10x         4x 3x 3x 3x 3x       2x 4x   1x   3x                                                     1x 1x       2x       2x       1x       1x       1x 1x 1x 1x         1x 1x 3x 1x 1x 1x         1x 1x 3x 1x 1x 1x       1x       1x       1x 1x       1x       1x         1x     1x       4x 5x             4x 4x 4x         3x 3x 3x 2x   1x 1x       107x                                                            
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'
import type { EntityExportBundle } from '@/utils/entityExportBundle'
import type { JobStatusResponse } from '@/composables/usePollUntilComplete'
 
// A plain string, or translations keyed by language code
export type LocalizedText = string | Record<string, string>
 
export interface PackEntityPreview {
  name: LocalizedText
  fieldCount: number
}
 
// A pack as any user sees it, at its current version: never who published it.
export interface Pack {
  id: string
  name: LocalizedText
  description: LocalizedText
  version: number
  entities: PackEntityPreview[]
  publishedAt: string
  flow: { id: string; name: string | null; slug: string | null }
  likesCount: number
  importsCount: number
  likedByMe: boolean
  // Whether the pack takes comments, and how many approved ones it has
  commentsEnabled: boolean
  commentsCount: number
  // Shown on its card (UC-STORE-014.1); absent from packs published before it existed
  picture?: string | null
}
 
// A pack the active flow installed (UC-STORE-015.1): `installedVersion` is the
// lowest version among its copies, null for an install from before it was kept
export interface InstalledPack extends Pack {
  installedVersion: number | null
  importedAt: string
}
 
/** Whether the flow's copies of an installed pack are behind its current version. */
export function hasUpdate(pack: InstalledPack): boolean {
  return pack.installedVersion !== null && pack.installedVersion < pack.version
}
 
// What a version was published from: the flow's entities chosen, the
// dependencies left out, and the entities whose items it carries
export interface PackSource {
  entityIds: string[]
  excludeEntityIds: string[]
  itemsEntityIds: string[]
}
 
export interface PackDetail extends Pack {
  bundle: EntityExportBundle
  canDelete: boolean
  // Its next version is published from the pack, by its author or the flow's owner
  canPublishVersion?: boolean
  // Sent only with canPublishVersion: what the next version starts from
  source?: PackSource
}
 
export interface PackPublication {
  version?: number
  isNewPack?: boolean
  refusal?: 'PACK_NAME_TAKEN' | 'PACK_NOT_FOUND' | 'PACK_NOT_MAINTAINED'
}
 
export interface PublishPackPayload {
  name: LocalizedText
  description?: LocalizedText
  entityIds: string[]
  excludeEntityIds?: string[]
  // The pack of the active flow a new version is for; omitted for a new pack
  packId?: string
  // A new pack only: the id the panel chose, so that its picture is uploaded
  // under it first, and that picture
  id?: string
  picture?: string
  // A new pack only: a new version keeps the pack's setting
  commentsEnabled?: boolean
  // Entities whose items the pack carries (at most 20 each), and the
  // publisher's confirmation that they may be shared
  itemsEntityIds?: string[]
  itemsConfirmed?: boolean
}
 
// The order of the Store when it is not searched: a search is never sorted
export type PackSort = 'recent' | 'likes' | 'imports'
 
export interface InstallChoice {
  tempId: string
  mode: 'create' | 'skip'
  name?: string | Record<string, string>
  // The pack's items for that entity come with it unless false
  includeItems?: boolean
}
 
/**
 * A field of the copy already named like an added field, in one language
 * (UC-ENTITY-029.1). When the version removed it, it can be renamed instead.
 */
export interface PackUpgradeNameConflict {
  language: string
  fieldId: string
  fieldName: string
  removed: boolean
  suggestedName: string
}
 
/** A field of the pack's version, as an upgrade shows it. */
export interface PackUpgradeField {
  fieldId: string
  name: LocalizedText
  type: string
  mandatory: boolean
  nameConflicts?: PackUpgradeNameConflict[]
}
 
/** What differs between a copy and the version, listed and never applied. */
export interface PackUpgradeChange {
  /**
   * `conflict`: changed by the version and by the copy; `manual`: changed by
   * the version only, but applying it would touch the copy's items or names
   */
  change: 'conflict' | 'manual' | 'retyped' | 'removed' | 'entityRemoved'
  fieldId?: string
  section?: PackUpgradeSection
  name?: LocalizedText
  properties?: string[]
  reasons?: string[]
  type?: string
  packType?: string
}
 
/** Parts of an entity compared as a whole, like a field. */
export type PackUpgradeSection = 'forms' | 'emailTemplates'
 
/** A field only the version changed since the copy took it: offered. */
export interface PackUpgradeChangedField {
  fieldId: string
  name: LocalizedText
  packName: LocalizedText
  /** The properties of its definition that differ */
  properties: string[]
}
 
/** What upgrading the active flow's copies of a pack would add (UC-STORE-013.1). */
export interface PackUpgradePreview {
  fromVersion: number | null
  toVersion: number
  copies: Array<{
    entityId: string
    name: LocalizedText
    version: number
    canUpdate: boolean
    addedFields: PackUpgradeField[]
    changedFields: PackUpgradeChangedField[]
    changedSections: PackUpgradeSection[]
    /** Installed before copies kept a baseline: every difference is listed */
    noBaseline?: boolean
    otherChanges: PackUpgradeChange[]
  }>
  newEntities: Array<{
    tempId: string
    name: LocalizedText
    fieldCount: number
    /** An entity of the flow has this name: it needs another one */
    nameTaken?: boolean
  }>
  canCreate: boolean
}
 
/** Names by field, then by language: `{ [fieldId]: { [language]: name } }`. */
export type FieldNamesByLanguage = Record<string, Record<string, string>>
 
export interface PackUpgradeChoices {
  copies: Array<{
    entityId: string
    fieldIds: string[]
    /** Other names for added fields */
    fieldNames?: FieldNamesByLanguage
    /** New names for the copy's fields the version removed */
    renames?: FieldNamesByLanguage
    /** Changed fields to take the version's definition of */
    changedFieldIds?: string[]
    sections?: PackUpgradeSection[]
  }>
  entities: Array<{ tempId: string; name?: LocalizedText }>
}
 
/** The upgrade job's result: the new entities' import results, and each copy's. */
export interface PackUpgradeResult {
  results: Array<{ tempId: string; status: string; entityId?: string; error?: string }>
  upgraded: Array<{
    entityId: string
    status: 'upgraded' | 'failed'
    addedFieldsCount: number
    changedFieldsCount?: number
    changedSections?: PackUpgradeSection[]
    droppedFieldsCount: number
    error?: string
  }>
}
 
/** The Entity Store (docs/architecture/ENTITY_STORE.md). */
export const usePacksStore = defineStore('packs', () => {
  const packs = ref<Pack[]>([])
  const nextToken = ref<string | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)
  // The text the Store is searched by ('' lists every pack, newest first), and
  // whether an extremely common text may have hidden some matches
  const search = ref('')
  const truncated = ref(false)
  const sort = ref<PackSort>('recent')
  const myPacks = ref<Pack[]>([])
  const myNextToken = ref<string | null>(null)
  const loadingMine = ref(false)
  const installed = ref<InstalledPack[]>([])
  const installedNextToken = ref<string | null>(null)
  const loadingInstalled = ref(false)
 
  // Bumped by every first-page request, so that a slow answer to an older
  // search never replaces the newer one's
  let latestRequest = 0
 
  async function fetchPacks(more = false, searchText?: string, order?: PackSort) {
    if (more && !nextToken.value) return
    if (!more && searchText !== undefined) search.value = searchText.trim()
    if (!more && order !== undefined) sort.value = order
    const request = more ? latestRequest : ++latestRequest
    loading.value = true
    error.value = null
    try {
      const params: Record<string, string> = {}
      if (search.value) params.search = search.value
      else if (sort.value !== 'recent') params.sort = sort.value
      if (more && nextToken.value) params.nextToken = nextToken.value
      const response = await api.get<{
        items: Pack[]
        nextToken: string | null
        truncated?: boolean
      }>('/v1/store', { params: Object.keys(params).length > 0 ? params : undefined })
      if (request !== latestRequest) return
      packs.value = more ? [...packs.value, ...response.data.items] : response.data.items
      nextToken.value = response.data.nextToken
      truncated.value = response.data.truncated === true
    } catch (err: any) {
      Iif (request !== latestRequest) return
      error.value = err.response?.data?.error || 'Failed to load packs'
    } finally {
      if (request === latestRequest) loading.value = false
    }
  }
 
  async function fetchMyPacks(more = false) {
    if (more && !myNextToken.value) return
    loadingMine.value = true
    error.value = null
    try {
      const response = await api.get<{ items: Pack[]; nextToken: string | null }>(
        '/v1/store/mine',
        { params: more && myNextToken.value ? { nextToken: myNextToken.value } : undefined }
      )
      myPacks.value = more ? [...myPacks.value, ...response.data.items] : response.data.items
      myNextToken.value = response.data.nextToken
    } catch (err: any) {
      error.value = err.response?.data?.error || 'Failed to load your packs'
    } finally {
      loadingMine.value = false
    }
  }
 
  // The packs the active flow installed, the most recently installed first
  async function fetchInstalled(more = false) {
    if (more && !installedNextToken.value) return
    loadingInstalled.value = true
    error.value = null
    try {
      const response = await api.get<{ items: InstalledPack[]; nextToken: string | null }>(
        '/v1/store/installed',
        {
          params:
            more && installedNextToken.value ? { nextToken: installedNextToken.value } : undefined
        }
      )
      installed.value = more ? [...installed.value, ...response.data.items] : response.data.items
      installedNextToken.value = response.data.nextToken
    } catch (err: any) {
      error.value = err.response?.data?.error || 'Failed to load the installed packs'
    } finally {
      loadingInstalled.value = false
    }
  }
 
  async function getPack(packId: string) {
    const response = await api.get<PackDetail>(`/v1/store/${packId}`)
    return response.data
  }
 
  async function checkName(name: LocalizedText, packId?: string) {
    const response = await api.post<PackPublication>('/v1/store/check', {
      name,
      ...(packId && { packId })
    })
    return response.data
  }
 
  async function publish(payload: PublishPackPayload) {
    const response = await api.post<{ id: string; version: number; isNewPack: boolean }>(
      '/v1/store',
      payload
    )
    return response.data
  }
 
  async function deletePack(packId: string) {
    await api.delete(`/v1/store/${packId}`)
    packs.value = packs.value.filter((pack) => pack.id !== packId)
    myPacks.value = myPacks.value.filter((pack) => pack.id !== packId)
    installed.value = installed.value.filter((pack) => pack.id !== packId)
  }
 
  // Turns a pack's comments on or off (its author, its flow's owner, a platform admin)
  async function setCommentsEnabled(packId: string, commentsEnabled: boolean) {
    await api.put(`/v1/store/${packId}`, { commentsEnabled })
    const update = <T extends Pack>(pack: T): T =>
      pack.id === packId ? { ...pack, commentsEnabled } : pack
    packs.value = packs.value.map(update)
    myPacks.value = myPacks.value.map(update)
    installed.value = installed.value.map(update)
  }
 
  // Sets or removes a pack's picture, an upload under the pack (UC-STORE-014.1)
  async function setPicture(packId: string, picture: string | null) {
    await api.put(`/v1/store/${packId}`, { picture })
    const update = <T extends Pack>(pack: T): T =>
      pack.id === packId ? { ...pack, picture } : pack
    packs.value = packs.value.map(update)
    myPacks.value = myPacks.value.map(update)
    installed.value = installed.value.map(update)
  }
 
  async function install(packId: string, version: number, choices: InstallChoice[]) {
    const response = await api.post<{ jobId: string }>(`/v1/store/${packId}/import`, {
      version,
      choices
    })
    return response.data
  }
 
  async function getUpgrade(packId: string) {
    const response = await api.get<PackUpgradePreview>(`/v1/store/${packId}/upgrade`)
    return response.data
  }
 
  async function upgrade(packId: string, version: number, choices: PackUpgradeChoices) {
    const response = await api.post<{ jobId: string }>(`/v1/store/${packId}/upgrade`, {
      version,
      ...choices
    })
    return response.data
  }
 
  // An upgrade runs as an import job, whose result also holds the copies'
  async function getUpgradeJob(jobId: string) {
    const response = await api.get<JobStatusResponse<PackUpgradeResult>>(
      `/v1/entities/import/jobs/${jobId}`
    )
    return response.data
  }
 
  function applyLike(packId: string, liked: boolean) {
    const update = <T extends Pack>(pack: T): T =>
      pack.id === packId
        ? {
            ...pack,
            likedByMe: liked,
            likesCount: Math.max(0, pack.likesCount + (liked ? 1 : -1))
          }
        : pack
    packs.value = packs.value.map(update)
    myPacks.value = myPacks.value.map(update)
    installed.value = installed.value.map(update)
  }
 
  // Optimistic: the button follows at once and rolls back if the request fails.
  async function toggleLike(packId: string, liked: boolean) {
    applyLike(packId, !liked)
    try {
      if (liked) await api.delete(`/v1/store/${packId}/like`)
      else await api.post(`/v1/store/${packId}/like`)
    } catch (err) {
      applyLike(packId, liked)
      throw err
    }
  }
 
  return {
    packs,
    nextToken,
    loading,
    error,
    search,
    truncated,
    sort,
    myPacks,
    myNextToken,
    loadingMine,
    installed,
    installedNextToken,
    loadingInstalled,
    fetchPacks,
    fetchMyPacks,
    fetchInstalled,
    getPack,
    checkName,
    publish,
    deletePack,
    setCommentsEnabled,
    setPicture,
    install,
    getUpgrade,
    upgrade,
    getUpgradeJob,
    toggleLike
  }
})