All files / src/components EntityItemCard.vue

85.52% Statements 260/304
75.6% Branches 217/287
91.11% Functions 41/45
91.28% Lines 241/264

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 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832  56x             1x               1x           2x 46x 48x           2x       2x                                                                                                           22x         2x     2x       3x         4x                                   2x                                     43x 43x                                                             86x 86x     43x       43x           43x 43x 43x 43x 43x 43x                     4x 4x 4x           5x 10x 5x 3x 3x 3x             4x 4x           4x 1x   3x           5x 6x 6x 6x   4x 6x 6x   1x 1x               8x 6x 6x 6x 6x       8x 8x 8x 8x 8x       6x                   28x 28x   10x           10x       5x 5x 5x           5x             5x       17x   17x 17x 20x   17x   17x 3x 3x 3x     17x       17x 17x 17x 17x 17x 17x 17x 17x                 17x 6x       11x 17x 17x   17x 5x     6x 6x 6x               6x 6x 6x 6x 6x 6x 6x   6x 6x 5x 5x       6x 6x 3x 3x 3x                       6x 6x 1x   6x 1x 1x 1x       6x   6x 2x   2x 2x               2x   2x 2x 2x       2x 2x 2x             6x 4x 4x     2x   4x 3x 3x 3x               5x 1x 1x       5x       5x 5x 5x       43x                                                   55x         4x 3x 3x 3x 3x 1x             2x 2x 2x   1x 2x     43x           45x   34x 33x           2x 2x 5x 5x       2x       2x 2x   2x 4x 4x   4x 4x 4x 4x   4x         4x 4x 4x           2x 2x 2x 2x 2x 4x 2x 2x       2x             2x 2x                                   18x   22x 18x   18x 18x 2x     17x 18x   18x 18x 2x   18x         18x 20x 20x 20x 20x   20x 18x               2x       2x   2x 4x 4x   4x 4x   4x 4x 4x 4x   4x         4x 4x 4x         2x 2x 2x 3x 1x 4x 3x 3x       2x       2x           3x 3x   3x 3x                                                                                                                                                                                                                                                
<template>
  <div class="card entity-item-card h-100 position-relative">
    <!-- Action buttons (top-right) -->
    <div v-if="props.canEdit || props.canDelete" class="card-actions">
      <button
        v-if="props.canEdit"
        class="btn btn-sm btn-secondary action-icon"
        title="Edit"
        @click.stop="$emit('edit', item)"
      >
        <font-awesome-icon icon="fa-solid fa-pen" />
      </button>
      <button
        v-if="props.canDelete"
        class="btn btn-sm btn-danger action-icon"
        title="Delete"
        @click.stop="$emit('delete', item.id || '')"
      >
        <font-awesome-icon icon="fa-solid fa-trash" />
      </button>
    </div>
 
    <div class="card-body">
      <div v-for="row in visibleFieldRows" :key="row.key" class="item-fields-row">
        <div
          v-for="cell in row.cells"
          :key="cell.key"
          class="item-field-cell"
          :style="{ gridColumn: `${cell.start} / span ${cell.span}` }"
        >
          <div class="text-muted small mb-1">
            {{ getTranslation(cell.field.name) }}
            <span v-if="cell.field.mandatory" class="text-danger">*</span>
          </div>
          <div class="field-value">
            <template v-if="!cell.field.type || cell.field.type === 'text'">
              {{ getTranslation(item[getFieldKey(cell.field)] ?? {}) }}
            </template>
            <template v-else-if="cell.field.type === 'textarea'">
              <div class="text-truncate-3">
                {{ getTranslation(item[getFieldKey(cell.field)] ?? {}) }}
              </div>
            </template>
            <template v-else-if="cell.field.type === 'boolean'">
              <span
                class="badge"
                :class="item[getFieldKey(cell.field)] ? 'bg-success' : 'bg-secondary'"
              >
                {{ item[getFieldKey(cell.field)] ? 'Yes' : 'No' }}
              </span>
            </template>
            <template v-else-if="cell.field.type === 'image'">
              <ImageField
                v-if="item[getFieldKey(cell.field)]"
                :model-value="item[getFieldKey(cell.field)]"
                :field="cell.field"
                :is-editing="false"
                :item-id="item.id"
                no-thumbnail
                :clickable="false"
                no-wrapper
              />
              <span v-else class="text-muted">{{ t('item.noImage') }}</span>
            </template>
            <template v-else-if="cell.field.type === 'image_set'">
              <ImageCarousel
                v-if="item[getFieldKey(cell.field)]?.length"
                :images="item[getFieldKey(cell.field)]"
                :item-id="item.id"
              />
              <span v-else class="text-muted">{{ t('item.noImages') }}</span>
            </template>
            <template v-else-if="cell.field.type === 'date'">
              <template v-if="item[getFieldKey(cell.field)]">
                {{ formatDate(item[getFieldKey(cell.field)]) }}
              </template>
              <span v-else class="text-muted">-</span>
            </template>
            <template v-else-if="cell.field.type === 'workflow'">
              <span class="badge bg-primary">
                {{ getWorkflowStateLabel(cell.field, item[getFieldKey(cell.field)]) }}
              </span>
            </template>
            <template v-else-if="cell.field.type === 'user'">
              {{ getUserReferenceLabel(cell.field, item[getFieldKey(cell.field)]) }}
            </template>
            <template v-else-if="cell.field.type === 'entity_ref'">
              <div class="entity-ref-list">
                <div
                  v-for="entry in getEntityRefEntries(cell.field, item[getFieldKey(cell.field)])"
                  :key="entry.id"
                  class="entity-ref-card"
                >
                  <div class="entity-ref-card-title">
                    <template v-if="entry.loading">
                      <span class="spinner-border spinner-border-sm text-secondary" role="status">
                        <span class="visually-hidden">{{ t('common.loading') }}</span>
                      </span>
                    </template>
                  </div>
                  <div
                    v-for="(entityRefRow, rowIndex) in entry.rows"
                    :key="rowIndex"
                    class="entity-ref-card-row"
                  >
                    <div
                      v-for="entityRefCell in entityRefRow.cells"
                      :key="entityRefCell.key"
                      class="entity-ref-card-cell"
                      :style="{ gridColumn: `${entityRefCell.start} / span ${entityRefCell.span}` }"
                    >
                      {{ entityRefCell.text }}
                    </div>
                  </div>
                </div>
              </div>
            </template>
            <template v-else>
              {{ item[getFieldKey(cell.field)] ?? '-' }}
            </template>
          </div>
        </div>
      </div>
      <div class="text-muted small mt-3 mb-2">
        {{ t('entity.created') }}:
        {{ item.createdAt ? new Date(item.createdAt).toLocaleDateString() : '' }}
      </div>
    </div>
  </div>
