All files / src/components FileField.vue

86% Statements 86/100
82.22% Branches 74/90
78.94% Functions 15/19
87.09% Lines 81/93

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  23x         1x 10x               2x     10x             10x       10x                                                       10x   7x     10x 1x                                                                                             13x 13x 13x 13x                                   13x             13x   13x 13x   13x 8x         13x 5x     13x   3x               1x 1x 1x             1x       2x 1x             3x     1x               1x   2x 2x 2x 3x 3x   3x 3x       2x       2x                   2x       5x 1x     1x     4x 1x 1x     3x 3x   3x       4x 4x 4x   4x 4x 4x 4x         4x 4x         1x 1x 1x   1x   1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x           1x 1x     1x 1x                      
<template>
  <div :class="{ 'file-field': !props.noWrapper }">
    <!-- Display mode (single file) -->
    <div v-if="!isEditing && props.field.type === 'file'">
      <div v-if="singleFile" class="file-chip">
        <font-awesome-icon icon="fa-solid fa-file" class="me-2 text-muted" />
        <a href="#" @click.prevent="downloadFile(singleFile)">{{ singleFile.name }}</a>
        <span class="text-muted small ms-2">{{ formatFileSize(singleFile.size) }}</span>
      </div>
      <div v-else class="text-muted small">{{ t('common.noFile') }}</div>
    </div>
 
    <!-- Display mode (file_set) -->
    <div v-else-if="!isEditing && props.field.type === 'file_set'">
      <div v-if="fileSetValue.length > 0" class="d-flex flex-column gap-1">
        <div v-for="file in fileSetValue" :key="file.key" class="file-chip">
          <font-awesome-icon icon="fa-solid fa-file" class="me-2 text-muted" />
          <a href="#" @click.prevent="downloadFile(file)">{{ file.name }}</a>
          <span class="text-muted small ms-2">{{ formatFileSize(file.size) }}</span>
        </div>
      </div>
      <div v-else class="text-muted small">{{ t('common.noFiles') }}</div>
    </div>
 
    <!-- Edit mode (single file) -->
    <div v-else-if="isEditing && props.field.type === 'file'" class="file-edit">
      <div v-if="singleFile" class="file-chip mb-2">
        <font-awesome-icon icon="fa-solid fa-file" class="me-2 text-muted" />
        <a href="#" @click.prevent="downloadFile(singleFile)">{{ singleFile.name }}</a>
        <span class="text-muted small ms-2">{{ formatFileSize(singleFile.size) }}</span>
        <button type="button" class="btn btn-sm btn-danger ms-2" @click="removeFile">
          <font-awesome-icon icon="fa-solid fa-times" />
        </button>
      </div>
      <input
        ref="fileInput"
        type="file"
        class="d-none"
        :disabled="uploading"
        name="file"
        @change="handleFileChange"
      />
      <button
        type="button"
        class="btn btn-sm btn-secondary"
        :disabled="uploading"
        @click="triggerFileInput"
      >
        {{ t('common.chooseFile') }}
      </button>
      <div v-if="uploading" class="text-muted small mt-1">
        <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
        {{ t('common.uploading') }}
      </div>
    </div>
 
    <!-- Edit mode (file_set) -->
    <div v-else-if="isEditing && props.field.type === 'file_set'" class="file-set-edit">
      <div v-if="fileSetValue.length > 0" class="d-flex flex-column gap-1 mb-2">
        <div v-for="(file, index) in fileSetValue" :key="file.key" class="file-chip">
          <font-awesome-icon icon="fa-solid fa-file" class="me-2 text-muted" />
          <a href="#" @click.prevent="downloadFile(file)">{{ file.name }}</a>
          <span class="text-muted small ms-2">{{ formatFileSize(file.size) }}</span>
          <button type="button" class="btn btn-sm btn-danger ms-2" @click="removeFileAt(index)">
            <font-awesome-icon icon="fa-solid fa-times" />
          </button>
        </div>
      </div>
      <input
        ref="fileInput"
        type="file"
        multiple
        class="d-none"
        :disabled="uploading || atMaxFiles"
        name="files"
        @change="handleFileSetChange"
      />
      <button
        type="button"
        class="btn btn-sm btn-secondary"
        :disabled="uploading || atMaxFiles"
        @click="triggerFileInput"
      >
        {{ t('common.chooseFile') }}
      </button>
      <div v-if="atMaxFiles" class="text-muted small mt-1">
        {{ t('field.fileSetMaxReached') }}
      </div>
      <div v-if="uploading" class="text-muted small mt-1">
        <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
        {{ t('common.uploading') }}
      </div>
    </div>
  </div>
</template>
 
<script setup lang="ts">
// @implements UC-ENTITY-027.1, UC-ITEM-008.1, UC-CREDITS-004.1
import { ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useUILanguage } from '@/composables/useUILanguage'
import { resolveFileUrl } from '@/composables/useFileUrlCache'
import api from '@/services/api'
import type { EntityField, FileValue } from '@/stores/entities'
import { ensureUuid } from '@/utils/uploadIds'
import { isAllowedFileUpload, formatFileSize, MAX_FILE_SIZE_BYTES } from '@/utils/fileUploadPolicy'
import { uploadToS3 } from '@/utils/s3Upload'
import { useToastStore } from '@/stores/toast'
 
const route = useRoute()
const authStore = useAuthStore()
const toastStore = useToastStore()
const { t } = useUILanguage()
 
