All files / src/views AdminAppsView.vue

0% Statements 0/423
100% Branches 1/1
100% Functions 1/1
0% Lines 0/423

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import {
  ChevronDown, ChevronRight,
  Check, X, RotateCcw, Inbox, ExternalLink,
} from 'lucide-vue-next'
import BaseButton from '@/components/ui/BaseButton.vue'
import Modal from '@/components/ui/Modal.vue'
import AppVersionStatusBadge from '@/components/ui/AppVersionStatusBadge.vue'
import PageHeader from '@/components/ui/PageHeader.vue'
import EntityListState from '@/components/ui/EntityListState.vue'
import { appApi } from '@/api/app.api'
import { useToast } from '@/composables/useToast'
import type { App, AppVersionApproval } from '@/types'
 
const { t } = useI18n()
const toast = useToast()
 
// ----------------------------------------------------------------
// State
// ----------------------------------------------------------------
const isLoading = ref(true)
const apps = ref<App[]>([])
// appId → pending count (from initial pending queue load)
const pendingCountMap = ref<Record<string, number>>({})
// appId → total submission count (any status)
const submissionCountMap = ref<Record<string, number>>({})
// appId → loaded approvals (lazy)
const approvalsMap = ref<Record<string, AppVersionApproval[]>>({})
// appId → currently loading
const loadingMap = ref<Record<string, boolean>>({})
// which app is expanded
const expandedAppId = ref<string | null>(null)
// filter: true = only apps with submissions
const onlyWithSubmissions = ref(true)
 
// Reject modal (single version only)
const showRejectModal = ref(false)
const rejectTarget = ref<{ appId: string; appName: string; versionTag: string } | null>(null)
const rejectionReason = ref('')
const isRejecting = ref(false)
 
// Revoke modal
const showRevokeModal = ref(false)
const revokeTarget = ref<{ appId: string; versionTag: string } | null>(null)
const revokeReason = ref('')
const isRevoking = ref(false)
 
// Per-version action loading
const actingOn = ref<string | null>(null) // `${appId}:${versionTag}`
 
// ----------------------------------------------------------------
// Computed
// ----------------------------------------------------------------
const sortedApps = computed(() => {
  const filtered = onlyWithSubmissions.value
    ? apps.value.filter(a => (submissionCountMap.value[a.appId] ?? 0) > 0)
    : apps.value
  return [...filtered].sort((a, b) => {
    const pa = pendingCountMap.value[a.appId] ?? 0
    const pb = pendingCountMap.value[b.appId] ?? 0
    return pb - pa
  })
})
 
// ----------------------------------------------------------------
// Load
// ----------------------------------------------------------------
const loadAll = async () => {
  isLoading.value = true
  try {
    const [appsRes, pendingRes] = await Promise.all([
      appApi.list(),
      appApi.admin.listPendingApprovals(),
    ])
    apps.value = appsRes.data
 
    // Build pending + submission count maps from the pending queue
    const pending: Record<string, number> = {}
    const submissions: Record<string, number> = {}
    for (const item of pendingRes.data) {
      pending[item.appId] = (pending[item.appId] ?? 0) + 1
      submissions[item.appId] = (submissions[item.appId] ?? 0) + 1
    }
    pendingCountMap.value = pending
    submissionCountMap.value = submissions
  } catch {
    toast.error(t('AdminAppsView.loadError'))
  } finally {
    isLoading.value = false
  }
}
 
const loadApprovals = async (appId: string) => {
  if (approvalsMap.value[appId] !== undefined) return
  loadingMap.value[appId] = true
  try {
    const res = await appApi.listVersionApprovals(appId)
    approvalsMap.value[appId] = res.data
    // Update submission count now that we have the full picture
    submissionCountMap.value[appId] = res.data.length
    pendingCountMap.value[appId] = res.data.filter(a => a.status === 'pending').length
  } catch {
    approvalsMap.value[appId] = []
  } finally {
    loadingMap.value[appId] = false
  }
}
 
