All files / src/stores admin.ts

98.41% Statements 124/126
90.38% Branches 47/52
100% Functions 18/18
100% Lines 121/121

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 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x         35x 35x 35x     31x       4x 4x 4x 4x         29x 29x 29x 29x 29x   29x 27x 29x 29x 29x       8x 6x 6x 6x 6x 6x 4x 4x 4x   6x     1110x               13x 185x 185x 185x 185x 185x 185x   185x 185x 185x 185x       185x 185x 185x 185x 185x       185x     185x         185x           185x                   1x 1x               1x               1x 1x             185x     185x               1x 1x       14x 14x 14x 14x 10x   4x 4x     14x         11x 11x 11x 11x 7x   4x 4x   11x         26x 26x 26x 26x 23x   3x 3x     26x               6x 6x 6x 4x     6x 6x 3x       3x         4x   6x         2x 2x 2x 2x 1x   1x 1x 1x   2x         3x 3x       2x 2x       4x 4x 4x         3x 1x   3x   4x       185x                                                                        
import { defineStore } from 'pinia'
import { reactive, ref, type Ref } from 'vue'
import api from '@/services/api'
 
export interface GrowthAnalytics {
  totals: {
    users: number | null
    flows: number | null
    entities: number | null
    items: number | null
  }
  trend: {
    days: number
    signupsByDay: Record<string, number>
    usersDeletedByDay: Record<string, number>
    totalUsersByDay: Record<string, number>
    flowsCreatedByDay: Record<string, number>
    flowsDeletedByDay: Record<string, number>
    totalFlowsByDay: Record<string, number>
    entitiesCreatedByDay: Record<string, number>
    entitiesDeletedByDay: Record<string, number>
    totalEntitiesByDay: Record<string, number>
    // Estimated distinct active users per month (YYYY-MM); months with no
    // recorded activity are absent
    activeUsersByMonth?: Record<string, number>
  }
}
 
export interface CostSeriesPoint {
  period: string
  total: number
  byService: Array<{ service: string; amount: number }>
}
 
export interface CostAnalytics {
  currency: string
  granularity: 'DAILY' | 'MONTHLY'
  environment: string | null
  availableEnvironments: string[]
  totalCost: number
  series: CostSeriesPoint[]
}
 
export interface CostAnalyticsParams {
  granularity?: 'DAILY' | 'MONTHLY'
  months?: number
  environment?: string
}
 
export interface LambdaCreditPool {
  pool: string
  rate: string
}
 
export interface LambdaCreditsInfo {
  billing: 'always' | 'conditional' | 'never'
  billed: boolean
  pools: LambdaCreditPool[]
}
 
export interface LambdaBillingOverride {
  updatedAt: string | null
  updatedBy: string | null
}
 
export interface LambdaStatEntry {
  functionKey: string
  resource: string
  operation: string
  invocationCount: number
  avgDurationMs: number
  totalDurationMs: number
  timeSharePercent: number
  lastSeenAt: string | null
  credits: LambdaCreditsInfo
  /** Set when a platform admin marked this function always free, null otherwise. */
  freeOverride: LambdaBillingOverride | null
}
 
export interface AdminUserLookupResult {
  id: string
  email: string
  name: string | null
  nickname: string | null
  creditsBalance: number
}
 
export interface AdminPlatformUser {
  id: string
  email: string
  name: string | null
  nickname: string | null
  status: string
  isPlatformAdmin: boolean
  creditsBalance: number
  createdAt: string | null
}
 
export interface AdminPlatformFlow {
  id: string
  name: string
  slug: string
  description: string | null
  status: string
  joinPolicy: string | null
  ownerId: string
  ownerName: string | null
  ownerEmail: string | null
  createdAt: string | null
}
 
export interface AdminReportUser {
  id: string
  name: string | null
  nickname: string | null
  email: string | null
}
 
export interface AdminReportMessage {
  senderId: string
  body: string
  createdAt: string
}
 
export type ReportSanction = 'warning' | 'restriction' | 'ban'
export type ReportOutcome = 'actioned' | 'dismissed'
 
/** Where the reported user stands: strikes of the last 12 months, sanctions running */
export interface AdminReportedUserStanding {
  activeStrikes: number
  restrictedUntil: string | null
  bannedAt: string | null
}
 
/** How the reporter reports, over 12 months: against bad faith (UC-REPORT-011.1) */
export interface AdminReporterStanding {
  reports: number
  dismissed: number
  reportingWarnedAt: string | null
  // Only while it holds
  reportingSuspendedUntil: string | null
}
 
export type ReportingAction = 'warn' | 'suspend'
 
