All files / src/stores items.ts

97.41% Statements 113/116
86.3% Branches 63/73
95.23% Functions 20/21
99.07% Lines 107/108

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                                                                                        7x   7x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x         250x 250x                 22x 2x   22x 2x   22x 10x     22x     18x 18x     22x   22x 22x 22x 22x 22x 2x   22x 4x   22x 3x   22x 13x     22x     22x 2x     20x 16x   4x     20x 22x 22x       22x   22x   22x 20x           3x                 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       1x 1x 1x         2x 3x 2x 2x             2x         2x     2x   2x                           5x       5x     5x 5x       5x       1x     1x       1x     1x 1x 1x   1x       3x 2x       2x       2x 2x 1x 1x   2x 1x 1x         2x 2x 1x 1x   2x 1x 1x             8x 8x 3x   8x 2x       250x                                                          
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'
import { CREATED_AT_SORT_FIELD_ID } from '@/utils/constants'
 
export interface Item {
  entityId: string
  id: string
  flowId: string
  createdBy: string
  createdAt: string
  updatedAt: string
  likeCount?: number
  likedByCurrentUser?: boolean
  // Only present when the item's entity accepts comments
  commentCount?: number
  [key: string]: any
}
 
// A single field filter — AND across array entries, OR within one entry's
// `values`. Mirrors the backend's `filters` query param shape (see
// flows-api items/filtering.js). `op` defaults to `'eq'` (exact match,
// automatic for number/date/boolean/select/entity_ref/user, or a `unique`
// text/email field); `'contains'` is substring search on text/textarea/email
// fields (each value must be a single word of at least 3 characters).
export interface ItemFilter {
  fieldId: string
  op?: 'eq' | 'contains'
  values: Array<string | number | boolean>
}
 
// Single-field sort. For a real entity field, the backend only honors it (see
// `sorted` in the response) when the candidate set (unfiltered entity, or
// matched/filtered count otherwise) is within LARGE_ENTITY_ITEM_THRESHOLD.
// CREATED_AT_SORT_FIELD_ID is a reserved pseudo-field id that's always
// honored regardless of size (index-backed, not an in-memory fetch-all).
export interface ItemSort {
  fieldId: string
  direction: 'asc' | 'desc'
}
 
// Default: newest-first by creation date — always available, so this is a
// safe default for any entity regardless of size, unlike a text field which
// would need the threshold check before ever being picked automatically.
export const DEFAULT_ITEM_SORT: ItemSort = { fieldId: CREATED_AT_SORT_FIELD_ID, direction: 'desc' }
 
