All files / src/views UserProfilePage.vue

89.57% Statements 146/163
88.18% Branches 97/110
63.63% Functions 21/33
89.3% Lines 142/159

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    1x 1x   1x 1x 1x 1x       1x 1x                   1x       1x 1x                                                         1x 1x                           1x                                   1x 1x 1x 1x       1x       1x 1x 1x 1x 1x 1629x               1x 1x 1x         1x 1x 1x                         159x               1x 1x 1x 1x                       1x                                                               1x 3x   149x                                                           52x 52x 52x 52x   52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x   52x 1536x 3132x       52x   52x 52x     52x   52x 52x 52x   52x 52x 52x   52x 52x 52x 52x 52x                     3x 3x   3x 3x   3x           2x       3x 1x           2x   2x 2x 1x   1x       2x         2x 2x   1x 1x   1x   3x     3x           2x 1x 1x         1x 1x       3x 3x 2x 2x         7x   4x 4x     1x 1x 1x 1x 1x       8x   8x   6x   6x   5x 3x 3x   1x         6x 6x   6x 3x         7x 7x 7x   7x 7x             7x 1x         2x 2x 2x 2x   1x 1x   1x   2x         1x                                                                                                                                                                                              
<template>
  <PageLayout :title="t('profile.title')" class="profile-page">
    <div class="scrollable-content">
      <div class="row">
        <!-- Account Information Card -->
        <div class="col-xl-4 mb-3">
          <div class="card h-100">
            <div class="card-body">
              <h5 class="card-title">
                <font-awesome-icon icon="fa-solid fa-user" class="me-2 text-success" />
                {{ t('profile.accountInformation') }}
              </h5>
              <div class="mb-2">
                <div class="text-muted small">{{ t('profile.name') }}</div>
                <div>
                  {{
                    userStore.user?.attributes?.name?.trim() ||
                    userStore.user?.attributes?.email ||
                    'User'
                  }}
                </div>
              </div>
              <div>
                <div class="text-muted small">{{ t('profile.email') }}</div>
                <div>{{ userStore.user?.attributes?.email || 'N/A' }}</div>
              </div>
 
              <div class="mt-3">
                <div class="text-muted small mb-1">{{ t('profile.profilePictureOptional') }}</div>
                <ImageField
                  :model-value="profilePicture"
                  :field="{
                    name: t('profile.profilePicture'),
                    type: 'image',
                    fieldId: 'profile-picture'
                  }"
                  :is-editing="true"
                  :entity-id="profileImageOwnerId || undefined"
                  :item-id="profileImageOwnerId || undefined"
                  :clickable="false"
                  no-wrapper
                  @update:model-value="updateProfilePicture"
                />
                <div v-if="isSavingProfilePicture" class="text-muted small mt-2">
                  <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
                  {{ t('common.loading') }}
                </div>
                <div
                  v-if="profilePictureMessage"
                  class="alert small py-1 px-2 mt-2 mb-0"
                  :class="profilePictureSaveSuccess ? 'alert-success' : 'alert-danger'"
                >
                  {{ profilePictureMessage }}
                </div>
              </div>
 
              <hr class="my-3" />
              <h6 class="mb-2">{{ t('profile.interfaceTheme') }}</h6>
              <p class="text-muted small mb-2">{{ t('profile.interfaceThemeDescription') }}</p>
              <div class="btn-group w-100" role="group" :aria-label="t('profile.interfaceTheme')">
                <button
                  type="button"
                  class="btn btn-sm"
                  :class="themePreference === 'light' ? 'btn-primary' : 'btn-outline-secondary'"
                  @click="updateThemePreference('light')"
                >
                  {{ t('profile.interfaceThemeLight') }}
                </button>
                <button
                  type="button"
                  class="btn btn-sm"
                  :class="themePreference === 'dark' ? 'btn-primary' : 'btn-outline-secondary'"
                  @click="updateThemePreference('dark')"
                >
                  {{ t('profile.interfaceThemeDark') }}
                </button>
                <button
                  type="button"
                  class="btn btn-sm"
                  :class="themePreference === 'system' ? 'btn-primary' : 'btn-outline-secondary'"
                  @click="updateThemePreference('system')"
                >
                  {{ t('profile.interfaceThemeSystem') }}
                </button>
              </div>
            </div>
          </div>
        </div>
 
        <!-- Language Preferences Card -->
        <div class="col-xl-8 mb-3">
          <div class="card h-100">
            <div class="card-body">
              <h5 class="card-title mb-3">
                <font-awesome-icon icon="fa-solid fa-language" class="me-2 text-success" />
                {{ t('profile.contentLanguagePreferences') }}
              </h5>
              <p class="text-muted small mb-3">
                {{ t('profile.contentLanguageDescription') }}
              </p>
 
              <div class="row">
                <div class="col-md-6 mb-3">
                  <h6 class="mb-2">{{ t('profile.availableLanguages') }}</h6>
                  <p class="text-muted small mb-2">{{ t('profile.clickToAdd') }}</p>
                  <div class="language-list-container">
                    <div
                      v-for="lang in availableLanguages"
                      :key="lang.code"
                      class="language-item available mb-1"
                      draggable="true"
                      @click="addLanguagePreference(lang.code)"
                      @dragstart="handleDragStart($event, lang.code, 'available')"
                    >
                      <span class="me-2">{{ lang.flag }}</span>
                      <span class="flex-grow-1">{{ lang.nativeName }}</span>
                      <small class="text-muted">{{ lang.code }}</small>
                    </div>
                  </div>
                </div>
 
                <div class="col-md-6 mb-3">
                  <h6 class="mb-2">{{ t('profile.yourPreferenceOrder') }}</h6>
                  <p class="text-muted small mb-2">
                    {{
                      preferences.length > 0
                        ? t('profile.dragToReorder')
                        : t('profile.addLanguagesToStart')
                    }}
                  </p>
                  <div
                    class="language-list-container preferences-container"
                    @drop="handleDrop($event)"
                    @dragover.prevent
                    @dragenter.prevent
                  >
                    <div
                      v-for="(langCode, index) in preferences"
                      :key="langCode"
                      class="language-item preferred mb-1"
                      draggable="true"
                      @dragstart="handleDragStart($event, langCode, 'preferred')"
                      @dragover.prevent="handleDragOver($event, index)"
                    >
                      <span class="badge bg-success me-2">{{ index + 1 }}</span>
                      <span class="me-2">{{ getLanguageInfo(langCode)?.flag }}</span>
                      <span class="flex-grow-1">{{ getLanguageInfo(langCode)?.nativeName }}</span>
                      <small class="text-muted me-2">{{ langCode }}</small>
                      <button
                        class="btn btn-sm btn-danger p-0"
                        style="width: 20px; height: 20px; line-height: 1"
                        :title="t('profile.removeFromPreferences')"
                        @click="removeLanguagePreference(index)"
                      >
                        ×
                      </button>
                    </div>
                    <div v-if="isLoadingPreferences" class="text-center py-4">
                      <div class="spinner-border spinner-border-sm text-primary" role="status">
                        <span class="visually-hidden">{{ t('common.loading') }}</span>
                      </div>
                    </div>
                    <div
                      v-else-if="preferences.length === 0"
                      class="text-muted fst-italic text-center py-4"
                    >
                      {{ t('profile.noPreferencesSet') }}
                    </div>
                  </div>
                </div>
              </div>
 
              <div
                v-if="saveMessage"
                class="alert mt-2 mb-0"
                :class="saveSuccess ? 'alert-success' : 'alert-info'"
              >
                {{ saveMessage }}
              </div>
            </div>
          </div>
        </div>
      </div>
 
      <!-- Danger Zone -->
      <DangerZone class="mb-3">
        <DangerZoneAction
          :action-label="t('profile.deleteAccount')"
          :warning-text="t('profile.deleteAccountWarning')"
          :disabled="isDeletingAccount"
          :error="deleteAccountError"
          @action="confirmDeleteAccount.open = true"
        />
      </DangerZone>
    </div>
  </PageLayout>
 
  <ConfirmModal
    :is-open="confirmDeleteAccount.open"
    :title="t('profile.deleteAccount')"
    :message="t('profile.deleteAccountWarning')"
    :confirm-label="isDeletingAccount ? t('profile.deletingAccount') : t('profile.deleteAccount')"
    :confirm-text="t('profile.deleteAccountConfirmText')"
    variant="danger"
    @confirm="doDeleteAccount"
    @cancel="confirmDeleteAccount.open = false"
  />
