All files / src/views UserProfilePublicPage.vue

80.86% Statements 93/115
82.05% Branches 64/78
70% Functions 14/20
82.72% Lines 91/110

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    1x       1x       1x 1x     1x 1x   1x 1x       1x 1x               1x                                                                                           1x                                     1x 1x     18x                           77x                                                                                                 21x 21x 21x 21x 21x 21x 21x 21x   21x 21x 21x 21x 21x 21x 21x 21x 21x   41x 21x 18x   21x     21x 21x 21x 21x 21x 18x 18x   2x 1x   1x 1x     20x         18x 18x 18x 18x       18x         3x 3x   3x 3x 3x 3x 3x 1x   2x     1x 1x 1x       3x                                                         3x 3x 3x 3x 1x   2x 2x               3x           3x 3x 3x 3x 2x 1x   1x   2x 2x   1x 1x   3x         2x 2x       1x     21x                                      
<template>
  <PageLayout :title="displayName" class="user-profile-public-page">
    <div class="container-fluid">
      <LoadingSpinner v-if="loading" />
 
      <EmptyState v-else-if="notFound" variant="info">
        {{ t('userProfile.notFound') }}
      </EmptyState>
 
      <template v-else-if="profile">
        <div class="profile-card">
          <div class="profile-avatar">
            <UserAvatar :picture-key="profile.profilePicture" />
          </div>
          <div class="profile-details">
            <h2 class="mb-1">{{ displayName }}</h2>
            <p v-if="profile.nickname" class="text-muted mb-1">@{{ profile.nickname }}</p>
            <p class="text-muted mb-2">{{ t('userProfile.status') }}: {{ profile.status }}</p>
            <p class="reputation text-muted mb-2">
              {{ t('moderation.reputationLabel') }}:
              <strong>{{ profile.reputationScore ?? 0 }}</strong>
            </p>
            <p class="follow-counts text-muted mb-3">
              <span class="me-3">{{
                t('follows.followerCount').replace('{count}', String(profile.followerCount))
              }}</span>
              <span>{{
                t('follows.followingCount').replace('{count}', String(profile.followingCount))
              }}</span>
            </p>
 
            <div class="d-flex gap-2 flex-wrap">
              <button
                v-if="!isOwnProfile"
                class="btn"
                :class="profile.isFollowedByCurrentUser ? 'btn-outline-secondary' : 'btn-success'"
                :disabled="followActionInFlight"
                @click="toggleFollow"
              >
                <font-awesome-icon
                  :icon="
                    profile.isFollowedByCurrentUser
                      ? 'fa-solid fa-user-check'
                      : 'fa-solid fa-user-plus'
                  "
                  class="me-2"
                />
                {{
                  profile.isFollowedByCurrentUser
                    ? t('follows.unfollowButton')
                    : t('follows.followButton')
                }}
              </button>
 
              <button
                v-if="profile.canMessage"
                class="btn btn-primary"
                :disabled="startingConversation"
                @click="startConversation"
              >
                <font-awesome-icon icon="fa-solid fa-envelope" class="me-2" />
                {{ t('messages.messageButton') }}
              </button>
 
              <button
                v-if="!isOwnProfile && profile.isBlockedByCurrentUser"
                class="btn btn-outline-secondary"
                :disabled="blockActionInFlight"
                @click="unblock"
              >
                <font-awesome-icon icon="fa-solid fa-user-check" class="me-2" />
                {{ t('messages.unblock') }}
              </button>
              <button
                v-else-if="!isOwnProfile"
                class="btn btn-outline-danger"
                :disabled="blockActionInFlight"
                @click="confirmBlock.open = true"
              >
                <font-awesome-icon icon="fa-solid fa-user-slash" class="me-2" />
                {{ t('messages.block') }}
              </button>
            </div>
            <p
              v-if="!isOwnProfile && !profile.canMessage"
              class="text-muted fst-italic mt-2 mb-0 cannot-message"
            >
              {{
                profile.isBlockedByCurrentUser
                  ? t('messages.youBlockedUser').replace('{name}', displayName)
                  : t('messages.cannotMessage')
              }}
            </p>
          </div>
        </div>
 
        <div class="public-entities-section mt-4">
          <h5 class="mb-3">{{ t('follows.publicEntitiesTitle') }}</h5>
          <LoadingSpinner v-if="loadingEntities" :grid="false" :padding="3" />
          <EmptyState v-else-if="publicEntities.length === 0" variant="info" :grid="false">
            {{ t('follows.noPublicEntities') }}
          </EmptyState>
          <VirtualCardGrid v-else :items="publicEntities" :has-more="false" :offset-height="280">
            <template #card="{ item: entity }">
              <EntityCard
                :entity="entity"
                navigation-source="catalog"
                @subscribe="handleSubscribe(entity)"
                @unsubscribe="handleUnsubscribe(entity)"
              />
            </template>
          </VirtualCardGrid>
        </div>
      </template>
    </div>
  </PageLayout>
 
  <ConfirmModal
    :is-open="confirmBlock.open"
    :title="t('messages.blockTitle').replace('{name}', displayName)"
    :message="t('messages.blockWarning')"
    :confirm-label="t('messages.block')"
    variant="danger"
    @confirm="block"
    @cancel="confirmBlock.open = false"
  />