/** An admin's decision on a target's reports (UC-REPORT-005.1) */
export interface AdminReportDecision {
  // What an appeal names (UC-REPORT-009.1)
  id?: string
  outcome: ReportOutcome
  removed: boolean
  sanction: ReportSanction | null
  restrictedUntil: string | null
  note: string | null
  decidedBy: string
  decidedAt: string
}
 
export interface ReportDecisionInput {
  targetKey: string
  outcome: ReportOutcome
  removed?: boolean
  sanction?: ReportSanction
  restrictionDays?: number
  note?: string
}
 
/**
 * A user's report of a comment, a conversation or a store pack, with a copy of
 * what was reported, taken when it was reported.
 */
export interface AdminContentReport {
  id: string
  targetType: 'comment' | 'conversation' | 'pack'
  target: {
    commentId?: string
    entityId?: string
    itemId?: string
    packId?: string
    conversationId?: string
    flowId?: string | null
  }
  reason: string
  details: string | null
  reporter: AdminReportUser | null
  // null for a deleted account
  reporterStanding?: AdminReporterStanding | null
  reportedUser: AdminReportUser | null
  // null for a deleted account
  reportedUserStanding: AdminReportedUserStanding | null
  status: 'open' | ReportOutcome
  decision: AdminReportDecision | null
  // A dismissal overturned on appeal: the report is open again (UC-REPORT-010.1)
  previousDecision?: AdminReportDecision | null
  // The target's key, which a decision takes: every report of it is decided at once
  targetKey: string
  // How many reports of the same target the list holds
  targetReportCount?: number
  snapshot: {
    body?: string
    packVersion?: number
    name?: string | Record<string, string>
    version?: number | null
    status?: string
    requesterId?: string | null
    messages?: AdminReportMessage[]
    createdAt?: string | null
  }
  createdAt: string
}
 
export type AppealOutcome = 'upheld' | 'overturned'
 
/** The admin's answer to an appeal (UC-REPORT-010.1) */
export interface AdminAppealDecision {
  outcome: AppealOutcome
  note: string | null
  sanctionLifted: boolean
  reopened: number
  decidedBy: string
  decidedAt: string
}
 
/**
 * An appeal of a decision on reports (UC-REPORT-009.1): by the author of
 * actioned content, or a reporter of a dismissed report.
 */
export interface AdminAppeal {
  id: string
  decisionId: string
  appellant: AdminReportUser | null
  role: 'author' | 'reporter'
  message: string
  targetKey: string
  targetType: AdminContentReport['targetType']
  target: AdminContentReport['target']
  reason: string
  snapshot: AdminContentReport['snapshot']
  reportedUser: AdminReportUser | null
  reportedUserStanding: AdminReportedUserStanding | null
  decision: AdminReportDecision
  status: 'open' | AppealOutcome
  appealDecision: AdminAppealDecision | null
  createdAt: string
}
 
export interface AppealDecisionInput {
  decisionId: string
  appellantId: string
  outcome: AppealOutcome
  note?: string
}
 
interface PlatformListPage<T> {
  items: T[]
  nextCursor: string | null
  /** A search hit the index's candidate cap, so some matches may be missing */
  truncated?: boolean
}
 
/**
 * State + actions for one platform-wide, cursor-paginated admin list. `load`
 * (re)starts from the first page for a search text; `loadMore` follows the
 * cursor. A newer request supersedes an in-flight one, so a slow response for
 * an old search can never overwrite the results of the current one.
 */
function createPlatformList<T>(
  path: string,
  fallbackError: string,
  // Sent with every page, e.g. which of a list's partitions to read
  fixedParams: Record<string, string> = {}
) {
  // Cast: ref<T[]> on a generic T resolves to UnwrapRef<T>[], which loses T.
  const items = ref([]) as Ref<T[]>
  const nextCursor = ref<string | null>(null)
  const truncated = ref(false)
  const loading = ref(false)
  const loadingMore = ref(false)
  const error = ref<string | null>(null)
  let search = ''
  let latestRequest = 0
 
  type PageResult = { status: 'ok'; page: PlatformListPage<T> } | { status: 'error' | 'stale' }
 
  async function fetchPage(cursor?: string): Promise<PageResult> {
    const requestId = ++latestRequest
    try {
      const response = await api.get(path, {
        params: { ...fixedParams, ...(search && { search }), ...(cursor && { cursor }) }
      })
      return requestId === latestRequest
        ? { status: 'ok', page: response.data }
        : { status: 'stale' }
    } catch (err: any) {
      Iif (requestId !== latestRequest) return { status: 'stale' }
      console.error(`Failed to fetch ${path}:`, err)
      error.value = err.response?.data?.error || err.message || fallbackError
      return { status: 'error' }
    }
  }
 
  async function load(newSearch = '') {
    search = newSearch
    loading.value = true
    loadingMore.value = false
    error.value = null
    const result = await fetchPage()
    // A superseded request leaves `loading` to the request that replaced it.
    if (result.status === 'stale') return
    items.value = result.status === 'ok' ? result.page.items : []
    nextCursor.value = result.status === 'ok' ? result.page.nextCursor : null
    truncated.value = result.status === 'ok' && result.page.truncated === true
    loading.value = false
  }
 
  async function loadMore() {
    if (!nextCursor.value || loading.value || loadingMore.value) return
    loadingMore.value = true
    error.value = null
    const result = await fetchPage(nextCursor.value)
    Iif (result.status === 'stale') return
    if (result.status === 'ok') {
      items.value = [...items.value, ...result.page.items]
      nextCursor.value = result.page.nextCursor
      truncated.value = truncated.value || result.page.truncated === true
    }
    loadingMore.value = false
  }
 
  return { items, nextCursor, truncated, loading, loadingMore, error, load, loadMore }
}
 