export const useItemsStore = defineStore('items', () => {
  const items = ref<Item[]>([])
  const currentItem = ref<Item | null>(null)
  const nextToken = ref<string | null>(null)
  const hasMore = ref<boolean>(true)
  const loading = ref<boolean>(false)
  const error = ref<string | null>(null)
  const total = ref(0)
  const filteredTotal = ref(0)
  const searchQuery = ref('')
  const filters = ref<ItemFilter[]>([])
  const sort = ref<ItemSort | null>(DEFAULT_ITEM_SORT)
  // Reflects the last response's `sorted` flag — false whenever the
  // requested `sort` was ignored server-side (candidate set over threshold).
  // Defensive UI signal only: the frontend already gates the sort controls
  // on the same threshold before ever sending `sort`.
  const sorted = ref(false)
  let latestFetchRequestId = 0
 
  async function fetchItems(
    entityId: string,
    reset = true,
    search?: string,
    newFilters?: ItemFilter[],
    newSort?: ItemSort | null
  ) {
    if (search !== undefined) {
      searchQuery.value = search
    }
    if (newFilters !== undefined) {
      filters.value = newFilters
    }
    if (newSort !== undefined) {
      sort.value = newSort
    }
 
    if (reset) {
      // Do NOT clear items.value eagerly — it causes a visible flash.
      // Items are replaced atomically when the response arrives below.
      nextToken.value = null
      hasMore.value = true
    }
 
    Iif ((!reset && loading.value) || (!reset && !hasMore.value)) return
 
    const requestId = ++latestFetchRequestId
    loading.value = true
    try {
      const params: any = { limit: 30 }
      if (searchQuery.value.trim()) {
        params.q = searchQuery.value.trim()
      }
      if (nextToken.value) {
        params.nextToken = nextToken.value
      }
      if (filters.value.length > 0) {
        params.filters = JSON.stringify(filters.value)
      }
      if (sort.value) {
        params.sort = JSON.stringify(sort.value)
      }
 
      const response = await api.get(`/v1/entities/${entityId}/items`, { params })
 
      // A newer request has started: ignore stale response.
      if (requestId !== latestFetchRequestId) {
        return
      }
 
      if (reset) {
        items.value = response.data.items || response.data
      } else {
        items.value = [...items.value, ...(response.data.items || response.data)]
      }
 
      nextToken.value = response.data.nextToken || null
      hasMore.value = response.data.hasMore ?? false
      filteredTotal.value =
        typeof response.data.filteredTotal === 'number'
          ? response.data.filteredTotal
          : items.value.length
      total.value =
        typeof response.data.total === 'number' ? response.data.total : filteredTotal.value
      sorted.value = response.data.sorted === true
    } finally {
      if (requestId === latestFetchRequestId) {
        loading.value = false
      }
    }
  }
 
  async function loadMore(entityId: string) {
    await fetchItems(entityId, false)
  }
 
  /**
   * Drops the items listed for the previous active flow (see entities.ts
   * reset). Search, filters and sort are view settings, not flow data, so
   * they are left as they are.
   */
  function reset() {
    latestFetchRequestId++
    items.value = []
    currentItem.value = null
    nextToken.value = null
    hasMore.value = true
    loading.value = false
    error.value = null
    total.value = 0
    filteredTotal.value = 0
    sorted.value = false
  }
 
  async function fetchItem(entityId: string, itemId: string) {
    const response = await api.get(`/v1/entities/${entityId}/items/${itemId}`)
    currentItem.value = response.data
    return response.data
  }
 
  /** Reloads one item of the list, e.g. after it changed behind the user's back */
  async function refreshItem(entityId: string, itemId: string) {
    const response = await api.get(`/v1/entities/${entityId}/items/${itemId}`)
    const index = items.value.findIndex((i) => i.id === itemId)
    if (index !== -1) items.value[index] = response.data
    return response.data
  }
 
  async function createItem(entityId: string, data: any, id?: string) {
    // `id` is generated client-side up front so image fields uploaded during
    // creation can be keyed by the real item id from the start, instead of a
    // placeholder that would never get reconciled afterward.
    const response = await api.post(`/v1/entities/${entityId}/items`, {
      entityId,
      data,
      ...(id && { id })
    })
    const newItem = response.data
 
    // Add new item to the beginning of the list
    items.value.unshift(newItem)
 
    return newItem
  }
 
  /**
   * Saves an item. With `expectedUpdatedAt` (the `updatedAt` it was loaded
   * with), the API refuses with 409 `ITEM_MODIFIED` an item that changed since
   * — another user, an automatic transition — instead of overwriting it.
   */
  async function updateItem(
    entityId: string,
    itemId: string,
    data: any,
    expectedUpdatedAt?: string | null
  ) {
    const response = await api.put(`/v1/entities/${entityId}/items/${itemId}`, {
      data,
      ...(expectedUpdatedAt !== undefined ? { expectedUpdatedAt } : {})
    })
    const updatedItem = response.data
 
    // Update item locally instead of refetching all
    const index = items.value.findIndex((i) => i.id === itemId)
    Iif (index !== -1) {
      items.value[index] = updatedItem
    }
 
    return updatedItem
  }
 
  async function deleteItem(entityId: string, itemId: string) {
    await api.delete(`/v1/entities/${entityId}/items/${itemId}`)
 
    // Remove item locally instead of refetching all
    items.value = items.value.filter((i) => i.id !== itemId)
  }
 
  async function clearAllItems(entityId: string) {
    const response = await api.delete(`/v1/entities/${entityId}/items`)
 
    // Clear all items locally
    items.value = []
    nextToken.value = null
    hasMore.value = false
 
    return response
  }
 
  async function likeItem(entityId: string, itemId: string) {
    const response = await api.post(`/v1/entities/${entityId}/items/${itemId}/like`)
    return response.data
  }
 
  async function unlikeItem(entityId: string, itemId: string) {
    await api.delete(`/v1/entities/${entityId}/items/${itemId}/like`)
  }
 
  function markAsLiked(itemId: string) {
    const item = items.value.find((i) => i.id === itemId)
    if (item) {
      item.likedByCurrentUser = true
      item.likeCount = (item.likeCount ?? 0) + 1
    }
    if (currentItem.value?.id === itemId) {
      currentItem.value.likedByCurrentUser = true
      currentItem.value.likeCount = (currentItem.value.likeCount ?? 0) + 1
    }
  }
 
  function markAsUnliked(itemId: string) {
    const item = items.value.find((i) => i.id === itemId)
    if (item) {
      item.likedByCurrentUser = false
      item.likeCount = Math.max(0, (item.likeCount ?? 0) - 1)
    }
    if (currentItem.value?.id === itemId) {
      currentItem.value.likedByCurrentUser = false
      currentItem.value.likeCount = Math.max(0, (currentItem.value.likeCount ?? 0) - 1)
    }
  }
 
  // Applies a change to an item's comment counter (+1 posted, -1 deleted)
  // without refetching the list, like markAsLiked does for likes.
  function adjustCommentCount(itemId: string, delta: number) {
    const item = items.value.find((i) => i.id === itemId)
    if (item && typeof item.commentCount === 'number') {
      item.commentCount = Math.max(0, item.commentCount + delta)
    }
    if (currentItem.value?.id === itemId && typeof currentItem.value.commentCount === 'number') {
      currentItem.value.commentCount = Math.max(0, currentItem.value.commentCount + delta)
    }
  }
 
  return {
    items,
    currentItem,
    nextToken,
    hasMore,
    loading,
    error,
    total,
    filteredTotal,
    searchQuery,
    filters,
    sort,
    sorted,
    fetchItems,
    loadMore,
    reset,
    fetchItem,
    createItem,
    updateItem,
    refreshItem,
    deleteItem,
    clearAllItems,
    likeItem,
    unlikeItem,
    markAsLiked,
    markAsUnliked,
    adjustCommentCount
  }
})