</template>
 
<script setup lang="ts">
// @implements UC-WORKFLOW-004.1
import type { EntityField } from '@/stores/entities'
import type { WorkflowDefinition } from '@/schemas/entity-schema'
import ImageField from '@/components/ImageField.vue'
import ImageCarousel from '@/components/ImageCarousel.vue'
import { useUILanguage } from '@/composables/useUILanguage'
import { useFlowMemberReference } from '@/composables/useFlowMemberReference'
import api from '@/services/api'
import { computed, ref } from 'vue'
 
const { t } = useUILanguage()
const { memberLabelById } = useFlowMemberReference()
 
interface EntityReferenceContext {
  metaLoaded: boolean
  itemById: Map<string, Record<string, any>>
  labelById: Map<string, string>
  fieldById: Map<string, EntityField>
  formById: Map<
    string,
    {
      id: string
      purpose?: 'default' | 'short'
      fields: Array<{
        fieldId: string
        order: number
        x?: number
        y?: number
        w?: number
        h?: number
      }>
    }
  >
}
 
interface CachedEntityReferenceContext {
  context: EntityReferenceContext
  expiresAt: number
  lastAccessAt: number
}
 
function readPositiveIntegerEnv(name: string, fallback: number): number {
  const raw = Number(import.meta.env[name])
  return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : fallback
}
 
