All files / src/views NotificationsPage.vue

100% Statements 120/120
96.24% Branches 128/133
96% Functions 24/25
100% Lines 112/112

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  26x 1x       25x   53x                 1x   28x             4x 1x             1x 1x 1x 1x           1x                 2x                     1x                             1x                                                     26x 26x 26x 26x 26x 26x 26x 26x   26x                         26x 26x               38x 16x   22x 2x   20x 20x       1x 1x       28x         28x 25x 24x 19x 18x 2x   16x       97x       84x                 11x 1x   10x 10x     11x         8x 8x         28x 7x     7x   21x 5x         16x 2x   2x     2x         14x 13x 1x         12x 3x       9x 1x       8x     28x         28x 21x 5x 5x   16x 2x 2x 2x 2x   14x 2x   12x 1x   11x 3x 3x 3x   3x 2x             7x           7x                           5x 1x 1x     4x 4x 2x 2x 2x   2x 1x   1x 1x             26x 26x 26x   26x 25x   1x 1x       26x 1x                                                                                        
<template>
  <PageLayout :title="t('notifications.title')" class="notifications-page">
    <div class="container-fluid">
      <LoadingSpinner v-if="loading && notifications.length === 0" />
 
      <EmptyState v-else-if="!loading && notifications.length === 0">
        {{ t('notifications.empty') }}
      </EmptyState>
    </div>
 
    <VirtualCardGrid
      v-if="notifications.length > 0"
      :items="notifications"
      :has-more="!!nextToken"
      :is-loading="loading"
      single-column
      :estimate-size="96"
      @load-more="notificationsStore.loadMore()"
    >
      <template #card="{ item }">
        <div
          class="notification-row"
          :class="{ unread: notificationsStore.isNew(item), clickable: isClickable(item) }"
          :data-type="item.type"
          :role="isClickable(item) ? 'button' : undefined"
          :tabindex="isClickable(item) ? 0 : undefined"
          @click="open(item)"
          @keydown.enter="open(item)"
        >
          <font-awesome-icon
            :icon="iconFor(item)"
            class="notification-icon"
            :class="iconClassFor(item)"
          />
          <div class="notification-body">
            <div class="d-flex justify-content-between align-items-center gap-2">
              <span class="notification-title">{{ describe(item) }}</span>
              <span class="notification-time text-muted small">
                <time :datetime="item.createdAt" :title="formatDateTime(item.createdAt)">{{
                  formatRelative(item.createdAt)
                }}</time>
              </span>
            </div>
            <div class="notification-excerpt text-muted small">
              {{ excerpt(item) }}
            </div>
            <!-- The statement of reasons says how to contest the decision -->
            <div v-if="appealRefOf(item)" class="small mt-1">
              <button
                type="button"
                class="btn btn-link btn-sm p-0 notification-appeal"
                :disabled="appealed.has(appealRefOf(item)!.decisionId)"
                @click.stop="appealing = appealRefOf(item)"
              >
                <font-awesome-icon icon="fa-solid fa-scale-balanced" class="me-1" />
                {{
                  t(appealed.has(appealRefOf(item)!.decisionId) ? 'appeal.sent' : 'appeal.action')
                }}
              </button>
            </div>
            <!-- Sent before appeals were in the app: by email -->
            <div
              v-else-if="item.type === 'moderation-decision' && item.data.contactEmail"
              class="notification-contest small mt-1"
            >
              {{ t('notifications.moderationContest') }}
              <a :href="`mailto:${item.data.contactEmail}`" @click.stop>{{
                item.data.contactEmail
              }}</a>
            </div>
          </div>
          <span v-if="notificationsStore.isNew(item)" class="badge bg-primary notification-new">
            {{ t('notifications.new') }}
          </span>
        </div>
      </template>
    </VirtualCardGrid>
 
    <AppealModal :appeal-ref="appealing" @close="appealing = null" @appealed="onAppealed" />
  </PageLayout>
</template>
 
<script setup lang="ts">
// @implements UC-NOTIF-001.1, UC-NOTIF-002.1, UC-MOD-012.1, UC-WORKFLOW-011.1, UC-STORE-009.1, UC-STORE-013.1, UC-REPORT-006.1, UC-REPORT-009.1, UC-REPORT-010.1, UC-REPORT-011.1
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import PageLayout from '@/components/PageLayout.vue'
import VirtualCardGrid from '@/components/VirtualCardGrid.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import EmptyState from '@/components/EmptyState.vue'
import AppealModal from '@/components/AppealModal.vue'
import type { AppealRef } from '@/services/contentReports'
import { useUILanguage } from '@/composables/useUILanguage'
import { useDateFormat } from '@/composables/useDateFormat'
import { useLanguage } from '@/composables/useLanguage'
import {
  useNotificationsStore,
  type AppNotification,
  type ModerationDecisionData
} from '@/stores/notifications'
import { useToastStore } from '@/stores/toast'
import { useFlowLink } from '@/composables/useFlowLink'
import { flowRoute } from '@/router/flowRoutes'
 