</template>
 
<script setup lang="ts">
// @implements UC-DM-001.1, UC-DM-002.2, UC-DM-003.2, UC-DM-009.1, UC-PROFILE-006.1, UC-PROFILE-009.1, UC-MOD-009.1
import { ref, computed, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import PageLayout from '@/components/PageLayout.vue'
import ConfirmModal from '@/components/ConfirmModal.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import EmptyState from '@/components/EmptyState.vue'
import VirtualCardGrid from '@/components/VirtualCardGrid.vue'
import EntityCard from '@/components/EntityCard.vue'
import UserAvatar from '@/components/UserAvatar.vue'
import api from '@/services/api'
import { useUILanguage } from '@/composables/useUILanguage'
import { useMessagesStore } from '@/stores/messages'
import { useToastStore } from '@/stores/toast'
import { useAuthStore } from '@/stores/auth'
import { useFollowsStore } from '@/stores/follows'
import { useEntitiesStore, type Entity } from '@/stores/entities'
import { getErrorMessage } from '@/utils/errors'
 
interface PublicUserProfile {
  id: string
  nickname: string | null
  name: string
  status: string
  profilePicture: string | null
  canMessage: boolean
  isBlockedByCurrentUser: boolean
  followerCount: number
  followingCount: number
  // Community-moderation reputation: informative, gates nothing
  reputationScore?: number
  isFollowedByCurrentUser: boolean
}
 
const route = useRoute()
const router = useRouter()
const { t } = useUILanguage()
const messagesStore = useMessagesStore()
const toastStore = useToastStore()
const authStore = useAuthStore()
const followsStore = useFollowsStore()
const entitiesStore = useEntitiesStore()
 
const profile = ref<PublicUserProfile | null>(null)
const loading = ref(true)
const notFound = ref(false)
const startingConversation = ref(false)
const followActionInFlight = ref(false)
const blockActionInFlight = ref(false)
const confirmBlock = reactive({ open: false })
const publicEntities = ref<Entity[]>([])
const loadingEntities = ref(false)
 
const displayName = computed(() => profile.value?.name || profile.value?.nickname || '')
const currentUserId = computed(
  () => authStore.user?.attributes?.sub || authStore.user?.sub || authStore.user?.userId || ''
)
const isOwnProfile = computed(() => !!profile.value && profile.value.id === currentUserId.value)
 
async function loadProfile() {
  loading.value = true
  notFound.value = false
  try {
    const userId = route.params.userId as string
    const response = await api.get<PublicUserProfile>(`/v1/users/${userId}`)
    profile.value = response.data
    loadPublicEntities(userId)
  } catch (error: any) {
    if (error?.response?.status === 404) {
      notFound.value = true
    } else {
      console.error('Failed to load user profile:', error)
      toastStore.error(t('userProfile.loadError'))
    }
  } finally {
    loading.value = false
  }
}
 
async function loadPublicEntities(userId: string) {
  loadingEntities.value = true
  try {
    const response = await api.get<{ items: Entity[] }>(`/v1/users/${userId}/entities`)
    publicEntities.value = response.data.items ?? []
  } catch (error) {
    console.error('Failed to load public entities:', error)
  } finally {
    loadingEntities.value = false
  }
}
 
async function toggleFollow() {
  Iif (!profile.value) return
  const wasFollowing = profile.value.isFollowedByCurrentUser
  // Optimistic: flip the button immediately, roll it back if the request fails.
  profile.value.isFollowedByCurrentUser = !wasFollowing
  profile.value.followerCount = Math.max(0, profile.value.followerCount + (wasFollowing ? -1 : 1))
  followActionInFlight.value = true
  try {
    if (wasFollowing) {
      await followsStore.unfollowUser(profile.value.id)
    } else {
      await followsStore.followUser(profile.value.id)
    }
  } catch (error) {
    profile.value.isFollowedByCurrentUser = wasFollowing
    profile.value.followerCount = Math.max(0, profile.value.followerCount + (wasFollowing ? 1 : -1))
    toastStore.error(
      getErrorMessage(error, wasFollowing ? t('follows.unfollowError') : t('follows.followError'))
    )
  } finally {
    followActionInFlight.value = false
  }
}
 
async function handleSubscribe(entity: Entity) {
  entity.subscribedByCurrentUser = true
  entity.subscriberCount = (entity.subscriberCount ?? 0) + 1
  try {
    await entitiesStore.subscribeToEntity(entity.id)
  } catch (error) {
    entity.subscribedByCurrentUser = false
    entity.subscriberCount = Math.max(0, (entity.subscriberCount ?? 0) - 1)
    toastStore.error(getErrorMessage(error, t('catalog.subscribe-error')))
  }
}
 
async function handleUnsubscribe(entity: Entity) {
  entity.subscribedByCurrentUser = false
  entity.subscriberCount = Math.max(0, (entity.subscriberCount ?? 0) - 1)
  try {
    await entitiesStore.unsubscribeFromEntity(entity.id)
  } catch (error) {
    entity.subscribedByCurrentUser = true
    entity.subscriberCount = (entity.subscriberCount ?? 0) + 1
    toastStore.error(getErrorMessage(error, t('catalog.unsubscribe-error')))
  }
}
 
async function startConversation() {
  Iif (!profile.value) return
  startingConversation.value = true
  try {
    const conversationId = await messagesStore.createOrGetConversation(profile.value.id)
    router.push({ name: 'conversation', params: { conversationId } })
  } catch (error: any) {
    console.error('Failed to start conversation:', error)
    toastStore.error(
      t(
        error?.response?.data?.error === 'ACCOUNT_RESTRICTED'
          ? 'report.restricted'
          : 'messages.startConversationError'
      )
    )
  } finally {
    startingConversation.value = false
  }
}
 
/** Blocks or unblocks this user, then re-reads the profile's `canMessage`. */
async function setBlocked(blocked: boolean) {
  Iif (!profile.value) return
  blockActionInFlight.value = true
  try {
    if (blocked) {
      await messagesStore.blockUser(profile.value.id)
      toastStore.success(t('messages.blockedToast').replace('{name}', displayName.value))
    } else {
      await messagesStore.unblockUser(profile.value.id)
    }
    const response = await api.get<PublicUserProfile>(`/v1/users/${profile.value.id}`)
    profile.value = response.data
  } catch (error) {
    console.error('Failed to change block:', error)
    toastStore.error(t('messages.blockError'))
  } finally {
    blockActionInFlight.value = false
  }
}
 
function block() {
  confirmBlock.open = false
  return setBlocked(true)
}
 
function unblock() {
  return setBlocked(false)
}
 
onMounted(loadProfile)
</script>
 
<style scoped>
.profile-card {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  padding: 1.5rem;
  border-radius: 0.5rem;
  background: var(--bw-surface-muted);
  border: 1px solid var(--bw-border);
  max-width: 36rem;
}
 
.profile-avatar {
  flex-shrink: 0;
}
</style>