const ENTITY_REFERENCE_CACHE_TTL_MS = readPositiveIntegerEnv(
  'VITE_ENTITY_REFERENCE_CACHE_TTL_MS',
  5 * 60 * 1000
)
const ENTITY_REFERENCE_CACHE_MAX_ENTITIES = readPositiveIntegerEnv(
  'VITE_ENTITY_REFERENCE_CACHE_MAX_ENTITIES',
  30
)
 
// Lazy entity item cache for entity_ref display
const entityReferenceCache = ref<Map<string, CachedEntityReferenceContext>>(new Map())
const entityReferenceLoading = ref<Set<string>>(new Set())
const scheduledEntityReferenceLoads = new Set<string>()
const pendingEntityReferenceIds = new Map<string, Set<string>>()
const pendingEntityReferenceFormIds = new Map<string, Set<string>>()
const ignoredItemLabelKeys = new Set([
  'id',
  'entityId',
  'flowId',
  'createdAt',
  'updatedAt',
  'createdBy',
  'updatedBy'
])
 
function getObjectText(value: Record<string, unknown> | null | undefined): string {
  Iif (!value) return ''
  for (const candidate of Object.values(value)) {
    Eif (candidate) return String(candidate)
  }
  return ''
}
 
function getItemLabel(item: Record<string, any>): string {
  for (const [key, val] of Object.entries(item)) {
    if (ignoredItemLabelKeys.has(key)) continue
    if (typeof val === 'string' && val && val !== item.id) return val
    Eif (val && typeof val === 'object' && !Array.isArray(val)) {
      const text = getObjectText(val as Record<string, unknown>)
      Eif (text) return text
    }
  }
  return item.id
}
 
function formatItemFieldValue(value: unknown): string {
  Iif (!value) return ''
  Iif (Array.isArray(value)) {
    return value
      .map((entry) => String(entry))
      .filter(Boolean)
      .join(', ')
  }
  if (typeof value === 'object') {
    return getObjectText(value as Record<string, unknown>)
  }
  return String(value)
}
 
function sortFormFieldsByPosition(
  fields: Array<{ fieldId: string; order: number; x?: number; y?: number; w?: number; h?: number }>
): Array<{ fieldId: string; order: number; x?: number; y?: number; w?: number; h?: number }> {
  return [...fields].sort((a, b) => {
    const aY = a.y ?? Number.MAX_SAFE_INTEGER
    const bY = b.y ?? Number.MAX_SAFE_INTEGER
    if (aY !== bY) return aY - bY
 
    const aX = a.x ?? Number.MAX_SAFE_INTEGER
    const bX = b.x ?? Number.MAX_SAFE_INTEGER
    if (aX !== bX) return aX - bX
 
    Eif ((a.order ?? 0) !== (b.order ?? 0)) {
      return (a.order ?? 0) - (b.order ?? 0)
    }
 
    return a.fieldId.localeCompare(b.fieldId)
  })
}
 
function toGridSpan(width: number | undefined): number {
  if (!width || !Number.isFinite(width)) return 12
  const normalized = Math.floor(width)
  Iif (normalized < 1) return 1
  Iif (normalized > 12) return 12
  return normalized
}
 
function toGridStart(column: number | undefined): number {
  Iif (column === undefined || !Number.isFinite(column)) return 1
  const normalized = Math.floor(column) + 1
  Iif (normalized < 1) return 1
  Iif (normalized > 12) return 12
  return normalized
}
 
function createEmptyEntityReferenceContext(): EntityReferenceContext {
  return {
    metaLoaded: false,
    itemById: new Map(),
    labelById: new Map(),
    fieldById: new Map(),
    formById: new Map()
  }
}
 
function getCachedEntityReferenceContext(entityId: string): EntityReferenceContext | undefined {
  const cached = entityReferenceCache.value.get(entityId)
  if (!cached) return undefined
 
  Iif (cached.expiresAt <= Date.now()) {
    const next = new Map(entityReferenceCache.value)
    next.delete(entityId)
    entityReferenceCache.value = next
    return undefined
  }
  return cached.context
}
 