const router = useRouter()
const { slugOf, currentFlowSlug } = useFlowLink()
const { t } = useUILanguage()
const { formatRelative, formatDateTime } = useDateFormat()
const { getTranslation } = useLanguage()
const notificationsStore = useNotificationsStore()
const toastStore = useToastStore()
const { notifications, loading, nextToken } = storeToRefs(notificationsStore)
 
const ICONS: Record<AppNotification['type'], string> = {
  'comment-rejected': 'fa-solid fa-ban',
  'comment-removed': 'fa-solid fa-trash',
  'automation-email-skipped': 'fa-solid fa-envelope',
  'pack-version-published': 'fa-solid fa-store',
  'moderation-decision': 'fa-solid fa-gavel',
  'report-decided': 'fa-solid fa-flag',
  'appeal-decided': 'fa-solid fa-scale-balanced',
  'reporting-warning': 'fa-solid fa-triangle-exclamation',
  'reporting-suspended': 'fa-solid fa-ban'
}
 
// The decision the user is appealing, and those appealed from this page
const appealing = ref<AppealRef | null>(null)
const appealed = reactive(new Set<string>())
 
/**
 * What an appeal of the notification's decision names: a decision against
 * the user's content, or the dismissal of their report. Null otherwise, and
 * for a notification sent before appeals were in the app.
 */
function appealRefOf(notification: AppNotification): AppealRef | null {
  if (notification.type !== 'moderation-decision' && notification.type !== 'report-decided') {
    return null
  }
  if (notification.type === 'report-decided' && notification.data.outcome !== 'dismissed') {
    return null
  }
  const { targetKey, decisionId } = notification.data
  return targetKey && decisionId ? { targetKey, decisionId } : null
}
 
function onAppealed(appealRef: AppealRef) {
  appealed.add(appealRef.decisionId)
  appealing.value = null
}
 
function iconFor(notification: AppNotification): string {
  return ICONS[notification.type]
}
 
/** Warnings in amber, news in blue, what went wrong in red */
function iconClassFor(notification: AppNotification): string {
  if (notification.type === 'automation-email-skipped') return 'text-warning'
  if (notification.type === 'pack-version-published') return 'text-primary'
  if (notification.type === 'report-decided') return 'text-success'
  if (notification.type === 'reporting-warning') return 'text-warning'
  if (notification.type === 'appeal-decided') {
    return notification.data.outcome === 'overturned' ? 'text-success' : 'text-secondary'
  }
  return 'text-danger'
}
 
function isRejection(notification: AppNotification): boolean {
  return notification.type === 'comment-rejected'
}
 
function isClickable(notification: AppNotification): boolean {
  return (
    isRejection(notification) ||
    notification.type === 'automation-email-skipped' ||
    notification.type === 'pack-version-published'
  )
}
 
/** "Recipes › Pancakes", or "Store › CRM" for a comment on a pack */
function where(data: { entityName?: unknown; itemLabel?: unknown; packName?: unknown }): string {
  if (data.packName) {
    return `${t('store.title')} › ${getTranslation(data.packName as string | Record<string, string>)}`
  }
  const entity = getTranslation(data.entityName as string | Record<string, string>)
  const label = data.itemLabel
    ? getTranslation(data.itemLabel as string | Record<string, string>)
    : ''
  return label ? `${entity} › ${label}` : entity
}
 
/** "your comment", "your pack Garden", "your messages": what a decision was about */
function reportedContent(data: { targetType: string; packName?: unknown }): string {
  const name = data.packName ? getTranslation(data.packName as string | Record<string, string>) : ''
  return t(`notifications.reportedContent.${data.targetType}`).replace('{name}', name)
}
 
/** "Your comment on Recipes › Pancakes was rejected" (or removed, or an email not sent) */
function describe(notification: AppNotification): string {
  if (notification.type === 'moderation-decision') {
    const key = notification.data.removed
      ? 'notifications.moderationRemoved'
      : 'notifications.moderationActioned'
    return t(key).replace('{content}', reportedContent(notification.data))
  }
  if (notification.type === 'report-decided') {
    return t(`notifications.reportDecided.${notification.data.outcome}`).replace(
      '{content}',
      t(`notifications.reportedTarget.${notification.data.targetType}`)
    )
  }
  if (notification.type === 'appeal-decided') {
    const { data } = notification
    const content =
      data.role === 'author'
        ? reportedContent(data)
        : t(`notifications.reportedTarget.${data.targetType}`)
    return t(`notifications.appealDecided.${data.role}.${data.outcome}`).replace(
      '{content}',
      content
    )
  }
  if (notification.type === 'reporting-warning') return t('notifications.reportingWarning')
  if (notification.type === 'reporting-suspended') {
    return t('notifications.reportingSuspended').replace(
      '{date}',
      formatDateTime(notification.data.suspendedUntil ?? '')
    )
  }
  if (notification.type === 'automation-email-skipped') {
    return t('notifications.automationEmailSkipped')
      .replace('{template}', getTranslation(notification.data.templateName))
      .replace('{where}', where(notification.data))
  }
  if (notification.type === 'pack-version-published') {
    return t('notifications.packVersionPublished')
      .replace('{pack}', getTranslation(notification.data.packName))
      .replace('{version}', String(notification.data.version))
  }
  const key = isRejection(notification)
    ? 'notifications.commentRejected'
    : 'notifications.commentRemoved'
  return t(key).replace('{where}', where(notification.data))
}
 
