@enlt-bakusoku/nuxt4 0.0.0-stage → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +38 -2
  2. package/dist/module.d.mts +25 -0
  3. package/dist/module.json +9 -0
  4. package/dist/module.mjs +208 -0
  5. package/dist/runtime/shared/schemas/user.d.ts +40 -0
  6. package/dist/runtime/shared/schemas/user.js +21 -0
  7. package/dist/runtime/tasks-catalog.d.ts +6 -0
  8. package/dist/runtime/tasks-catalog.js +7 -0
  9. package/dist/types.d.mts +9 -0
  10. package/package.json +120 -3
  11. package/scripts/bakusoku-dev.mjs +387 -0
  12. package/scripts/dev-log-relay.mjs +96 -0
  13. package/scripts/predeploy.mjs +24 -0
  14. package/scripts/prepare-firebase-artifact.mjs +43 -0
  15. package/scripts/setup-worktree.sh +59 -0
  16. package/scripts/verify-firebase-artifacts.mjs +70 -0
  17. package/src/layer/app/components/admin/AdminExecutionHistory.vue +137 -0
  18. package/src/layer/app/components/admin/TaskRunDialog.vue +162 -0
  19. package/src/layer/app/components/admin/UserManagementPage.vue +342 -0
  20. package/src/layer/app/components/debug/DebugApplicationLogs.vue +87 -0
  21. package/src/layer/app/components/debug/DebugErrorLogs.vue +47 -0
  22. package/src/layer/app/components/debug/DebugFirestoreOperations.vue +48 -0
  23. package/src/layer/app/components/debug/DebugHttpRequests.vue +86 -0
  24. package/src/layer/app/components/debug/DebugNavigation.vue +60 -0
  25. package/src/layer/app/components/debug/DebugNowControl.vue +243 -0
  26. package/src/layer/app/components/debug/DebugPublicConfig.vue +24 -0
  27. package/src/layer/app/components/debug/DebugTestAdmin.vue +67 -0
  28. package/src/layer/app/components/demo/DemoDebug.vue +266 -0
  29. package/src/layer/app/components/demo/DemoHome.vue +347 -0
  30. package/src/layer/app/components/demo/DemoLogin.vue +391 -0
  31. package/src/layer/app/components/demo/DemoPassword.vue +224 -0
  32. package/src/layer/app/components/demo/DemoRegister.vue +148 -0
  33. package/src/layer/app/components/home/HomePage.vue +77 -0
  34. package/src/layer/app/layouts/dashboard.vue +126 -0
  35. package/src/layer/app/layouts/default.vue +3 -0
  36. package/src/layer/app/middleware/admin.ts +15 -0
  37. package/src/layer/app/middleware/authenticated.ts +19 -0
  38. package/src/layer/app/pages/admin/migrations.vue +463 -0
  39. package/src/layer/app/pages/admin/tasks/[id].vue +276 -0
  40. package/src/layer/app/pages/admin/tasks/index.vue +220 -0
  41. package/src/layer/app/pages/admin/users.vue +17 -0
  42. package/src/layer/app/pages/bakusoku-devtools.vue +294 -0
  43. package/src/layer/app/plugins/auth-init.ts +36 -0
  44. package/src/layer/app/plugins/debug-devtools.client.ts +20 -0
  45. package/src/layer/app/plugins/debug-errors.client.ts +78 -0
  46. package/src/layer/app/plugins/debug-http.client.ts +154 -0
  47. package/src/layer/app/plugins/debug-nav.client.ts +28 -0
  48. package/src/layer/app/plugins/vuefire-inspect.ts +18 -0
  49. package/src/layer/app/stores/auth.ts +462 -0
  50. package/src/layer/app/stores/datetime.ts +41 -0
  51. package/src/layer/app/stores/debug.ts +235 -0
  52. package/src/layer/app/stores/user.ts +170 -0
  53. package/src/layer/app/utils/admin-execution.ts +48 -0
  54. package/src/layer/app/utils/dashboard-heading.ts +36 -0
  55. package/src/layer/app/utils/debug-bridge.ts +270 -0
  56. package/src/layer/app/utils/debug-firestore.ts +38 -0
  57. package/src/layer/app/utils/debug-format.ts +19 -0
  58. package/src/layer/app/utils/execution-refresh.ts +66 -0
  59. package/src/layer/app/utils/framework-version.ts +4 -0
  60. package/src/layer/app/utils/inspect-nuxt-vuefire.ts +288 -0
  61. package/src/layer/app/utils/is-debug-enabled.ts +13 -0
  62. package/src/layer/app/utils/logger.ts +235 -0
  63. package/src/layer/app/utils/map-auth-error.ts +11 -0
  64. package/src/layer/app/utils/mask-secrets.ts +100 -0
  65. package/src/layer/app/utils/resolve-auth-user.ts +53 -0
  66. package/src/layer/app/utils/resolve-firestore.ts +20 -0
  67. package/src/layer/app/utils/task-run.ts +15 -0
  68. package/src/layer/build-credentials.mjs +33 -0
  69. package/src/layer/nuxt.config.ts +86 -0
  70. package/src/layer/package.json +5 -0
  71. package/src/layer/server/api/debug/test-admin.post.ts +38 -0
  72. package/src/layer/server/api/tasks/executions/cancel.post.ts +21 -0
  73. package/src/layer/server/api/tasks/executions/index.get.ts +22 -0
  74. package/src/layer/server/api/tasks/executions/index.post.ts +25 -0
  75. package/src/layer/server/api/tasks/index.get.ts +70 -0
  76. package/src/layer/server/api/tasks/migrations/index.post.ts +27 -0
  77. package/src/layer/server/api/tasks/migrations/recovery.post.ts +20 -0
  78. package/src/layer/server/api/users/[id].delete.ts +57 -0
  79. package/src/layer/server/api/users/[id].put.ts +110 -0
  80. package/src/layer/server/api/users/index.post.ts +232 -0
  81. package/src/layer/server/utils/admin-access.ts +32 -0
  82. package/src/layer/server/utils/debug-test-admin.ts +17 -0
  83. package/src/layer/server/utils/firebase-admin.ts +22 -0
  84. package/src/layer/server/utils/logger.ts +172 -0
  85. package/src/layer/server/utils/tasks-gateway.ts +57 -0
  86. package/src/layer/server/utils/user-mutations.ts +103 -0