function storeEntityReferenceContext(entityId: string, context: EntityReferenceContext) {
  const now = Date.now()
  const next = new Map(entityReferenceCache.value)
  next.set(entityId, {
    context,
    expiresAt: now + ENTITY_REFERENCE_CACHE_TTL_MS,
    lastAccessAt: now
  })
 
  Iif (next.size > ENTITY_REFERENCE_CACHE_MAX_ENTITIES) {
    const oldestEntry = [...next.entries()].sort((a, b) => a[1].lastAccessAt - b[1].lastAccessAt)[0]
    if (oldestEntry) {
      next.delete(oldestEntry[0])
    }
  }
 
  entityReferenceCache.value = next
}
 
function scheduleEntityReferenceLoad(entityId: string, ids: string[], formId?: string) {
  Iif (!entityId || ids.length === 0) return
 
  const pending = pendingEntityReferenceIds.get(entityId) ?? new Set<string>()
  for (const id of ids) {
    pending.add(id)
  }
  pendingEntityReferenceIds.set(entityId, pending)
 
  if (formId) {
    const pendingForms = pendingEntityReferenceFormIds.get(entityId) ?? new Set<string>()
    pendingForms.add(formId)
    pendingEntityReferenceFormIds.set(entityId, pendingForms)
  }
 
  Iif (scheduledEntityReferenceLoads.has(entityId)) {
    return
  }
 
  scheduledEntityReferenceLoads.add(entityId)
  queueMicrotask(async () => {
    scheduledEntityReferenceLoads.delete(entityId)
    const requested = [...(pendingEntityReferenceIds.get(entityId) ?? new Set<string>())]
    const requestedFormIds = [...(pendingEntityReferenceFormIds.get(entityId) ?? new Set<string>())]
    pendingEntityReferenceIds.delete(entityId)
    pendingEntityReferenceFormIds.delete(entityId)
    await loadEntityReferenceContext(entityId, requested, requestedFormIds)
  })
}
 