/**
 * Platform-admin analytics — global metrics across all flows, restricted to
 * users with isPlatformAdmin: true (see authStore.isPlatformAdmin). Distinct
 * from any per-flow dashboard: the API calls here hit /v1/platform-admin/*.
 */
export const useAdminStore = defineStore('admin', () => {
  const growth = ref<GrowthAnalytics | null>(null)
  const costs = ref<CostAnalytics | null>(null)
  const growthLoading = ref(false)
  const costsLoading = ref(false)
  const growthError = ref<string | null>(null)
  const costsError = ref<string | null>(null)
 
  const lambdaStats = ref<LambdaStatEntry[]>([])
  const lambdaStatsLoading = ref(false)
  const lambdaStatsError = ref<string | null>(null)
  const lambdaBillingSavingKey = ref<string | null>(null)
 
  // Credits management (manual grant/correction stop-gap until Stripe
  // purchases exist — see docs/architecture/USAGE_METERING.md step 8)
  const userSearchResults = ref<AdminUserLookupResult[]>([])
  const selectedUser = ref<AdminUserLookupResult | null>(null)
  const lookupLoading = ref(false)
  const lookupError = ref<string | null>(null)
  const adjustLoading = ref(false)
 
  // Platform-wide flow/user lists (Flows and Users admin tabs). `reactive`
  // unwraps the refs, so consumers read `adminStore.platformUsers.items`.
  const platformUsers = reactive(
    createPlatformList<AdminPlatformUser>('/v1/platform-admin/users', 'Failed to load users')
  )
  const platformFlows = reactive(
    createPlatformList<AdminPlatformFlow>('/v1/platform-admin/flows', 'Failed to load flows')
  )
  // Users' reports (Reports tab): the same paging, never searched. The open
  // ones wait for a decision; the closed ones keep it.
  const contentReports = reactive(
    createPlatformList<AdminContentReport>(
      '/v1/platform-admin/content-reports',
      'Failed to load reports'
    )
  )
  const closedContentReports = reactive(
    createPlatformList<AdminContentReport>(
      '/v1/platform-admin/content-reports',
      'Failed to load reports',
      { status: 'closed' }
    )
  )
 
  /** Decides every open report of a target (UC-REPORT-005.1) */
  async function decideContentReport(input: ReportDecisionInput): Promise<AdminReportDecision> {
    const response = await api.post('/v1/platform-admin/content-reports/decision', input)
    return response.data.decision
  }
 
  /**
   * Ends a user's restriction, ban and reporting suspension; their strikes
   * stay (UC-REPORT-008.1, UC-REPORT-011.1)
   */
  async function liftUserSanctions(userId: string): Promise<void> {
    await api.post(`/v1/platform-admin/users/${userId}/lift-sanctions`)
  }
 
  /** Warns a reporter, or suspends their reporting for some days (UC-REPORT-011.1) */
  async function restrictReporting(
    userId: string,
    input: { action: ReportingAction; days?: number; note?: string }
  ): Promise<Pick<AdminReporterStanding, 'reportingWarnedAt' | 'reportingSuspendedUntil'>> {
    const response = await api.post(`/v1/platform-admin/users/${userId}/reporting`, input)
    return {
      reportingWarnedAt: response.data.reportingWarnedAt,
      reportingSuspendedUntil: response.data.reportingSuspendedUntil
    }
  }
 
  // Appeals of decisions (Appeals tab, UC-REPORT-010.1): the same paging
  const appeals = reactive(
    createPlatformList<AdminAppeal>('/v1/platform-admin/appeals', 'Failed to load appeals')
  )
  const closedAppeals = reactive(
    createPlatformList<AdminAppeal>('/v1/platform-admin/appeals', 'Failed to load appeals', {
      status: 'closed'
    })
  )
 
  /** Upholds or overturns an appeal (UC-REPORT-010.1) */
  async function decideAppeal(input: AppealDecisionInput): Promise<AdminAppealDecision> {
    const response = await api.post('/v1/platform-admin/appeals/decision', input)
    return response.data.appealDecision
  }
 
  async function fetchGrowthAnalytics() {
    growthLoading.value = true
    growthError.value = null
    try {
      const response = await api.get('/v1/platform-admin/analytics/growth')
      growth.value = response.data
    } catch (err: any) {
      console.error('Failed to fetch platform growth analytics:', err)
      growthError.value =
        err.response?.data?.error || err.message || 'Failed to load analytics data'
    } finally {
      growthLoading.value = false
    }
  }
 
  async function fetchCostAnalytics(params?: CostAnalyticsParams) {
    costsLoading.value = true
    costsError.value = null
    try {
      const response = await api.get('/v1/platform-admin/analytics/costs', { params })
      costs.value = response.data
    } catch (err: any) {
      console.error('Failed to fetch platform cost analytics:', err)
      costsError.value = err.response?.data?.error || err.message || 'Failed to load analytics data'
    } finally {
      costsLoading.value = false
    }
  }
 
  async function fetchLambdaStats() {
    lambdaStatsLoading.value = true
    lambdaStatsError.value = null
    try {
      const response = await api.get('/v1/platform-admin/lambda-stats')
      lambdaStats.value = response.data.functions
    } catch (err: any) {
      console.error('Failed to fetch platform lambda stats:', err)
      lambdaStatsError.value =
        err.response?.data?.error || err.message || 'Failed to load analytics data'
    } finally {
      lambdaStatsLoading.value = false
    }
  }
 
  // Marks a function always free (or clears that override), then patches the
  // matching lambdaStats row in place from the server's response — avoids a
  // full re-fetch just to reflect one toggle.
  async function updateLambdaBilling(functionKey: string, free: boolean) {
    lambdaBillingSavingKey.value = functionKey
    try {
      const response = await api.put('/v1/platform-admin/lambda-billing', { functionKey, free })
      const freeOverride: LambdaBillingOverride | null = response.data.free
        ? { updatedAt: response.data.updatedAt, updatedBy: response.data.updatedBy }
        : null
      const entry = lambdaStats.value.find((fn) => fn.functionKey === functionKey)
      if (entry) {
        entry.freeOverride = freeOverride
        // `pools` always reflects what this function would charge regardless
        // of the override (see admin/lambda-stats.js), so it's the stable
        // source for what `billed` reverts to once the override is cleared.
        entry.credits = {
          ...entry.credits,
          billed: freeOverride ? false : entry.credits.pools.length > 0
        }
      }
      return response.data as { functionKey: string; free: boolean } & LambdaBillingOverride
    } finally {
      lambdaBillingSavingKey.value = null
    }
  }
 
  async function searchUsersForCredits(search: string) {
    lookupLoading.value = true
    lookupError.value = null
    try {
      const response = await api.get('/v1/platform-admin/users/lookup', { params: { search } })
      userSearchResults.value = response.data.items
    } catch (err: any) {
      console.error('Failed to search users:', err)
      lookupError.value = err.response?.data?.error || err.message || 'Failed to search users'
      userSearchResults.value = []
    } finally {
      lookupLoading.value = false
    }
  }
 
  function selectUserForCredits(user: AdminUserLookupResult) {
    selectedUser.value = user
    userSearchResults.value = []
  }
 
  function clearUserSearchResults() {
    userSearchResults.value = []
    lookupError.value = null
  }
 
  async function adjustUserCredits(userId: string, amount: number, reason: string) {
    adjustLoading.value = true
    try {
      const response = await api.post(`/v1/platform-admin/credits/${userId}/adjust`, {
        amount,
        reason
      })
      // Keep the displayed balance in sync without a second lookup round trip.
      if (selectedUser.value?.id === userId) {
        selectedUser.value = { ...selectedUser.value, creditsBalance: response.data.balance }
      }
      return response.data as { balance: number; transactionId: string }
    } finally {
      adjustLoading.value = false
    }
  }
 
  return {
    growth,
    costs,
    growthLoading,
    costsLoading,
    growthError,
    costsError,
    lambdaStats,
    lambdaStatsLoading,
    lambdaStatsError,
    lambdaBillingSavingKey,
    platformUsers,
    platformFlows,
    contentReports,
    closedContentReports,
    decideContentReport,
    liftUserSanctions,
    restrictReporting,
    appeals,
    closedAppeals,
    decideAppeal,
    fetchGrowthAnalytics,
    fetchCostAnalytics,
    fetchLambdaStats,
    updateLambdaBilling,
    userSearchResults,
    selectedUser,
    lookupLoading,
    lookupError,
    adjustLoading,
    searchUsersForCredits,
    selectUserForCredits,
    clearUserSearchResults,
    adjustUserCredits
  }
})