浏览代码

Merge pull request #15885 from Classic298/admin_export_user_csv

feat: Add button (for admins) to export all users in DB as csv file
Tim Jaeryang Baek 2 月之前
父节点
当前提交
da01021836
共有 1 个文件被更改,包括 50 次插入0 次删除
  1. 50 0
      src/lib/components/admin/Settings/Database.svelte

+ 50 - 0
src/lib/components/admin/Settings/Database.svelte

@@ -7,6 +7,7 @@
 	import { config, user } from '$lib/stores';
 	import { toast } from 'svelte-sonner';
 	import { getAllUserChats } from '$lib/apis/chats';
+	import { getAllUsers } from '$lib/apis/users';
 	import { exportConfig, importConfig } from '$lib/apis/configs';
 
 	const i18n = getContext('i18n');
@@ -20,6 +21,29 @@
 		saveAs(blob, `all-chats-export-${Date.now()}.json`);
 	};
 
+	const exportUsers = async () => {
+		const users = await getAllUsers(localStorage.token);
+
+		const headers = ['id', 'name', 'email', 'role'];
+
+		const csv = [
+			headers.join(','),
+			...users.users.map((user) => {
+				return headers
+					.map((header) => {
+						if (user[header] === null || user[header] === undefined) {
+							return '';
+						}
+						return `"${String(user[header]).replace(/"/g, '""')}"`;
+					})
+					.join(',');
+			})
+		].join('\n');
+
+		const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
+		saveAs(blob, 'users.csv');
+	};
+
 	onMount(async () => {
 		// permissions = await getUserPermissions(localStorage.token);
 	});
@@ -180,6 +204,32 @@
 						{$i18n.t('Export All Chats (All Users)')}
 					</div>
 				</button>
+
+				<button
+					class=" flex rounded-md py-2 px-3 w-full hover:bg-gray-200 dark:hover:bg-gray-800 transition"
+					on:click={() => {
+						exportUsers();
+					}}
+				>
+					<div class=" self-center mr-3">
+						<svg
+							xmlns="http://www.w3.org/2000/svg"
+							viewBox="0 0 16 16"
+							fill="currentColor"
+							class="w-4 h-4"
+						>
+							<path d="M2 3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V3Z" />
+							<path
+								fill-rule="evenodd"
+								d="M13 6H3v6a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V6ZM8.75 7.75a.75.75 0 0 0-1.5 0v2.69L6.03 9.22a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l2.5-2.5a.75.75 0 1 0-1.06-1.06l-1.22 1.22V7.75Z"
+								clip-rule="evenodd"
+							/>
+						</svg>
+					</div>
+					<div class=" self-center text-sm font-medium">
+						{$i18n.t('Export Users')}
+					</div>
+				</button>
 			{/if}
 		</div>
 	</div>