async function loadEntityReferenceContext(
  entityId: string,
  requestedIds: string[],
  requestedFormIds: string[]
) {
  if (!entityId || entityReferenceLoading.value.has(entityId)) {
    return
  }
 
  const currentContext =
    getCachedEntityReferenceContext(entityId) ?? createEmptyEntityReferenceContext()
  const missingIds = [...new Set(requestedIds)].filter((id) => !currentContext.itemById.has(id))
  const shouldLoadEntityMeta = !currentContext.metaLoaded
 
  if (!shouldLoadEntityMeta && missingIds.length === 0) {
    return
  }
 
  entityReferenceLoading.value = new Set([...entityReferenceLoading.value, entityId])
  try {
    const context: EntityReferenceContext = {
      metaLoaded: currentContext.metaLoaded,
      itemById: new Map(currentContext.itemById),
      labelById: new Map(currentContext.labelById),
      fieldById: new Map(currentContext.fieldById),
      formById: new Map(currentContext.formById)
    }
 
    Eif (shouldLoadEntityMeta) {
      try {
        const entityResponse = await api.get(`/v1/entities/${entityId}`)
        const entity = entityResponse?.data
        const fields = Array.isArray(entity?.fields) ? entity.fields : []
        const forms = Array.isArray(entity?.forms) ? entity.forms : []
        context.metaLoaded = true
 
        context.fieldById = new Map()
        for (const field of fields) {
          Eif (field?.fieldId) {
            context.fieldById.set(field.fieldId, field)
          }
        }
 
        context.formById = new Map()
        for (const form of forms) {
          Iif (!form?.id || !Array.isArray(form.fields)) continue
          const sortedFields = sortFormFieldsByPosition(form.fields)
          context.formById.set(form.id, {
            id: form.id,
            purpose: form.purpose,
            fields: sortedFields
          })
        }
      } catch {
        context.metaLoaded = true
        // Keep existing context and continue with item lookup fallback.
      }
    }
 
    Eif (missingIds.length > 0) {
      const requestedExistingFormIds = requestedFormIds.filter((formId) =>
        context.formById.has(formId)
      )
      if (requestedExistingFormIds.length === 0 && context.formById.size > 0) {
        const defaultFormId = context.formById.keys().next().value
        Eif (defaultFormId) {
          requestedExistingFormIds.push(defaultFormId)
        }
      }
 
      const fallbackMissing = new Set<string>(missingIds)
 
      for (const formId of requestedExistingFormIds) {
        Iif (fallbackMissing.size === 0) break
 
        try {
          const lookupByFormResponse = await api.post(
            `/v1/entities/${entityId}/items/lookup-form`,
            {
              ids: [...fallbackMissing],
              formId
            }
          )
          const items: Array<{ id: string; values?: Record<string, unknown> }> =
            lookupByFormResponse.data?.items ?? []
 
          for (const item of items) {
            const existing = context.itemById.get(item.id) ?? { id: item.id }
            const merged = {
              ...existing,
              ...(item.values ?? {})
            }
            context.itemById.set(item.id, merged)
            context.labelById.set(item.id, getItemLabel(merged))
            fallbackMissing.delete(item.id)
          }
        } catch {
          // Fall back to generic lookup below.
        }
      }
 
      if (fallbackMissing.size > 0) {
        try {
          const lookupResponse = await api.post(`/v1/entities/${entityId}/items/lookup`, {
            ids: [...fallbackMissing]
          })
          const items: Array<{ id: string; [key: string]: any }> = lookupResponse.data?.items ?? []
 
          for (const item of items) {
            context.itemById.set(item.id, item)
            context.labelById.set(item.id, getItemLabel(item))
            fallbackMissing.delete(item.id)
          }
        } catch {
          // Keep fallbackMissing values for placeholder caching below.
        }
      }
 
      // Cache fallback placeholders to avoid request storms until cache TTL expires.
      for (const missingId of fallbackMissing) {
        context.itemById.set(missingId, { id: missingId })
        context.labelById.set(missingId, missingId)
      }
    }
 
    storeEntityReferenceContext(entityId, context)
  } catch {
    storeEntityReferenceContext(entityId, currentContext)
  } finally {
    const next = new Set(entityReferenceLoading.value)
    next.delete(entityId)
    entityReferenceLoading.value = next
  }
}
 
const props = withDefaults(
  defineProps<{
    item: Record<string, any>
    fields: EntityField[]
    layout?: Array<{
      fieldId: string
      order: number
      x?: number
      y?: number
      w?: number
      h?: number
    }>
    getTranslation: (value: string | Record<string, string> | null | undefined) => string
    canEdit?: boolean
    canDelete?: boolean
  }>(),
  { canEdit: true, canDelete: true, layout: () => [] }
)
 
defineEmits<{
  edit: [item: Record<string, any>]
  delete: [id: string]
}>()
 
// Helper to get stable field key for data storage
function getFieldKey(field: { fieldId?: string; name: string | Record<string, string> }): string {
  return field.fieldId!
}
 
// Helper to resolve a workflow state ID to its translated label
function getWorkflowStateLabel(field: EntityField, stateId: string | null | undefined): string {
  if (!stateId) return '-'
  const def = field.workflowDefinition as WorkflowDefinition | undefined
  Iif (!def?.states) return stateId
  const state = def.states.find((s) => s.id === stateId)
  if (!state) return stateId
  return props.getTranslation(state.label as string | Record<string, string>)
}
 
function getUserReferenceLabel(
  field: EntityField,
  value: string | string[] | null | undefined
): string {
  Iif (!value) return '-'
  if (field.reference?.multiple && Array.isArray(value)) {
    return value.map((v) => memberLabelById.value.get(v) ?? v).join(', ') || '-'
  }
  const id = Array.isArray(value) ? value[0] : String(value)
  return memberLabelById.value.get(id) || id
}
 
const visibleFieldRows = computed<
  Array<{
    key: string
    cells: Array<{ key: string; field: EntityField; span: number; start: number }>
  }>