</template>
 
<script setup lang="ts">
// @implements UC-AUTH-006.1, UC-PROFILE-001.1, UC-PROFILE-003.1, UC-PROFILE-004.1, UC-I18N-001.1, UC-I18N-009.1
import { ref, computed, onMounted, reactive } from 'vue'
import PageLayout from '@/components/PageLayout.vue'
import ConfirmModal from '@/components/ConfirmModal.vue'
import DangerZone from '@/components/DangerZone.vue'
import DangerZoneAction from '@/components/DangerZoneAction.vue'
import ImageField from '@/components/ImageField.vue'
import { useAuthStore as useUserStore } from '@/stores/auth'
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
import { useTheme, type ThemePreference } from '@/composables/useTheme'
import { CONTENT_LANGUAGES, getLanguageInfo } from '@/utils/languages'
import api from '@/services/api'
 
const userStore = useUserStore()
const { getLanguagePreferences, setLanguagePreferences, initializePreferences } = useLanguage()
const { t } = useUILanguage()
const { themePreference, setThemePreference } = useTheme()
 
const preferences = ref<string[]>([])
const initialPreferences = ref<string[]>([])
const isLoadingPreferences = ref(true)
const draggedItem = ref<{ code: string; source: 'available' | 'preferred' } | null>(null)
const reorderingOccurred = ref(false)
const saveMessage = ref('')
const saveSuccess = ref(false)
const profilePicture = ref<string | null>(null)
const isSavingProfilePicture = ref(false)
const profilePictureMessage = ref('')
const profilePictureSaveSuccess = ref(false)
const confirmDeleteAccount = reactive({ open: false })
const isDeletingAccount = ref(false)
const deleteAccountError = ref('')
 