const toggleApp = async (appId: string) => {
  if (expandedAppId.value === appId) {
    expandedAppId.value = null
    return
  }
  expandedAppId.value = appId
  await loadApprovals(appId)
}
 
// ----------------------------------------------------------------
// Actions
// ----------------------------------------------------------------
const handleApprove = async (appId: string, _appName: string, versionTag: string) => {
  actingOn.value = `${appId}:${versionTag}`
  try {
    await appApi.admin.approveVersion(appId, versionTag)
    toast.success(t('AdminAppsView.approveSuccess'))
    // Update local state
    const list = approvalsMap.value[appId]
    if (list) {
      const entry = list.find(a => a.version_tag === versionTag)
      if (entry) entry.status = 'approved'
    }
    if (pendingCountMap.value[appId]) {
      pendingCountMap.value[appId] = Math.max(0, pendingCountMap.value[appId] - 1)
    }
  } catch {
    toast.error(t('AdminAppsView.approveError'))
  } finally {
    actingOn.value = null
  }
}
 
const openRejectModal = (appId: string, versionTag: string) => {
  rejectTarget.value = { appId, appName: '', versionTag }
  rejectionReason.value = ''
  showRejectModal.value = true
}
 
const handleReject = async () => {
  if (!rejectTarget.value || !rejectionReason.value.trim()) return
  const { appId, versionTag } = rejectTarget.value
  isRejecting.value = true
  try {
    await appApi.admin.rejectVersion(appId, versionTag, rejectionReason.value.trim())
    toast.success(t('AdminAppsView.rejectSuccess'))
    const list = approvalsMap.value[appId]
    if (list) {
      const entry = list.find(a => a.version_tag === versionTag)
      if (entry) {
        entry.status = 'rejected'
        entry.rejection_reason = rejectionReason.value.trim()
      }
    }
    if (pendingCountMap.value[appId]) {
      pendingCountMap.value[appId] = Math.max(0, pendingCountMap.value[appId] - 1)
    }
    showRejectModal.value = false
  } catch {
    toast.error(t('AdminAppsView.rejectError'))
  } finally {
    isRejecting.value = false
  }
}
 
const openRevokeModal = (appId: string, versionTag: string) => {
  revokeTarget.value = { appId, versionTag }
  revokeReason.value = ''
  showRevokeModal.value = true
}
 
const handleRevoke = async () => {
  if (!revokeTarget.value || !revokeReason.value.trim()) return
  const { appId, versionTag } = revokeTarget.value
  isRevoking.value = true
  try {
    await appApi.admin.revokeVersion(appId, versionTag, revokeReason.value.trim())
    toast.success(t('AdminAppsView.revokeSuccess'))
    const list = approvalsMap.value[appId]
    if (list) {
      const entry = list.find(a => a.version_tag === versionTag)
      if (entry) {
        entry.status = 'rejected'
        entry.rejection_reason = revokeReason.value.trim()
      }
    }
    showRevokeModal.value = false
  } catch {
    toast.error(t('AdminAppsView.revokeError'))
  } finally {
    isRevoking.value = false
  }
}
 
const formatDate = (val: string) => {
  const d = new Date(val)
  return isNaN(d.getTime()) ? val : d.toLocaleDateString('de-DE')
}
 
onMounted(loadAll)
</script>
 