>(() => {
  if (!props.fields.length) return []
 
  if (!props.layout?.length) {
    return props.fields.map((field, index) => ({
      key: `default-${field.fieldId ?? index}`,
      cells: [{ key: `default-cell-${field.fieldId ?? index}`, field, span: 12, start: 1 }]
    }))
  }
 
  const fieldsById = new Map<string, EntityField>()
  for (const field of props.fields) {
    Eif (field.fieldId) {
      fieldsById.set(field.fieldId, field)
    }
  }
 
  const rowsByY = new Map<
    number,
    Array<{ key: string; field: EntityField; x: number; span: number; start: number }>
  >()
  const fallbackRows: Array<{ key: string; field: EntityField; span: number; start: number }> = []
  const usedFieldIds = new Set<string>()
 
  for (const placement of sortFormFieldsByPosition(props.layout)) {
    const field = fieldsById.get(placement.fieldId)
    Iif (!field || usedFieldIds.has(placement.fieldId)) continue
 
    const key = `${placement.fieldId}-${placement.order}-${placement.x ?? 'na'}-${placement.y ?? 'na'}`
    const span = toGridSpan(placement.w)
    const start = toGridStart(placement.x)
    usedFieldIds.add(placement.fieldId)
 
    Iif (placement.y === undefined || placement.x === undefined) {
      fallbackRows.push({ key, field, span, start: 1 })
      continue
    }
 
    const row = rowsByY.get(placement.y) ?? []
    row.push({ key, field, x: placement.x, span, start })
    rowsByY.set(placement.y, row)
  }
 
  const rows: Array<{
    key: string
    cells: Array<{ key: string; field: EntityField; span: number; start: number }>
  }> = []
  const sortedY = [...rowsByY.keys()].sort((a, b) => a - b)
  for (const y of sortedY) {
    const cells = (rowsByY.get(y) ?? [])
      .sort((a, b) => a.x - b.x)
      .map((cell) => ({ key: cell.key, field: cell.field, span: cell.span, start: cell.start }))
    Eif (cells.length > 0) {
      rows.push({ key: `row-${y}`, cells })
    }
  }
 
  for (const cell of fallbackRows) {
    rows.push({
      key: `fallback-${cell.key}`,
      cells: [{ key: cell.key, field: cell.field, span: cell.span, start: cell.start }]
    })
  }
 
  Eif (rows.length > 0) {
    return rows
  }
 
  return props.fields.map((field, index) => ({
    key: `default-${field.fieldId ?? index}`,
    cells: [{ key: `default-cell-${field.fieldId ?? index}`, field, span: 12, start: 1 }]
  }))
})
 