@@ -0,0 +1,137 @@
1
+ <template>
2
+ <UCard :ui="{ body: 'p-0 sm:p-0' }">
3
+ <template #header>
4
+ <div class="flex items-center justify-between gap-3">
5
+ <h2 class="text-base font-semibold">実行履歴</h2>
6
+ <UBadge color="neutral" variant="subtle">
7
+ {{ rows.length }}
8
+ </UBadge>
9
+ </div>
10
+ </template>
11
+
12
+ <UTable
13
+ :data="rows"
14
+ :columns="columns"
15
+ :loading="loading"
16
+ empty="記録はありません。"
17
+ >
18
+ <template #name-cell="{ row }">
19
+ <p class="font-medium">{{ row.original.name || '—' }}</p>
20
+ </template>
21
+ <template #id-cell="{ row }">
22
+ <p class="max-w-56 truncate font-mono text-xs text-gray-500" :title="row.original.id">
23
+ {{ row.original.id }}
24
+ </p>
25
+ </template>
26
+ <template #direction-cell="{ row }">
27
+ <UBadge v-if="row.original.direction === 'down'" color="warning" variant="subtle" size="sm">
28
+ ロールバック
29
+ </UBadge>
30
+ <UBadge v-else color="neutral" variant="subtle" size="sm">
31
+ 実行
32
+ </UBadge>
33
+ </template>
34
+ <template #status-cell="{ row }">
35
+ <UBadge :color="statusColor(row.original.status)" variant="subtle">
36
+ {{ statusLabel(row.original.status) }}
37
+ </UBadge>
38
+ </template>
39
+ <template #source-cell="{ row }">
40
+ <span class="text-sm">{{ sourceLabel(row.original.source) }}</span>
41
+ </template>
42
+ <template #actorUid-cell="{ row }">
43
+ <p class="max-w-28 truncate font-mono text-xs text-gray-500" :title="row.original.actorUid || undefined">
44
+ {{ row.original.actorUid || '—' }}
45
+ </p>
46
+ </template>
47
+ <template #times-cell="{ row }">
48
+ <dl class="space-y-0.5 text-xs text-gray-500">
49
+ <div v-if="showSchedule" class="flex gap-2">
50
+ <dt class="w-8 shrink-0">予定</dt>
51
+ <dd>{{ formatTime(row.original.scheduleTime) }}</dd>
52
+ </div>
53
+ <div class="flex gap-2">
54
+ <dt class="w-8 shrink-0">開始</dt>
55
+ <dd>{{ formatTime(row.original.startedAt) }}</dd>
56
+ </div>
57
+ <div class="flex gap-2">
58
+ <dt class="w-8 shrink-0">終了</dt>
59
+ <dd>{{ formatTime(row.original.endedAt) }}</dd>
60
+ </div>
61
+ </dl>
62
+ </template>
63
+ <template #attempts-cell="{ row }">
64
+ <span class="tabular-nums">{{ row.original.attempts }}</span>
65
+ </template>
66
+ <template #error-cell="{ row }">
67
+ <p
68
+ class="max-w-64 text-xs whitespace-pre-wrap"
69
+ :class="row.original.error ? 'text-red-600 dark:text-red-400' : 'text-gray-500'"
70
+ >
71
+ {{ row.original.error || row.original.message || '—' }}
72
+ </p>
73
+ </template>
74
+ <template #actions-cell="{ row }">
75
+ <div class="flex justify-end">
76
+ <UButton
77
+ v-if="row.original.status === 'pending' || row.original.status === 'accepted'"
78
+ size="xs"
79
+ color="neutral"
80
+ variant="outline"
81
+ :loading="acting === row.original.id"
82
+ @click="emit('cancel', row.original.id)"
83
+ >
84
+ 取消
85
+ </UButton>
86
+ </div>
87
+ </template>
88
+ </UTable>
89
+ </UCard>
90
+ </template>
91
+
92
+ <script setup lang="ts">
93
+ import { formatTime, statusColor, statusLabel, type AdminExecutionRow } from '../../utils/admin-execution'
94
+ import { computed } from '#imports'
95
+
96
+ const props = withDefaults(defineProps<{
97
+ rows: AdminExecutionRow[]
98
+ loading: boolean
99
+ subjectLabel: string
100
+ showSubject?: boolean
101
+ showSchedule?: boolean
102
+ acting: string
103
+ }>(), {
104
+ showSubject: true,
105
+ showSchedule: false,
106
+ })
107
+
108
+ const emit = defineEmits<{
109
+ cancel: [id: string]
110
+ }>()
111
+
112
+ const columns = computed(() => [
113
+ { accessorKey: 'id', header: props.showSubject ? 'ID' : '実行ID' },
114
+ ...(props.showSubject ? [
115
+ { accessorKey: 'name', header: props.subjectLabel },
116
+ { id: 'direction', header: '種別' },
117
+ ] : []),
118
+ { accessorKey: 'status', header: '状態' },
119
+ { accessorKey: 'source', header: '起動元' },
120
+ { accessorKey: 'actorUid', header: '操作者' },
121
+ { id: 'times', header: '時刻' },
122
+ { accessorKey: 'attempts', header: '試行' },
123
+ { id: 'error', header: 'メッセージ' },
124
+ { id: 'actions', header: '' },
125
+ ])
126
+
127
+ const sourceLabels: Record<string, string> = {
128
+ manual: '管理画面',
129
+ schedule: '周期',
130
+ app: 'アプリ',
131
+ }
132
+
133
+ /** 実行元を画面表示用のラベルに変換する。 */
134
+ function sourceLabel(source: string) {
135
+ return sourceLabels[source] || source || '—'
136
+ }
137
+ </script>
@@ -0,0 +1,162 @@
1
+ <template>
2
+ <UModal
3
+ v-model:open="open"
4
+ :title="task?.name || 'タスクを実行'"
5
+ :description="task?.description"
6
+ >
7
+ <template #body>
8
+ <form v-if="task" class="space-y-4" @submit.prevent="runTask">
9
+ <UAlert v-if="taskError" color="error" variant="soft" :title="taskError" />
10
+ <UFormField
11
+ label="実行時刻"
12
+ name="scheduleTime"
13
+ description="空欄はすぐに実行します。時刻はブラウザのタイムゾーンで解釈します。"
14
+ >
15
+ <UInput v-model="scheduleLocal" type="datetime-local" class="w-full" />
16
+ </UFormField>
17
+ <UFormField
18
+ v-for="field in task.fields"
19
+ :key="field.key"
20
+ :label="field.label"
21
+ :name="field.key"
22
+ :required="field.required"
23
+ >
24
+ <USelect
25
+ v-if="field.type === 'select'"
26
+ v-model="draft[field.key]"
27
+ :items="field.options"
28
+ class="w-full"
29
+ />
30
+ <USelect
31
+ v-else-if="field.type === 'user'"
32
+ v-model="draft[field.key]"
33
+ :items="userItems"
34
+ placeholder="ユーザーを選択"
35
+ class="w-full"
36
+ />
37
+ <UInput
38
+ v-else
39
+ v-model="draft[field.key]"
40
+ :placeholder="field.placeholder || undefined"
41
+ class="w-full"
42
+ />
43
+ </UFormField>
44
+ <div class="flex justify-end gap-2">
45
+ <UButton type="button" color="neutral" variant="ghost" @click="open = false">
46
+ キャンセル
47
+ </UButton>
48
+ <UButton type="submit" :loading="running">
49
+ 実行
50
+ </UButton>
51
+ </div>
52
+ </form>
53
+ </template>
54
+ </UModal>
55
+ </template>
56
+
57
+ <script setup lang="ts">
58
+ import { useBakusokuUserStore } from '../../stores/user'
59
+ import type { TaskRunTarget } from '../../utils/task-run'
60
+ import { computed, ref, watch } from '#imports'
61
+
62
+ const open = defineModel<boolean>('open', { required: true })
63
+ const props = defineProps<{ task: TaskRunTarget | null }>()
64
+ const emit = defineEmits<{ done: [message: string] }>()
65
+
66
+ const userStore = useBakusokuUserStore()
67
+ const running = ref(false)
68
+ const taskError = ref('')
69
+ const executionId = ref('')
70
+ const scheduleLocal = ref('')
71
+ const draft = ref<Record<string, string>>({})
72
+ const userItems = computed(() => userStore.users.map(user => ({
73
+ label: user.displayName || user.email || user.uid,
74
+ value: user.uid,
75
+ })))
76
+
77
+ watch(() => [open.value, props.task?.id] as const, async ([isOpen]) => {
78
+ if (!isOpen || !props.task) return
79
+ taskError.value = ''
80
+ executionId.value = newExecutionId(props.task.id)
81
+ scheduleLocal.value = ''
82
+ draft.value = {}
83
+ for (const field of props.task.fields) {
84
+ draft.value[field.key] = field.type === 'select' ? (field.options[0]?.value ?? '') : ''
85
+ }
86
+ if (props.task.fields.some(field => field.type === 'user')) {
87
+ await userStore.fetchUsers()
88
+ }
89
+ })
90
+
91
+ /** 指定された接頭辞を付けて実行 ID を生成する。 */
92
+ function newExecutionId(prefix: string) {
93
+ const stamp = new Date().toISOString().replace(/\D/g, '').slice(0, 14)
94
+ const rand = crypto.randomUUID().replace(/-/g, '').slice(0, 8)
95
+ return `${prefix}_${stamp}_${rand}`
96
+ }
97
+
98
+ /** API エラーから画面表示用のメッセージを取り出す。 */
99
+ function messageOf(err: unknown) {
100
+ if (typeof err === 'object' && err && 'data' in err) {
101
+ const data = (err as { data?: { message?: string, statusMessage?: string } }).data
102
+ if (data?.message) return data.message
103
+ if (data?.statusMessage) return data.statusMessage
104
+ }
105
+ if (err instanceof Error) return err.message
106
+ return '操作に失敗しました。'
107
+ }
108
+
109
+ /** API エラーから HTTP ステータスコードを取り出す。 */
110
+ function statusCodeOf(err: unknown) {
111
+ if (typeof err === 'object' && err && 'statusCode' in err) {
112
+ return Number((err as { statusCode?: number }).statusCode)
113
+ }
114
+ if (typeof err === 'object' && err && 'status' in err) {
115
+ return Number((err as { status?: number }).status)
116
+ }
117
+ return 0
118
+ }
119
+
120
+ /** 入力値と予約設定を送信し、タスク実行の受付結果を反映する。 */
121
+ async function runTask() {
122
+ const item = props.task
123
+ if (!item || !executionId.value) return
124
+ running.value = true
125
+ taskError.value = ''
126
+ const data: Record<string, string> = {}
127
+ for (const field of item.fields) {
128
+ data[field.key] = draft.value[field.key] ?? ''
129
+ }
130
+ let scheduleTime = ''
131
+ if (scheduleLocal.value) {
132
+ const date = new Date(scheduleLocal.value)
133
+ if (Number.isNaN(date.getTime())) {
134
+ taskError.value = '実行時刻の形式が正しくありません。'
135
+ running.value = false
136
+ return
137
+ }
138
+ scheduleTime = date.toISOString()
139
+ }
140
+ try {
141
+ const result = await $fetch<{ data?: { executionId?: string } }>('/api/tasks/executions', {
142
+ method: 'POST',
143
+ body: {
144
+ executionId: executionId.value,
145
+ taskType: item.id,
146
+ data,
147
+ ...(scheduleTime ? { scheduleTime } : {}),
148
+ },
149
+ })
150
+ const acceptedId = result.data?.executionId ?? executionId.value
151
+ open.value = false
152
+ emit('done', `${item.name}を受け付けました。実行IDは ${acceptedId} です。`)
153
+ } catch (err) {
154
+ taskError.value = messageOf(err)
155
+ if (statusCodeOf(err) === 409) {
156
+ executionId.value = newExecutionId(item.id)
157
+ }
158
+ } finally {
159
+ running.value = false
160
+ }
161
+ }
162
+ </script>
@@ -0,0 +1,342 @@
1
+ <template>
2
+ <div class="flex flex-col gap-6">
3
+ <div v-if="!inDashboard" class="flex flex-wrap items-center justify-between gap-3">
4
+ <h1 class="text-xl font-semibold">ユーザー管理</h1>
5
+ <UButton icon="i-lucide-user-plus" @click="openCreate">
6
+ ユーザーを作成
7
+ </UButton>
8
+ </div>
9
+
10
+ <UAlert
11
+ v-if="userStore.error"
12
+ color="error"
13
+ variant="soft"
14
+ :title="userStore.error"
15
+ />
16
+
17
+ <UCard :ui="{ body: 'p-0 sm:p-0' }">
18
+ <div class="flex flex-col gap-3 border-b border-gray-200 p-4 sm:flex-row sm:items-center sm:justify-between sm:px-6 dark:border-gray-800">
19
+ <UInput
20
+ v-model="query"
21
+ icon="i-lucide-search"
22
+ placeholder="表示名・メール・ロール・uid"
23
+ class="w-full sm:max-w-sm"
24
+ />
25
+ <div class="flex items-center justify-between gap-3">
26
+ <p class="text-sm text-gray-500">
27
+ {{ filteredUsers.length }} / {{ userStore.users.length }} 件
28
+ </p>
29
+ <UButton v-if="inDashboard" icon="i-lucide-user-plus" size="sm" @click="openCreate">
30
+ ユーザーを作成
31
+ </UButton>
32
+ </div>
33
+ </div>
34
+ <UTable
35
+ :data="filteredUsers"
36
+ :columns="userColumns"
37
+ :loading="isLoading"
38
+ empty="該当するユーザーはいません。"
39
+ >
40
+ <template #displayName-cell="{ row }">
41
+ <p class="font-medium">{{ row.original.displayName || '未設定' }}</p>
42
+ <p class="mt-1 max-w-48 truncate font-mono text-xs text-gray-500">{{ row.original.uid }}</p>
43
+ </template>
44
+ <template #email-cell="{ row }">
45
+ <p class="wrap-anywhere whitespace-normal">{{ row.original.email || '未設定' }}</p>
46
+ </template>
47
+ <template #role-cell="{ row }">
48
+ <UBadge color="neutral" variant="subtle">
49
+ {{ roleLabel(row.original.role) }}
50
+ </UBadge>
51
+ </template>
52
+ <template #disabled-cell="{ row }">
53
+ <UBadge :color="row.original.deletionPending ? 'warning' : row.original.disabled ? 'error' : 'success'" variant="subtle">
54
+ {{ row.original.deletionPending ? '削除待ち' : row.original.disabled ? '無効' : '有効' }}
55
+ </UBadge>
56
+ </template>
57
+ <template #actions-cell="{ row }">
58
+ <div class="flex justify-end gap-2">
59
+ <UButton v-if="row.original.deletionPending" size="xs" color="error" variant="outline" @click="askUserAction(row.original)">
60
+ 削除を再試行
61
+ </UButton>
62
+ <template v-else>
63
+ <UButton size="xs" color="neutral" variant="outline" @click="openEdit(row.original)">
64
+ 編集
65
+ </UButton>
66
+ <UButton
67
+ size="xs"
68
+ :color="row.original.disabled ? 'success' : 'error'"
69
+ variant="outline"
70
+ @click="askUserAction(row.original)"
71
+ >
72
+ {{ row.original.disabled ? '有効化' : '無効化' }}
73
+ </UButton>
74
+ </template>
75
+ </div>
76
+ </template>
77
+ </UTable>
78
+ </UCard>
79
+
80
+ <UModal v-model:open="createOpen" title="ユーザーを作成" description="Auth にアカウントを作り、同じ uid で Firestore にプロフィールを書きます。">
81
+ <template #body>
82
+ <UForm
83
+ :schema="createUserSchema"
84
+ :state="createState"
85
+ class="space-y-4"
86
+ @submit="handleCreate"
87
+ >
88
+ <UFormField label="メールアドレス" name="email">
89
+ <UInput v-model="createState.email" type="email" class="w-full" />
90
+ </UFormField>
91
+ <UFormField label="表示名" name="displayName">
92
+ <UInput v-model="createState.displayName" class="w-full" />
93
+ </UFormField>
94
+ <UFormField label="パスワード" name="password">
95
+ <UInput v-model="createState.password" type="password" class="w-full" />
96
+ </UFormField>
97
+ <UFormField label="ロール" name="role">
98
+ <USelect v-model="createState.role" :items="roleItems" class="w-full" />
99
+ </UFormField>
100
+ <div class="flex justify-end gap-2">
101
+ <UButton color="neutral" variant="ghost" type="button" @click="createOpen = false">
102
+ キャンセル
103
+ </UButton>
104
+ <UButton type="submit" :loading="isSaving">作成</UButton>
105
+ </div>
106
+ </UForm>
107
+ </template>
108
+ </UModal>
109
+
110
+ <UModal v-model:open="editOpen" title="ユーザーを編集" description="表示名とメールは Auth と Firestore の両方、ロールは Firestore だけを更新します。">
111
+ <template #body>
112
+ <UForm
113
+ :schema="editUserSchema"
114
+ :state="editState"
115
+ class="space-y-4"
116
+ @submit="handleEdit"
117
+ >
118
+ <UFormField label="メールアドレス" name="email">
119
+ <UInput v-model="editState.email" type="email" class="w-full" />
120
+ </UFormField>
121
+ <UFormField label="表示名" name="displayName">
122
+ <UInput v-model="editState.displayName" class="w-full" />
123
+ </UFormField>
124
+ <UFormField label="ロール" name="role">
125
+ <USelect v-model="editState.role" :items="roleItems" class="w-full" />
126
+ </UFormField>
127
+ <div class="flex justify-end gap-2">
128
+ <UButton color="neutral" variant="ghost" type="button" @click="editOpen = false">
129
+ キャンセル
130
+ </UButton>
131
+ <UButton type="submit" :loading="isSaving">保存</UButton>
132
+ </div>
133
+ </UForm>
134
+ </template>
135
+ </UModal>
136
+
137
+ <UModal v-model:open="confirmOpen" :title="confirmTitle" :description="confirmDescription">
138
+ <template #footer>
139
+ <div class="flex justify-end gap-2">
140
+ <UButton color="neutral" variant="ghost" @click="confirmOpen = false">
141
+ キャンセル
142
+ </UButton>
143
+ <UButton :color="pendingUser?.deletionPending || pendingDisabled ? 'error' : 'success'" :loading="isSaving" @click="confirmUserAction">
144
+ {{ pendingUser?.deletionPending ? '削除を完了する' : pendingDisabled ? '無効化する' : '有効化する' }}
145
+ </UButton>
146
+ </div>
147
+ </template>
148
+ </UModal>
149
+ </div>
150
+ </template>
151
+
152
+ <script setup lang="ts">
153
+ import { useBakusokuAuthStore, type BakusokuAuthProfile } from '../../stores/auth'
154
+ import { useBakusokuUserStore } from '../../stores/user'
155
+ import { useInDashboardLayout } from '../../utils/dashboard-heading'
156
+
157
+ import type { FormSubmitEvent } from '@nuxt/ui'
158
+ import { createUserSchema, type CreateUserInput } from '#bakusoku/user-schemas'
159
+
160
+ type Role = 'admin' | 'approver' | 'user'
161
+
162
+ const roles = [
163
+ { value: 'admin' as const, label: '管理者' },
164
+ { value: 'approver' as const, label: '承認者' },
165
+ { value: 'user' as const, label: '一般' },
166
+ ]
167
+
168
+ const roleItems = roles.map(role => ({ label: role.label, value: role.value }))
169
+ const userColumns = [
170
+ { accessorKey: 'displayName', header: '表示名' },
171
+ { accessorKey: 'email', header: 'メールアドレス' },
172
+ { accessorKey: 'role', header: 'ロール' },
173
+ { accessorKey: 'disabled', header: '状態' },
174
+ { id: 'actions', header: '' },
175
+ ]
176
+ const editUserSchema = createUserSchema.pick({
177
+ displayName: true,
178
+ email: true,
179
+ role: true,
180
+ })
181
+
182
+ const userStore = useBakusokuUserStore()
183
+ const authStore = useBakusokuAuthStore()
184
+ const toast = useToast()
185
+ const inDashboard = useInDashboardLayout()
186
+
187
+ const query = ref('')
188
+ const isLoading = ref(true)
189
+ const isSaving = ref(false)
190
+ const createOpen = ref(false)
191
+ const editOpen = ref(false)
192
+ const confirmOpen = ref(false)
193
+ const editingUid = ref('')
194
+ const pendingUser = ref<BakusokuAuthProfile | null>(null)
195
+ const pendingDisabled = ref(false)
196
+
197
+ const createState = reactive({
198
+ email: '',
199
+ displayName: '',
200
+ password: '',
201
+ role: 'user' as Role,
202
+ })
203
+
204
+ const editState = reactive({
205
+ email: '',
206
+ displayName: '',
207
+ role: 'user' as Role,
208
+ })
209
+
210
+ const filteredUsers = computed(() => {
211
+ const keyword = query.value.trim().toLowerCase()
212
+ if (!keyword) return userStore.users
213
+ return userStore.users.filter(user => {
214
+ const role = `${user.role ?? ''} ${roleLabel(user.role)}`.toLowerCase()
215
+ return [user.displayName, user.email, user.uid, role].some(value =>
216
+ String(value ?? '').toLowerCase().includes(keyword),
217
+ )
218
+ })
219
+ })
220
+
221
+ const confirmTitle = computed(() => {
222
+ if (pendingUser.value?.deletionPending) return 'ユーザーの削除を再試行'
223
+ return pendingDisabled.value ? 'ユーザーを無効化' : 'ユーザーを有効化'
224
+ })
225
+ const confirmDescription = computed(() => {
226
+ const name = pendingUser.value?.displayName || pendingUser.value?.email || 'このユーザー'
227
+ if (pendingUser.value?.deletionPending) return `${name} の削除を完了します。`
228
+ if (!pendingDisabled.value) return `${name} を再びログインできる状態にします。`
229
+ const self = pendingUser.value?.uid === authStore.user?.uid
230
+ const suffix = self ? ' 自分のアカウントです。無効化すると次回からログインできません。' : ''
231
+ return `${name} はログインできなくなります。一覧には残ります。${suffix}`
232
+ })
233
+
234
+ /** ユーザーの権限を表示用のラベルに変換する。 */
235
+ function roleLabel(role?: string) {
236
+ return roles.find(item => item.value === role)?.label ?? (role || '未設定')
237
+ }
238
+
239
+ /** ユーザーの権限をフォームで扱う値に変換する。 */
240
+ function asRole(role?: string): Role {
241
+ return roles.some(item => item.value === role) ? role as Role : 'user'
242
+ }
243
+
244
+ /** 作成フォームを初期化してユーザー作成ダイアログを開く。 */
245
+ function openCreate() {
246
+ createState.email = ''
247
+ createState.displayName = ''
248
+ createState.password = ''
249
+ createState.role = 'user'
250
+ createOpen.value = true
251
+ }
252
+
253
+ /** 選択したユーザーの値で編集フォームを初期化し、ダイアログを開く。 */
254
+ function openEdit(user: BakusokuAuthProfile) {
255
+ editingUid.value = user.uid
256
+ editState.email = user.email ?? ''
257
+ editState.displayName = user.displayName ?? ''
258
+ editState.role = asRole(user.role)
259
+ editOpen.value = true
260
+ }
261
+
262
+ /** 状態変更または削除再試行の確認ダイアログを開く。 */
263
+ function askUserAction(user: BakusokuAuthProfile) {
264
+ pendingUser.value = user
265
+ pendingDisabled.value = user.disabled !== true
266
+ confirmOpen.value = true
267
+ }
268
+
269
+ /** 作成フォームの入力を送信し、ユーザーを登録する。 */
270
+ async function handleCreate(event: FormSubmitEvent<CreateUserInput>) {
271
+ isSaving.value = true
272
+ try {
273
+ await userStore.createUser({
274
+ email: event.data.email,
275
+ displayName: event.data.displayName,
276
+ password: event.data.password,
277
+ role: event.data.role,
278
+ })
279
+ createOpen.value = false
280
+ toast.add({ title: 'ユーザーを作成しました', color: 'success' })
281
+ } catch (error) {
282
+ toast.add({
283
+ title: 'ユーザー作成に失敗しました',
284
+ description: userStore.error ?? (error as Error).message,
285
+ color: 'error',
286
+ })
287
+ } finally {
288
+ isSaving.value = false
289
+ }
290
+ }
291
+
292
+ /** 編集フォームの入力を送信し、ユーザーの情報を更新する。 */
293
+ async function handleEdit(event: FormSubmitEvent<Pick<CreateUserInput, 'displayName' | 'email' | 'role'>>) {
294
+ isSaving.value = true
295
+ try {
296
+ await userStore.updateUser(editingUid.value, {
297
+ email: event.data.email,
298
+ displayName: event.data.displayName,
299
+ role: event.data.role,
300
+ })
301
+ editOpen.value = false
302
+ toast.add({ title: 'ユーザーを更新しました', color: 'success' })
303
+ } catch (error) {
304
+ toast.add({
305
+ title: 'ユーザー更新に失敗しました',
306
+ description: userStore.error ?? (error as Error).message,
307
+ color: 'error',
308
+ })
309
+ } finally {
310
+ isSaving.value = false
311
+ }
312
+ }
313
+
314
+ /** 確認した状態変更または削除の再試行を送信する。 */
315
+ async function confirmUserAction() {
316
+ const user = pendingUser.value
317
+ if (!user) return
318
+ isSaving.value = true
319
+ try {
320
+ if (user.deletionPending) await userStore.deleteUserById(user.uid)
321
+ else await userStore.updateUser(user.uid, { disabled: pendingDisabled.value })
322
+ confirmOpen.value = false
323
+ toast.add({
324
+ title: user.deletionPending ? 'ユーザーを削除しました' : pendingDisabled.value ? 'ユーザーを無効化しました' : 'ユーザーを有効化しました',
325
+ color: 'success',
326
+ })
327
+ } catch (error) {
328
+ toast.add({
329
+ title: user.deletionPending ? '削除を完了できませんでした' : '状態の更新に失敗しました',
330
+ description: userStore.error ?? (error as Error).message,
331
+ color: 'error',
332
+ })
333
+ } finally {
334
+ isSaving.value = false
335
+ }
336
+ }
337
+
338
+ onMounted(async () => {
339
+ await userStore.fetchUsers()
340
+ isLoading.value = false
341
+ })
342
+ </script>