<template>
  <div class="p-6">
 
    <PageHeader :title="$t('AdminAppsView.title')" :subtitle="$t('AdminAppsView.subtitle')">
      <template #actions>
        <!-- Filter toggle als Action. Spielt die Rolle, die in den
             anderen Views der "Neu"-Button spielt — Page-spezifisch,
             daher als Slot statt fest verdrahtet. -->
        <div class="flex items-center gap-2 text-sm">
          <span class="text-gray-500">{{ $t('AdminAppsView.filterLabel') }}</span>
          <button
            @click="onlyWithSubmissions = !onlyWithSubmissions"
            class="relative inline-flex h-5 w-10 flex-shrink-0 rounded-full border-2 border-transparent transition-colors duration-200 focus:outline-none"
            :class="onlyWithSubmissions ? 'bg-green-600' : 'bg-gray-300'"
          >
            <span
              class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200"
              :class="onlyWithSubmissions ? 'translate-x-5' : 'translate-x-0'"
            />
          </button>
          <span class="text-gray-700 font-medium">{{ $t('AdminAppsView.filterOnlySubmissions') }}</span>
        </div>
      </template>
    </PageHeader>
 
    <EntityListState
      :is-loading="isLoading && apps.length === 0"
      :is-empty="!isLoading && apps.length === 0"
      :icon="Inbox"
      :empty-message="$t('AdminAppsView.emptyAppsTitle')"
    >
      <!-- Accordion list. Apps mit pending Submissions stehen oben
           (siehe ``sortedApps`` im script). Anders als die anderen
           Main-Pages ist hier eine Liste, kein Grid — Approval-Workflow
           braucht das Aufklappen. -->
 
      <!-- Filter aktiv, aber keine offenen Einreichungen → eigener,
           freundlicher Empty-State. Ohne diesen Block wäre der Bereich
           einfach leer (apps.length > 0, aber sortedApps.length === 0),
           was wie ein Bug wirkt. -->
      <div
        v-if="sortedApps.length === 0"
        class="flex flex-col items-center justify-center py-16 px-6 text-center bg-gray-50 border border-dashed border-gray-200 rounded-xl"
      >
        <div class="w-14 h-14 rounded-full bg-white border border-gray-200 flex items-center justify-center mb-4">
          <Inbox :size="28" class="text-gray-400" />
        </div>
        <h3 class="text-base font-semibold text-gray-800 mb-1">
          {{ $t('AdminAppsView.emptyNoSubmissionsTitle') }}
        </h3>
        <p class="text-sm text-gray-500 max-w-sm">
          {{ $t('AdminAppsView.emptyNoSubmissionsDesc') }}
        </p>
        <button
          @click="onlyWithSubmissions = false"
          class="mt-5 text-sm font-medium text-primary hover:text-primaryDark underline-offset-2 hover:underline"
        >
          {{ $t('AdminAppsView.emptyShowAll') }}
        </button>
      </div>
 
      <div v-else class="space-y-2">
      <div
        v-for="app in sortedApps"
        :key="app.appId"
        class="border border-gray-200 rounded-xl overflow-hidden"
      >
        <!-- App row (header) -->
        <button
          class="w-full flex items-center gap-4 px-5 py-4 bg-white hover:bg-gray-50 transition-colors text-left"
          @click="toggleApp(app.appId)"
        >
          <component
            :is="expandedAppId === app.appId ? ChevronDown : ChevronRight"
            :size="18"
            class="text-gray-400 flex-shrink-0"
          />
 
          <!-- App name -->
          <span class="font-semibold text-gray-900 flex-grow">{{ app.name }}</span>
 
          <!-- Link to app detail -->
          <RouterLink
            :to="{ name: 'apps.detail', params: { id: app.appId } }"
            class="text-gray-400 hover:text-primary transition-colors p-1 rounded"
            :title="$t('AdminAppsView.goToApp')"
            @click.stop
          >
            <ExternalLink :size="15" />
          </RouterLink>
 
          <!-- Pending badge -->
          <span
            v-if="pendingCountMap[app.appId] && !app.is_private"
            class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-orange-100 text-orange-700"
          >
            {{ pendingCountMap[app.appId] }} {{ $t('AdminAppsView.pendingLabel') }}
          </span>
          <span
            v-else-if="app.is_private"
            class="text-xs text-purple-400"
          >
            {{ $t('AdminAppsView.privateLabel') }}
          </span>
          <span
            v-else
            class="text-xs text-gray-400"
          >
            {{ $t('AdminAppsView.noPendingLabel') }}
          </span>
        </button>
 
        <!-- Expanded: versions -->
        <div v-if="expandedAppId === app.appId" class="border-t border-gray-100 bg-gray-50">
 
          <!-- Private app: no pending submissions shown -->
          <div
            v-if="app.is_private"
            class="px-6 py-4 text-sm text-gray-400 italic"
          >
            {{ $t('AdminAppsView.privateAppNote') }}
          </div>
 
          <!-- Loading approvals -->
          <div v-else-if="loadingMap[app.appId]" class="flex justify-center py-6">
            <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-primary"></div>
          </div>
 
          <!-- No entries -->
          <div
            v-else-if="!(approvalsMap[app.appId] ?? []).length"
            class="px-6 py-4 text-sm text-gray-400 italic"
          >
            {{ $t('AdminAppsView.noVersionsSubmitted') }}
          </div>
 
          <!-- Version table -->
          <div v-else class="px-4 pb-3">
          <table class="w-full text-sm">
            <thead class="border-b border-gray-200">
              <tr>
                <th class="text-left py-2 px-2 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ $t('AdminAppsView.colVersion') }}</th>
                <th class="text-left py-2 px-4 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ $t('AdminAppsView.colStatus') }}</th>
                <th class="text-left py-2 px-4 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ $t('AdminAppsView.colDate') }}</th>
                <th class="text-right py-2 px-2 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ $t('AdminAppsView.colActions') }}</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
              <tr
                v-for="approval in (approvalsMap[app.appId] ?? [])"
                :key="approval.approvalId"
                class="bg-white hover:bg-gray-50 transition-colors"
              >
                <td class="py-3 px-2">
                  <span class="font-mono text-gray-800 bg-gray-100 px-2 py-0.5 rounded text-xs">
                    {{ approval.version_tag }}
                  </span>
                </td>
                <td class="py-3 px-4">
                  <div class="space-y-1.5">
                    <AppVersionStatusBadge :status="approval.status" />
                    <div v-if="approval.notes" class="flex items-start gap-1.5 max-w-xs">
                      <span class="text-xs font-medium text-gray-400 shrink-0 mt-px">{{ $t('AdminAppsView.notesLabel') }}</span>
                      <span class="text-xs text-gray-600 italic truncate" :title="approval.notes">{{ approval.notes }}</span>
                    </div>
                    <div v-if="approval.rejection_reason" class="flex items-start gap-1.5 max-w-xs">
                      <span class="text-xs font-medium text-red-400 shrink-0 mt-px">{{ $t('AdminAppsView.rejectionLabel') }}</span>
                      <span class="text-xs text-red-600 italic truncate" :title="approval.rejection_reason">{{ approval.rejection_reason }}</span>
                    </div>
                  </div>
                </td>
                <td class="py-3 px-4 text-gray-500 text-xs">
                  {{ formatDate(approval.created_at) }}
                </td>
                <td class="py-3 px-2">
                  <div class="flex justify-end gap-2">
 
                    <!-- Pending: Approve + Reject -->
                    <template v-if="approval.status === 'pending'">
                      <button
                        @click="handleApprove(app.appId, app.name, approval.version_tag)"
                        :disabled="actingOn === `${app.appId}:${approval.version_tag}`"
                        class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-green-50 text-green-700 border border-green-200 text-xs font-medium hover:bg-green-100 transition-colors disabled:opacity-50"
                      >
                        <Check :size="13" />
                        {{ $t('AdminAppsView.approveBtn') }}
                      </button>
                      <button
                        @click="openRejectModal(app.appId, approval.version_tag)"
                        :disabled="actingOn === `${app.appId}:${approval.version_tag}`"
                        class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-red-50 text-red-700 border border-red-200 text-xs font-medium hover:bg-red-100 transition-colors disabled:opacity-50"
                      >
                        <X :size="13" />
                        {{ $t('AdminAppsView.rejectBtn') }}
                      </button>
                    </template>
 
                    <!-- Approved: Revoke -->
                    <template v-else-if="approval.status === 'approved'">
                      <button
                        @click="openRevokeModal(app.appId, approval.version_tag)"
                        :disabled="actingOn === `${app.appId}:${approval.version_tag}`"
                        class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-gray-100 text-gray-600 border border-gray-200 text-xs font-medium hover:bg-gray-200 transition-colors disabled:opacity-50"
                      >
                        <RotateCcw :size="13" />
                        {{ $t('AdminAppsView.revokeBtn') }}
                      </button>
                    </template>
 
                    <!-- Rejected: Approve again -->
                    <template v-else-if="approval.status === 'rejected'">
                      <button
                        @click="handleApprove(app.appId, app.name, approval.version_tag)"
                        :disabled="actingOn === `${app.appId}:${approval.version_tag}`"
                        class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-green-50 text-green-700 border border-green-200 text-xs font-medium hover:bg-green-100 transition-colors disabled:opacity-50"
                      >
                        <Check :size="13" />
                        {{ $t('AdminAppsView.approveBtn') }}
                      </button>
                    </template>
 
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
          </div>
 
        </div>
      </div>
      </div>
    </EntityListState>
 
    <!-- Reject Modal -->
    <Modal :show="showRejectModal" @close="showRejectModal = false">
      <template #title>
        <span class="text-red-700">{{ $t('AdminAppsView.rejectModal.title') }}</span>
      </template>
      <template #body>
        <div class="space-y-5">
          <p class="text-sm text-gray-600">
            <span class="font-mono bg-gray-100 px-1.5 py-0.5 rounded text-xs">{{ rejectTarget?.versionTag }}</span>
            &nbsp;—&nbsp;{{ rejectTarget?.appName }}
          </p>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1.5">
              {{ $t('AdminAppsView.rejectModal.reasonLabel') }}
            </label>
            <textarea
              v-model="rejectionReason"
              :placeholder="$t('AdminAppsView.rejectModal.reasonPlaceholder')"
              rows="4"
              class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-red-400 focus:border-red-400 outline-none resize-none"
            />
          </div>
        </div>
      </template>
      <template #footer>
        <div class="flex justify-end gap-3">
          <BaseButton variant="ghost" @click="showRejectModal = false" :disabled="isRejecting">
            {{ $t('AdminAppsView.rejectModal.cancel') }}
          </BaseButton>
          <BaseButton
            variant="red"
            @click="handleReject"
            :disabled="!rejectionReason.trim() || isRejecting"
          >
            {{ isRejecting ? '...' : $t('AdminAppsView.rejectModal.submit') }}
          </BaseButton>
        </div>
      </template>
    </Modal>
 
    <!-- Revoke Modal -->
    <Modal :show="showRevokeModal" @close="showRevokeModal = false">
      <template #title>
        <span class="text-gray-800">{{ $t('AdminAppsView.revokeModal.title') }}</span>
      </template>
      <template #body>
        <div class="space-y-5">
          <p class="text-sm text-gray-600">
            <span class="font-mono bg-gray-100 px-1.5 py-0.5 rounded text-xs">{{ revokeTarget?.versionTag }}</span>
          </p>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1.5">
              {{ $t('AdminAppsView.revokeModal.reasonLabel') }}
            </label>
            <textarea
              v-model="revokeReason"
              :placeholder="$t('AdminAppsView.revokeModal.reasonPlaceholder')"
              rows="4"
              class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-gray-400 focus:border-gray-400 outline-none resize-none"
            />
          </div>
        </div>
      </template>
      <template #footer>
        <div class="flex justify-end gap-3">
          <BaseButton variant="ghost" @click="showRevokeModal = false" :disabled="isRevoking">
            {{ $t('AdminAppsView.revokeModal.cancel') }}
          </BaseButton>
          <BaseButton
            variant="primary"
            @click="handleRevoke"
            :disabled="!revokeReason.trim() || isRevoking"
          >
            {{ isRevoking ? '...' : $t('AdminAppsView.revokeModal.submit') }}
          </BaseButton>
        </div>
      </template>
    </Modal>
 
  </div>
</template>