function getEntityRefEntries(
  field: EntityField,
  value: string | string[] | null | undefined
): Array<{
  id: string
  title: string
  loading: boolean
  rows: Array<{ cells: Array<{ key: string; text: string; span: number; start: number }> }>
}> {
  Iif (!value) return []
 
  const ids = (Array.isArray(value) ? value : [value]).map((entry) => String(entry)).filter(Boolean)
  Iif (ids.length === 0) return []
 
  const entityId = field.reference?.entityId
  if (!entityId) {
    return ids.map((id) => ({ id, title: id, loading: false, rows: [] }))
  }
 
  const targetFormId = field.reference?.displayFormId
  scheduleEntityReferenceLoad(entityId, ids, targetFormId)
 
  const context = getCachedEntityReferenceContext(entityId)
  const shortDefaultForm = !targetFormId
    ? [...(context?.formById.values() ?? [])].find((f) => f.purpose === 'short')
    : undefined
  const form =
    (targetFormId ? context?.formById.get(targetFormId) : undefined) ??
    shortDefaultForm ??
    context?.formById.values().next().value
 
  return ids.map((id) => {
    const linkedItem = context?.itemById.get(id)
    const cachedTitle = context?.labelById.get(id)
    const isLoadingTitle = entityReferenceLoading.value.has(entityId) && !cachedTitle
    const title = isLoadingTitle ? '' : (cachedTitle ?? id)
 
    if (!linkedItem || !form) {
      return {
        id,
        title,
        loading: isLoadingTitle,
        rows: []
      }
    }
 
    const rowsByY = new Map<
      number,
      Array<{ key: string; text: string; x: number; span: number; start: number }>
    >()
    const fallbackRows: Array<{ key: string; text: string; span: number; start: number }> = []
 
    for (const placement of form.fields) {
      const targetField = context?.fieldById.get(placement.fieldId)
      Iif (!targetField) continue
 
      const fieldValue = formatItemFieldValue(linkedItem[placement.fieldId])
      Iif (!fieldValue) continue
 
      const text = fieldValue
      const key = `${placement.fieldId}-${placement.order}-${placement.x ?? 'na'}-${placement.y ?? 'na'}`
      const span = toGridSpan(placement.w)
      const start = toGridStart(placement.x)
 
      Iif (placement.y === undefined || placement.x === undefined) {
        fallbackRows.push({ key, text, span, start: 1 })
        continue
      }
 
      const row = rowsByY.get(placement.y) ?? []
      row.push({ key, text, x: placement.x, span, start })
      rowsByY.set(placement.y, row)
    }
 
    const rows: Array<{
      cells: Array<{ key: string; text: string; span: number; start: number }>
    }> = []
    const sortedY = [...rowsByY.keys()].sort((a, b) => a - b)
    for (const y of sortedY) {
      const row = (rowsByY.get(y) ?? [])
        .sort((a, b) => a.x - b.x)
        .map((cell) => ({ key: cell.key, text: cell.text, span: cell.span, start: cell.start }))
      Eif (row.length > 0) {
        rows.push({ cells: row })
      }
    }
 
    for (const cell of fallbackRows) {
      rows.push({ cells: [{ key: cell.key, text: cell.text, span: cell.span, start: cell.start }] })
    }
 
    return { id, title, loading: false, rows: rows.slice(0, 4) }
  })
}
 
// Helper to format date from ISO format (YYYY-MM-DD) to localized format
function formatDate(isoDate: string): string {
  Iif (!isoDate) return '-'
  try {
    // Parse ISO date (YYYY-MM-DD) and format to local date string
    const date = new Date(isoDate + 'T00:00:00')
    return date.toLocaleDateString()
  } catch {
    return isoDate
  }
}
</script>
 
<style scoped>
.entity-item-card {
  overflow: hidden;
}
 
.card-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
  display: flex;
  gap: 4px;
}
 
.action-icon {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
  border-radius: 4px;
  opacity: 0.9;
}
 
.action-icon:hover {
  opacity: 1;
}
 
.field-value {
  padding: 0.5rem;
  background-color: var(--bw-surface-muted);
  border-radius: 0.25rem;
  min-height: 38px;
  word-wrap: break-word;
  color: var(--bw-text);
}
 
.entity-ref-list {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
}
 
.entity-ref-card {
  border: 1px solid var(--bw-border);
  border-radius: 0.375rem;
  background-color: var(--bw-surface);
  padding: 0.45rem 0.55rem;
}
 
.entity-ref-card-title {
  font-weight: 600;
  font-size: 0.9rem;
  margin-bottom: 0.15rem;
}
 
.entity-ref-card-line {
  color: var(--bw-text-muted);
  font-size: 0.82rem;
}
 
.entity-ref-card-row {
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  gap: 0.4rem;
  margin-top: 0.2rem;
}
 
.entity-ref-card-cell {
  color: var(--bw-text-muted);
  font-size: 0.82rem;
  min-width: 0;
  overflow-wrap: anywhere;
}
 
.item-fields-row {
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  gap: 0.75rem;
  margin-bottom: 0.75rem;
}
 
.item-field-cell {
  min-width: 0;
}
 
.field-value:has(.image-carousel) {
  padding: 0;
  min-height: unset;
  background-color: transparent;
}
 
.field-value img {
  pointer-events: none;
}
 
.text-truncate-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
 
@media (max-width: 767px) {
  .card-actions {
    gap: 8px;
  }
 
  .action-icon {
    padding: 0.4rem 0.65rem;
    font-size: 1rem;
  }
}
</style>