const availableLanguages = computed(() => {
  return CONTENT_LANGUAGES.filter((lang) => !preferences.value.includes(lang.code)).sort((a, b) =>
    a.nativeName.localeCompare(b.nativeName)
  )
})
 
const profileImageOwnerId = computed(() => {
  const candidate =
    userStore.user?.attributes?.sub || userStore.user?.sub || userStore.user?.userId || ''
  return typeof candidate === 'string' && candidate.trim() ? candidate : ''
})
 
onMounted(async () => {
  // Load preferences from API first
  isLoadingPreferences.value = true
  await initializePreferences()
  isLoadingPreferences.value = false
 
  const saved = getLanguagePreferences()
  preferences.value = [...saved]
  initialPreferences.value = [...saved]
 
  try {
    const response = await api.get('/v1/users/preferences')
    profilePicture.value = response.data?.profilePicture || null
    Eif (!profilePicture.value && typeof window !== 'undefined') {
      profilePicture.value = localStorage.getItem('profilePictureKey') || null
    }
  } catch (error) {
    console.warn('Failed to load profile picture preference:', error)
    if (typeof window !== 'undefined') {
      profilePicture.value = localStorage.getItem('profilePictureKey') || null
    }
  }
})
 
async function updateProfilePicture(value: string | string[] | null) {
  const normalizedValue = typeof value === 'string' ? value : null
  profilePicture.value = normalizedValue
 
  isSavingProfilePicture.value = true
  try {
    // Keep languagePreferences for backward compatibility with currently deployed API.
    const response = await api.put('/v1/users/preferences', {
      languagePreferences: preferences.value,
      profilePicture: normalizedValue
    })
 
    const persistedProfilePicture =
      typeof response.data?.profilePicture === 'string' || response.data?.profilePicture === null
        ? response.data.profilePicture
        : normalizedValue
 
    if (persistedProfilePicture !== normalizedValue) {
      console.warn('[profile-picture] API persisted a different key than requested', {
        requested: normalizedValue,
        persisted: persistedProfilePicture
      })
    }
 
    profilePicture.value = persistedProfilePicture
 
    Eif (typeof window !== 'undefined') {
      if (persistedProfilePicture) {
        localStorage.setItem('profilePictureKey', persistedProfilePicture)
      } else {
        localStorage.removeItem('profilePictureKey')
      }
    }
 
    console.warn('[profile-picture] saved', {
      requested: normalizedValue,
      persisted: persistedProfilePicture
    })
 
    profilePictureMessage.value = t('profile.profilePictureSaved')
    profilePictureSaveSuccess.value = true
  } catch (error: any) {
    console.error('Failed to save profile picture preference:', error)
    profilePictureMessage.value =
      error.response?.data?.error || t('profile.profilePictureSaveError')
    profilePictureSaveSuccess.value = false
  } finally {
    isSavingProfilePicture.value = false
  }
 
  setTimeout(() => {
    profilePictureMessage.value = ''
  }, 3000)
}
 
async function addLanguagePreference(langCode: string) {
  if (!preferences.value.includes(langCode)) {
    preferences.value.push(langCode)
    await autoSavePreferences()
  }
}
 
async function removeLanguagePreference(index: number) {
  preferences.value.splice(index, 1)
  await autoSavePreferences()
}
 