interface Props {
  modelValue: FileValue | FileValue[] | null | undefined
  field: EntityField
  isEditing: boolean
  itemId?: string
  entityId?: string
  noWrapper?: boolean
  flowId?: string
  /** A join form's file (UC-SPACE-020.1): uploaded to the requester's drafts */
  joinSlug?: string
}
 
interface Emits {
  (e: 'update:modelValue', value: FileValue | FileValue[] | null): void
}
 
const props = withDefaults(defineProps<Props>(), {
  itemId: undefined,
  entityId: undefined,
  noWrapper: false,
  flowId: undefined,
  joinSlug: undefined
})
const emit = defineEmits<Emits>()
 
const fileInput = ref<HTMLInputElement | null>(null)
const uploading = ref(false)
 
const singleFile = computed<FileValue | null>(() =>
  props.field.type === 'file' && props.modelValue && !Array.isArray(props.modelValue)
    ? props.modelValue
    : null
)
 
const fileSetValue = computed<FileValue[]>(() =>
  props.field.type === 'file_set' && Array.isArray(props.modelValue) ? props.modelValue : []
)
 
const atMaxFiles = computed(
  () =>
    typeof props.field.maxFiles === 'number' && fileSetValue.value.length >= props.field.maxFiles
)
 
function triggerFileInput() {
  fileInput.value?.click()
}
 
async function downloadFile(file: FileValue) {
  const url = await resolveFileUrl(file.key, file.name)
  if (url) {
    window.open(url, '_blank', 'noopener')
  } else E{
    toastStore.error(t('field.fileDownloadError'))
  }
}
 
function removeFile() {
  emit('update:modelValue', null)
}
 
function removeFileAt(index: number) {
  const next = fileSetValue.value.filter((_, i) => i !== index)
  emit('update:modelValue', next.length ? next : null)
}
 
async function getPresignedUrl(
  fileName: string,
  fileType: string
): Promise<{ uploadUrl: string; uploadFields: Record<string, string>; key: string }> {
  if (props.joinSlug) {
    // The requester is not a member yet: the file goes to their drafts, for
    // this field of the space's join form
    const response = await api.post('/v1/upload/presigned-url', {
      fileName,
      fileType,
      fieldName: props.field.fieldId,
      scope: 'membership-request',
      slug: props.joinSlug,
      uploadKind: 'file'
    })
    return response.data
  }
  const routeEntityId = route.params.entityId as string | undefined
  const routeItemId = route.params.itemId as string | undefined
  const entityId = ensureUuid(props.entityId || routeEntityId)
  const itemId = ensureUuid(props.itemId || routeItemId)
  const fieldIdentifier = props.field.fieldId || 'field'
 
  let resolvedFlowId = props.flowId || authStore.currentFlow
  Iif (!resolvedFlowId) {
    await authStore.loadUser()
    resolvedFlowId = props.flowId || authStore.currentFlow
  }
  Iif (!resolvedFlowId) {
    throw new Error('Missing active flow context')
  }
 
  const response = await api.post('/v1/upload/presigned-url', {
    fileName,
    fileType,
    flowId: resolvedFlowId,
    entityId,
    itemId,
    fieldName: fieldIdentifier,
    uploadKind: 'file'
  })
 
  return response.data
}
 
async function processFile(file: File): Promise<FileValue | null> {
  if (file.size > MAX_FILE_SIZE_BYTES) {
    toastStore.error(
      t('field.fileSizeInvalid').replace('{max}', formatFileSize(MAX_FILE_SIZE_BYTES))
    )
    return null
  }
 
  if (!isAllowedFileUpload(file.name, file.type)) {
    toastStore.error(t('field.fileTypeInvalid'))
    return null
  }
 
  const { uploadUrl, uploadFields, key } = await getPresignedUrl(file.name, file.type)
  await uploadToS3(file, uploadUrl, uploadFields)
 
  return { key, name: file.name, size: file.size, type: file.type }
}
 
async function handleFileChange(event: Event) {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  Iif (!file) return
 
  uploading.value = true
  try {
    const value = await processFile(file)
    if (value) emit('update:modelValue', value)
  } catch (error) {
    console.error('Error uploading file:', error)
    toastStore.error(t('field.fileUploadError'))
  } finally {
    uploading.value = false
    Eif (fileInput.value) fileInput.value.value = ''
  }
}
 
async function handleFileSetChange(event: Event) {
  const input = event.target as HTMLInputElement
  const files = Array.from(input.files || [])
  Iif (files.length === 0) return
 
  const maxFiles = props.field.maxFiles
  const room =
    typeof maxFiles === 'number' ? Math.max(0, maxFiles - fileSetValue.value.length) : files.length
  const filesToUpload = files.slice(0, room)
  Eif (files.length > filesToUpload.length) {
    toastStore.error(t('field.fileSetMaxReached'))
  }
 
  uploading.value = true
  try {
    const uploaded: FileValue[] = []
    for (const file of filesToUpload) {
      try {
        const value = await processFile(file)
        Eif (value) uploaded.push(value)
      } catch (error) {
        console.error('Error uploading file:', error)
        toastStore.error(t('field.fileUploadError'))
      }
    }
    Eif (uploaded.length > 0) {
      emit('update:modelValue', [...fileSetValue.value, ...uploaded])
    }
  } finally {
    uploading.value = false
    Eif (fileInput.value) fileInput.value.value = ''
  }
}
</script>
 
<style scoped>
.file-chip {
  display: flex;
  align-items: center;
}
</style>