/** The comment, or why recipients were skipped: "No longer a member: 2 · No email address: 1" */
function excerpt(notification: AppNotification): string {
  if (notification.type === 'moderation-decision') return moderationReasons(notification.data)
  if (notification.type === 'report-decided') {
    const { data } = notification
    return data.contentExcerpt || (data.packName ? getTranslation(data.packName) : '')
  }
  if (notification.type === 'appeal-decided') {
    const { data } = notification
    const lifted = data.sanctionLifted ? [t('notifications.appealSanctionLifted')] : []
    const note = data.note ? [`“${data.note}”`] : []
    return [...lifted, ...note].join(' ') || data.contentExcerpt || ''
  }
  if (notification.type === 'reporting-warning' || notification.type === 'reporting-suspended') {
    return notification.data.note ? `“${notification.data.note}”` : t('notifications.reportingHint')
  }
  if (notification.type === 'pack-version-published') {
    return t('notifications.packVersionPublishedHint').replace('{flow}', notification.data.flowName)
  }
  if (notification.type !== 'automation-email-skipped') return notification.data.commentExcerpt
  const counts = new Map<string, number>()
  for (const { reason } of notification.data.recipients ?? []) {
    counts.set(reason, (counts.get(reason) ?? 0) + 1)
  }
  return [...counts]
    .map(([reason, count]) => `${t(`notifications.skipReasons.${reason}`)}: ${count}`)
    .join(' · ')
}
 
/** The statement of reasons: why, what follows, the administrator's note */
function moderationReasons(data: ModerationDecisionData): string {
  const sanction =
    data.sanction === 'restriction'
      ? t('notifications.sanctions.restriction').replace(
          '{date}',
          formatDateTime(data.restrictedUntil ?? '')
        )
      : t(`notifications.sanctions.${data.sanction}`)
  return [
    t('notifications.moderationReason').replace('{reason}', t(`report.reasons.${data.reason}`)),
    sanction,
    ...(data.note ? [`“${data.note}”`] : [])
  ].join(' ')
}
 
/**
 * A rejected comment is listed, with its status, in "My submissions"; an email
 * not sent leads to its item's entity; a new version of a pack, to the pack
 * over the Store, which offers the update. A removed comment is gone, and its entity may
 * no longer be reachable: nowhere to go.
 */
function open(notification: AppNotification) {
  if (isRejection(notification)) {
    router.push({ name: 'moderation' })
    return
  }
  // In the notification's flow, which may not be this tab's
  const inFlow = (flowId: string | undefined) => slugOf(flowId) ?? currentFlowSlug.value
  if (notification.type === 'automation-email-skipped') {
    const flowSlug = inFlow(notification.data.flowId)
    Eif (flowSlug) {
      router.push(flowRoute(flowSlug, 'entity-items', { entityId: notification.data.entityId }))
    }
  } else if (notification.type === 'pack-version-published') {
    const flowSlug = inFlow(notification.data.flowId)
    // Over the Store, on the update of the flow's copies
    Eif (flowSlug) {
      router.push(
        flowRoute(flowSlug, 'store', {}, { pack: notification.data.packId, section: 'update' })
      )
    }
  }
}
 
onMounted(async () => {
  notificationsStore.inboxOpen = true
  try {
    // List first: it carries the previous lastReadAt, which tells the new ones
    await notificationsStore.fetchNotifications()
    await notificationsStore.markAllRead()
  } catch (error) {
    console.error('Failed to load notifications:', error)
    toastStore.error(t('notifications.loadError'))
  }
})
 
onUnmounted(() => {
  notificationsStore.inboxOpen = false
})
</script>
 
<style scoped>
.notification-row {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem 1rem;
  border-radius: 0.5rem;
  background: var(--bw-surface-muted);
  border: 1px solid var(--bw-border);
  height: 100%;
  box-sizing: border-box;
}
 
.notification-row.clickable {
  cursor: pointer;
}
 
.notification-row.unread {
  border-color: var(--bs-primary, #0d6efd);
}
 
.notification-row.unread .notification-title {
  font-weight: 600;
}
 
.notification-icon {
  font-size: 1.25rem;
}
 
.notification-body {
  flex: 1;
  min-width: 0;
}
 
.notification-excerpt {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>