function handleDragStart(event: DragEvent, langCode: string, source: 'available' | 'preferred') {
  draggedItem.value = { code: langCode, source }
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move'
    event.dataTransfer.setData('text/plain', langCode)
  }
}
 
async function handleDragOver(_event: DragEvent, targetIndex: number) {
  if (!draggedItem.value || draggedItem.value.source !== 'preferred') return
 
  const currentIndex = preferences.value.indexOf(draggedItem.value.code)
  if (currentIndex === -1 || currentIndex === targetIndex) return
 
  // Reorder array
  const newPrefs = [...preferences.value]
  newPrefs.splice(currentIndex, 1)
  newPrefs.splice(targetIndex, 0, draggedItem.value.code)
  preferences.value = newPrefs
  reorderingOccurred.value = true
}
 
async function handleDrop(event: DragEvent) {
  event.preventDefault()
 
  if (!draggedItem.value) return
 
  let shouldSave = false
 
  if (draggedItem.value.source === 'available') {
    // Add to preferences if not already there
    if (!preferences.value.includes(draggedItem.value.code)) {
      preferences.value.push(draggedItem.value.code)
      shouldSave = true
    }
  } else Iif (reorderingOccurred.value) {
    // Save if reordering occurred in preferred list
    shouldSave = true
  }
 
  draggedItem.value = null
  reorderingOccurred.value = false
 
  if (shouldSave) {
    await autoSavePreferences()
  }
}
 
async function autoSavePreferences() {
  try {
    await setLanguagePreferences(preferences.value)
    initialPreferences.value = [...preferences.value]
 
    saveMessage.value = t('profile.preferencesSaved')
    saveSuccess.value = true
  } catch (error) {
    console.error('Failed to save preferences:', error)
    saveMessage.value = 'Failed to save preferences. Please try again.'
    saveSuccess.value = false
  }
 
  setTimeout(() => {
    saveMessage.value = ''
  }, 3000)
}
 
async function doDeleteAccount() {
  isDeletingAccount.value = true
  deleteAccountError.value = ''
  try {
    await userStore.deleteAccount()
  } catch (err: any) {
    console.error('[doDeleteAccount] error:', err)
    deleteAccountError.value =
      err.response?.data?.error || err.message || t('profile.deleteAccountError')
    confirmDeleteAccount.open = false
  } finally {
    isDeletingAccount.value = false
  }
}
 
function updateThemePreference(preference: ThemePreference) {
  setThemePreference(preference)
}
</script>
 
<style scoped>
.profile-page :deep(.page-content) {
  padding: 0 !important;
  height: 100%;
  display: flex;
  flex-direction: column;
}
 
.profile-page {
  --profile-language-list-bg: #f8f9fa;
  --profile-preferences-bg: #f9fff1;
  --profile-preferences-border: #aafc74;
  --profile-preferred-border: #a6fc74;
  --profile-language-item-hover: #f0f9e8;
}
 
:global([data-bs-theme='dark'] .profile-page) {
  --profile-language-list-bg: #2b3138;
  --profile-preferences-bg: #3e4838;
  --profile-preferences-border: #bdfc74;
  --profile-preferred-border: #a6e27e;
  --profile-language-item-hover: #33452b;
}
 
.profile-page :deep(.page-header) {
  flex-shrink: 0;
  padding: 0 2rem !important;
  margin-bottom: 0;
}
 
.scrollable-content {
  flex: 1;
  overflow-y: auto;
  padding: 1rem 2rem;
}
 
/* Mobile optimization */
@media (max-width: 767px) {
  .profile-page :deep(.page-header) {
    padding: 0 1rem !important;
  }
 
  .scrollable-content {
    padding: 1rem;
  }
}
 
.language-list-container {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid var(--bw-border);
  border-radius: 0.375rem;
  padding: 0.5rem;
  background-color: var(--profile-language-list-bg);
}
 
.preferences-container {
  background-color: var(--profile-preferences-bg);
  border-color: var(--profile-preferences-border);
}
 
.language-item {
  display: flex;
  align-items: center;
  padding: 0.5rem;
  background: var(--bw-surface);
  border: 1px solid var(--bw-border);
  border-radius: 0.375rem;
  cursor: move;
  transition: all 0.2s;
}
 
.language-item.available {
  cursor: pointer;
}
 
.language-item.available:hover {
  border-color: #689909;
  background-color: var(--profile-language-item-hover);
  transform: translateX(4px);
}
 
.language-item.preferred {
  border-color: var(--profile-preferred-border);
}
 
.language-item.preferred:hover {
  border-color: #689909;
  box-shadow: 0 2px 4px rgba(104, 153, 9, 0.1);
}
</style>