openadminjs 0.1.16 → 0.1.18
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.
- package/LICENSE +21 -0
- package/dist/create-project.js +4 -1
- package/dist/index.js +127 -0
- package/package.json +10 -11
- package/template/apps/admin/.storybook/main.ts +12 -0
- package/template/apps/admin/.storybook/preview.ts +10 -0
- package/template/apps/admin/app/dashboard/page.tsx +357 -277
- package/template/apps/admin/app/layout.tsx +5 -1
- package/template/apps/admin/app/login/page.tsx +38 -0
- package/template/apps/admin/app/resources/[resource]/page.tsx +15 -1
- package/template/apps/admin/app/settings/page.tsx +40 -2
- package/template/apps/admin/app/system-logs/page.tsx +212 -0
- package/template/apps/admin/components/api-error-banner.tsx +26 -0
- package/template/apps/admin/components/app-shell.tsx +92 -18
- package/template/apps/admin/components/logo.stories.tsx +24 -0
- package/template/apps/admin/components/resource-form.tsx +47 -0
- package/template/apps/admin/components/resource-table.tsx +417 -44
- package/template/apps/admin/lib/api.ts +44 -1
- package/template/apps/admin/lib/resource-table-prefs.ts +57 -0
- package/template/apps/admin/package.json +8 -2
- package/template/apps/api/package.json +28 -15
- package/template/apps/api/plugins.manifest.example.json +12 -0
- package/template/apps/api/prisma.config.ts +6 -0
- package/template/apps/api/src/admin/admin-ai.controller.ts +3 -2
- package/template/apps/api/src/admin/admin-logs.controller.ts +31 -0
- package/template/apps/api/src/admin/admin-plugins.controller.ts +5 -0
- package/template/apps/api/src/admin/admin-plugins.service.ts +11 -0
- package/template/apps/api/src/admin/admin-resource.service.ts +235 -1
- package/template/apps/api/src/admin/admin.controller.ts +35 -0
- package/template/apps/api/src/admin/admin.module.ts +6 -3
- package/template/apps/api/src/admin/dto/resource-bulk.dto.ts +17 -0
- package/template/apps/api/src/admin/dto/resource-reorder.dto.ts +17 -0
- package/template/apps/api/src/admin/dto/resource-upload.dto.ts +20 -0
- package/template/apps/api/src/app.module.ts +45 -5
- package/template/apps/api/src/auth/auth.module.ts +4 -2
- package/template/apps/api/src/auth/auth.service.test.ts +6 -3
- package/template/apps/api/src/auth/auth.service.ts +84 -0
- package/template/apps/api/src/auth/sso-oidc.controller.ts +78 -0
- package/template/apps/api/src/auth/sso-oidc.service.test.ts +84 -0
- package/template/apps/api/src/auth/sso-oidc.service.ts +281 -0
- package/template/apps/api/src/common/app-logger.service.ts +138 -0
- package/template/apps/api/src/common/auth.guard.test.ts +1 -0
- package/template/apps/api/src/common/auth.guard.ts +15 -1
- package/template/apps/api/src/common/current-user.decorator.ts +6 -2
- package/template/apps/api/src/common/logging.module.ts +10 -0
- package/template/apps/api/src/common/request-logging.interceptor.ts +70 -0
- package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +44 -0
- package/template/apps/api/src/graphql/admin-resources.resolver.ts +65 -0
- package/template/apps/api/src/graphql/graphql.module.ts +26 -0
- package/template/apps/api/src/main.ts +2 -0
- package/template/apps/api/src/plugins/bundled/registry.ts +3 -1
- package/template/apps/api/src/plugins/bundled/webhook.plugin.ts +64 -0
- package/template/apps/api/src/resources/categories.resource.ts +1 -0
- package/template/apps/api/src/resources/system.resource.ts +1 -0
- package/template/apps/web/package.json +2 -2
- package/template/package.json +1 -1
- package/template/packages/auth/package.json +1 -1
- package/template/packages/brand/package.json +1 -1
- package/template/packages/brand/src/generate-assets.mjs +12 -5
- package/template/packages/core/package.json +1 -1
- package/template/packages/core/src/index.ts +5 -0
- package/template/packages/core/vitest.config.ts +9 -0
- package/template/packages/mail/package.json +3 -3
- package/template/packages/notifications/package.json +1 -1
- package/template/packages/permissions/package.json +1 -1
- package/template/packages/plugin-sdk/package.json +1 -1
- package/template/packages/queue/package.json +1 -1
- package/template/packages/resource/package.json +12 -1
- package/template/packages/resource/src/index.test.ts +45 -0
- package/template/packages/resource/src/index.ts +63 -0
- package/template/packages/storage/package.json +1 -1
- package/template/prisma/schema.prisma +5 -0
- package/template/packages/core/src/index.js +0 -1
- package/template/packages/permissions/src/blueprints.js +0 -57
- package/template/packages/permissions/src/index.js +0 -11
- package/template/packages/resource/src/index.js +0 -177
|
@@ -11,6 +11,26 @@ const rawApi = process.env.NEXT_PUBLIC_API_URL;
|
|
|
11
11
|
export const API_URL =
|
|
12
12
|
typeof rawApi === "string" && rawApi.trim().length > 0 ? rawApi.trim() : "http://localhost:4000";
|
|
13
13
|
|
|
14
|
+
export class ApiError extends Error {
|
|
15
|
+
status: number;
|
|
16
|
+
retryAfterSec?: number;
|
|
17
|
+
|
|
18
|
+
constructor(message: string, status: number, retryAfterSec?: number) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = "ApiError";
|
|
21
|
+
this.status = status;
|
|
22
|
+
this.retryAfterSec = retryAfterSec;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const API_ERROR_EVENT = "openadmin:api-error";
|
|
27
|
+
|
|
28
|
+
function emitApiError(error: ApiError): void {
|
|
29
|
+
if (typeof window === "undefined") return;
|
|
30
|
+
if (typeof window.dispatchEvent !== "function") return;
|
|
31
|
+
window.dispatchEvent(new CustomEvent<ApiError>(API_ERROR_EVENT, { detail: error }));
|
|
32
|
+
}
|
|
33
|
+
|
|
14
34
|
export type ResourceMeta = {
|
|
15
35
|
name: string;
|
|
16
36
|
label: string;
|
|
@@ -92,12 +112,35 @@ export async function api<T>(path: string, options: RequestInit = {}): Promise<T
|
|
|
92
112
|
const url = `${API_URL}${withAdminLocale(path)}`;
|
|
93
113
|
const response = await requestWithAuthRetry(url, options);
|
|
94
114
|
if (!response.ok) {
|
|
115
|
+
const retryAfterHeader = response.headers?.get?.("retry-after") ?? null;
|
|
116
|
+
const retryAfterSec = retryAfterHeader ? Number(retryAfterHeader) : undefined;
|
|
95
117
|
const error = await response.json().catch(() => ({ message: response.statusText }));
|
|
96
|
-
|
|
118
|
+
if (response.status === 429) {
|
|
119
|
+
const seconds = Number.isFinite(retryAfterSec) ? Math.max(1, Number(retryAfterSec)) : undefined;
|
|
120
|
+
const message = seconds
|
|
121
|
+
? `Too many requests. Try again in ${seconds}s.`
|
|
122
|
+
: "Too many requests. Please try again in a moment.";
|
|
123
|
+
const err = new ApiError(message, 429, seconds);
|
|
124
|
+
emitApiError(err);
|
|
125
|
+
throw err;
|
|
126
|
+
}
|
|
127
|
+
const err = new ApiError((error as { message?: string }).message ?? "Request failed", response.status);
|
|
128
|
+
emitApiError(err);
|
|
129
|
+
throw err;
|
|
97
130
|
}
|
|
98
131
|
return response.json() as Promise<T>;
|
|
99
132
|
}
|
|
100
133
|
|
|
134
|
+
export function onApiError(listener: (error: ApiError) => void): () => void {
|
|
135
|
+
if (typeof window === "undefined") return () => {};
|
|
136
|
+
const handler = (event: Event) => {
|
|
137
|
+
const custom = event as CustomEvent<ApiError>;
|
|
138
|
+
if (custom.detail) listener(custom.detail);
|
|
139
|
+
};
|
|
140
|
+
window.addEventListener(API_ERROR_EVENT, handler as EventListener);
|
|
141
|
+
return () => window.removeEventListener(API_ERROR_EVENT, handler as EventListener);
|
|
142
|
+
}
|
|
143
|
+
|
|
101
144
|
async function requestWithAuthRetry(url: string, options: RequestInit): Promise<Response> {
|
|
102
145
|
const method = (options.method ?? "GET").toUpperCase();
|
|
103
146
|
const body =
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
const PREFIX = "openadminjs.resourceTable.";
|
|
2
|
+
|
|
3
|
+
function keyColumnOrder(resourceName: string): string {
|
|
4
|
+
return `${PREFIX}${resourceName}.columnOrder`;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function keyDensity(resourceName: string): string {
|
|
8
|
+
return `${PREFIX}${resourceName}.density`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type TableDensity = "comfortable" | "compact";
|
|
12
|
+
|
|
13
|
+
export function loadColumnOrder(resourceName: string, allowed: string[]): string[] {
|
|
14
|
+
if (typeof window === "undefined") return allowed;
|
|
15
|
+
try {
|
|
16
|
+
const raw = window.localStorage.getItem(keyColumnOrder(resourceName));
|
|
17
|
+
if (!raw) return allowed;
|
|
18
|
+
const parsed = JSON.parse(raw) as unknown;
|
|
19
|
+
if (!Array.isArray(parsed)) return allowed;
|
|
20
|
+
const set = new Set(allowed);
|
|
21
|
+
const ordered = parsed.map(String).filter((n) => set.has(n));
|
|
22
|
+
for (const n of allowed) {
|
|
23
|
+
if (!ordered.includes(n)) ordered.push(n);
|
|
24
|
+
}
|
|
25
|
+
return ordered;
|
|
26
|
+
} catch {
|
|
27
|
+
return allowed;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function saveColumnOrder(resourceName: string, order: string[]): void {
|
|
32
|
+
if (typeof window === "undefined") return;
|
|
33
|
+
try {
|
|
34
|
+
window.localStorage.setItem(keyColumnOrder(resourceName), JSON.stringify(order));
|
|
35
|
+
} catch {
|
|
36
|
+
/* ignore */
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function loadDensity(resourceName: string): TableDensity {
|
|
41
|
+
if (typeof window === "undefined") return "comfortable";
|
|
42
|
+
try {
|
|
43
|
+
const v = window.localStorage.getItem(keyDensity(resourceName));
|
|
44
|
+
return v === "compact" ? "compact" : "comfortable";
|
|
45
|
+
} catch {
|
|
46
|
+
return "comfortable";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function saveDensity(resourceName: string, density: TableDensity): void {
|
|
51
|
+
if (typeof window === "undefined") return;
|
|
52
|
+
try {
|
|
53
|
+
window.localStorage.setItem(keyDensity(resourceName), density);
|
|
54
|
+
} catch {
|
|
55
|
+
/* ignore */
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"dev": "next dev --port 3000",
|
|
8
|
+
"storybook": "storybook dev -p 6006",
|
|
9
|
+
"build-storybook": "storybook build",
|
|
8
10
|
"build": "next build",
|
|
9
11
|
"start": "next start --port 3000",
|
|
10
12
|
"lint": "tsc -p tsconfig.json --noEmit",
|
|
@@ -17,7 +19,7 @@
|
|
|
17
19
|
"@tanstack/react-table": "^8.20.6",
|
|
18
20
|
"clsx": "^2.1.1",
|
|
19
21
|
"lucide-react": "^0.468.0",
|
|
20
|
-
"next": "^15.
|
|
22
|
+
"next": "^15.5.18",
|
|
21
23
|
"next-intl": "^4.11.0",
|
|
22
24
|
"next-themes": "^0.4.4",
|
|
23
25
|
"react": "^19.0.0",
|
|
@@ -29,6 +31,9 @@
|
|
|
29
31
|
"zod": "^3.24.1"
|
|
30
32
|
},
|
|
31
33
|
"devDependencies": {
|
|
34
|
+
"@storybook/addon-docs": "^10.3.6",
|
|
35
|
+
"@storybook/addon-onboarding": "^10.3.6",
|
|
36
|
+
"@storybook/nextjs": "^10.3.6",
|
|
32
37
|
"@testing-library/jest-dom": "^6.9.1",
|
|
33
38
|
"@testing-library/react": "^16.3.2",
|
|
34
39
|
"@types/node": "^22.10.2",
|
|
@@ -37,8 +42,9 @@
|
|
|
37
42
|
"autoprefixer": "^10.4.20",
|
|
38
43
|
"jsdom": "^29.1.1",
|
|
39
44
|
"postcss": "^8.4.49",
|
|
45
|
+
"storybook": "^10.3.6",
|
|
40
46
|
"tailwindcss": "^3.4.17",
|
|
41
47
|
"typescript": "^5.7.2",
|
|
42
|
-
"vitest": "^2.
|
|
48
|
+
"vitest": "^3.2.0"
|
|
43
49
|
}
|
|
44
50
|
}
|
|
@@ -5,52 +5,65 @@
|
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"dev": "tsx watch src/main.ts",
|
|
8
|
+
"prisma:generate": "prisma generate --schema ../../prisma/schema.prisma",
|
|
9
|
+
"prebuild": "pnpm run prisma:generate",
|
|
8
10
|
"build": "nest build",
|
|
9
11
|
"start": "node dist/apps/api/src/main.js",
|
|
12
|
+
"prelint": "pnpm run prisma:generate",
|
|
10
13
|
"lint": "tsc -p tsconfig.json --noEmit",
|
|
14
|
+
"pretypecheck": "pnpm run prisma:generate",
|
|
11
15
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
16
|
+
"pretest": "pnpm run prisma:generate",
|
|
12
17
|
"test": "vitest run",
|
|
13
18
|
"db:migrate": "prisma migrate dev --schema ../../prisma/schema.prisma",
|
|
14
19
|
"db:seed": "prisma db seed --schema ../../prisma/schema.prisma"
|
|
15
20
|
},
|
|
16
21
|
"dependencies": {
|
|
22
|
+
"@apollo/server": "^5.5.0",
|
|
17
23
|
"@casl/ability": "^6.8.1",
|
|
24
|
+
"@nestjs/apollo": "^13.4.0",
|
|
18
25
|
"@nestjs/bullmq": "^11.0.4",
|
|
19
|
-
"@nestjs/common": "^
|
|
20
|
-
"@nestjs/config": "^
|
|
21
|
-
"@nestjs/core": "^
|
|
22
|
-
"@nestjs/
|
|
23
|
-
"@nestjs/
|
|
24
|
-
"@nestjs/
|
|
25
|
-
"@nestjs/
|
|
26
|
+
"@nestjs/common": "^11.1.19",
|
|
27
|
+
"@nestjs/config": "^4.0.4",
|
|
28
|
+
"@nestjs/core": "^11.1.19",
|
|
29
|
+
"@nestjs/graphql": "^13.4.0",
|
|
30
|
+
"@nestjs/jwt": "^11.0.2",
|
|
31
|
+
"@nestjs/platform-express": "^11.1.19",
|
|
32
|
+
"@nestjs/swagger": "^11.4.2",
|
|
33
|
+
"@nestjs/throttler": "^6.5.0",
|
|
26
34
|
"@openadminjs/core": "workspace:*",
|
|
27
35
|
"@openadminjs/mail": "workspace:*",
|
|
28
36
|
"@openadminjs/payments": "workspace:*",
|
|
29
37
|
"@openadminjs/permissions": "workspace:*",
|
|
30
38
|
"@openadminjs/plugin-sdk": "workspace:*",
|
|
31
|
-
"
|
|
32
|
-
"stripe": "^17.7.0",
|
|
39
|
+
"@openadminjs/storage": "workspace:^",
|
|
33
40
|
"@prisma/client": "^6.1.0",
|
|
41
|
+
"@types/express": "^5.0.6",
|
|
34
42
|
"bcryptjs": "^2.4.3",
|
|
35
43
|
"bullmq": "^5.76.4",
|
|
36
44
|
"class-transformer": "^0.5.1",
|
|
37
45
|
"class-validator": "^0.14.1",
|
|
46
|
+
"cookie-parser": "^1.4.7",
|
|
47
|
+
"graphql": "^16.11.0",
|
|
48
|
+
"graphql-scalars": "^1.25.0",
|
|
38
49
|
"helmet": "^8.0.0",
|
|
39
50
|
"ioredis": "^5.10.1",
|
|
51
|
+
"nodemailer": "^8.0.5",
|
|
40
52
|
"reflect-metadata": "^0.2.2",
|
|
41
53
|
"rxjs": "^7.8.1",
|
|
54
|
+
"stripe": "^17.7.0",
|
|
55
|
+
"winston": "^3.19.0",
|
|
56
|
+
"winston-daily-rotate-file": "^5.0.0",
|
|
42
57
|
"zod": "^3.24.1"
|
|
43
58
|
},
|
|
44
59
|
"devDependencies": {
|
|
45
|
-
"@nestjs/cli": "^
|
|
60
|
+
"@nestjs/cli": "^11.0.21",
|
|
46
61
|
"@types/bcryptjs": "^2.4.6",
|
|
47
|
-
"@types/
|
|
62
|
+
"@types/cookie-parser": "^1.4.10",
|
|
63
|
+
"@types/nodemailer": "^8.0.0",
|
|
48
64
|
"prisma": "^6.1.0",
|
|
49
65
|
"tsx": "4.19.2",
|
|
50
66
|
"typescript": "^5.7.2",
|
|
51
|
-
"vitest": "^2.
|
|
52
|
-
},
|
|
53
|
-
"prisma": {
|
|
54
|
-
"seed": "tsx ../../prisma/seed.ts"
|
|
67
|
+
"vitest": "^3.2.0"
|
|
55
68
|
}
|
|
56
69
|
}
|
|
@@ -17,6 +17,18 @@
|
|
|
17
17
|
"bundled": "seo",
|
|
18
18
|
"config": {}
|
|
19
19
|
},
|
|
20
|
+
{
|
|
21
|
+
"id": "io.openadminjs.webhook",
|
|
22
|
+
"enabled": false,
|
|
23
|
+
"trustMode": "sandboxed",
|
|
24
|
+
"capabilities": ["resource.hooks"],
|
|
25
|
+
"bundled": "webhook",
|
|
26
|
+
"config": {
|
|
27
|
+
"url": "https://example.com/openadmin-hooks",
|
|
28
|
+
"secret": "optional-shared-secret",
|
|
29
|
+
"resources": ["posts", "orders"]
|
|
30
|
+
}
|
|
31
|
+
},
|
|
20
32
|
{
|
|
21
33
|
"id": "com.vendor.billing",
|
|
22
34
|
"enabled": false,
|
|
@@ -81,10 +81,11 @@ export class AdminAiController {
|
|
|
81
81
|
}
|
|
82
82
|
} catch (error) {
|
|
83
83
|
const err = error as { response?: { message?: string; code?: string; details?: unknown } };
|
|
84
|
+
const errorCode = err.response?.code ?? "AI_STREAM_FAILED";
|
|
84
85
|
const payload: AiStreamErrorEvent = {
|
|
85
86
|
type: "error",
|
|
86
|
-
message:
|
|
87
|
-
code:
|
|
87
|
+
message: "Chat stream failed",
|
|
88
|
+
code: errorCode,
|
|
88
89
|
details: err.response?.details ?? null
|
|
89
90
|
};
|
|
90
91
|
res.write(`data: ${JSON.stringify(payload)}\n\n`);
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Controller, Get, Inject, Query, UseGuards } from "@nestjs/common";
|
|
2
|
+
import { AuthGuard } from "../common/auth.guard";
|
|
3
|
+
import { RequireAuthRealm } from "../common/auth-realm.decorator";
|
|
4
|
+
import { AppLoggerService } from "../common/app-logger.service";
|
|
5
|
+
|
|
6
|
+
@UseGuards(AuthGuard)
|
|
7
|
+
@RequireAuthRealm("admin")
|
|
8
|
+
@Controller("admin/logs")
|
|
9
|
+
export class AdminLogsController {
|
|
10
|
+
constructor(@Inject(AppLoggerService) private readonly logs: AppLoggerService) {}
|
|
11
|
+
|
|
12
|
+
@Get()
|
|
13
|
+
list(
|
|
14
|
+
@Query("level") level: "info" | "error" | undefined,
|
|
15
|
+
@Query("search") search: string | undefined,
|
|
16
|
+
@Query("from") from: string | undefined,
|
|
17
|
+
@Query("to") to: string | undefined,
|
|
18
|
+
@Query("page") page: string | undefined,
|
|
19
|
+
@Query("limit") limit: string | undefined
|
|
20
|
+
) {
|
|
21
|
+
return this.logs.query({
|
|
22
|
+
level,
|
|
23
|
+
search,
|
|
24
|
+
from,
|
|
25
|
+
to,
|
|
26
|
+
page: Number(page ?? 1),
|
|
27
|
+
limit: Number(limit ?? 50)
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
@@ -74,6 +74,17 @@ export class AdminPluginsService {
|
|
|
74
74
|
};
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
+
getDashboardWidgets() {
|
|
78
|
+
return pluginRuntime
|
|
79
|
+
.getAdminUiExtensions()
|
|
80
|
+
.filter((item) => item.kind === "widget")
|
|
81
|
+
.map((item) => ({
|
|
82
|
+
id: item.id,
|
|
83
|
+
title: item.title,
|
|
84
|
+
config: item.config ?? {}
|
|
85
|
+
}));
|
|
86
|
+
}
|
|
87
|
+
|
|
77
88
|
private writeManifest(manifest: PluginManifest) {
|
|
78
89
|
const path = resolveWritableManifestPath();
|
|
79
90
|
const parsed = pluginManifestSchema.safeParse(manifest);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { BadRequestException, ForbiddenException, Inject, Injectable, NotFoundException } from "@nestjs/common";
|
|
1
|
+
import { BadRequestException, ForbiddenException, HttpException, Inject, Injectable, NotFoundException } from "@nestjs/common";
|
|
2
2
|
import { Prisma } from "@prisma/client";
|
|
3
|
+
import { defaultFileValidation } from "@openadminjs/storage";
|
|
3
4
|
import type { ResourceConfig, ResourceField } from "@openadminjs/core";
|
|
4
5
|
import {
|
|
5
6
|
listScopeWhereClause,
|
|
@@ -9,7 +10,10 @@ import {
|
|
|
9
10
|
} from "@openadminjs/core";
|
|
10
11
|
import bcrypt from "bcryptjs";
|
|
11
12
|
import { randomBytes } from "node:crypto";
|
|
13
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
14
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
12
15
|
import { PrismaService } from "../common/prisma.service";
|
|
16
|
+
import { pluginRuntime } from "../plugins/plugin-runtime";
|
|
13
17
|
import { getResource, resources } from "../resources/registry";
|
|
14
18
|
import {
|
|
15
19
|
runAfterCreate,
|
|
@@ -54,6 +58,48 @@ export class AdminResourceService {
|
|
|
54
58
|
});
|
|
55
59
|
}
|
|
56
60
|
|
|
61
|
+
async globalSearch(
|
|
62
|
+
query: string,
|
|
63
|
+
user: UserContext,
|
|
64
|
+
opts?: { perResourceLimit?: number; resources?: string[] }
|
|
65
|
+
): Promise<Array<{ resource: string; resourceLabel: string; id: string; title: string }>> {
|
|
66
|
+
const q = query.trim();
|
|
67
|
+
if (q.length < 2) return [];
|
|
68
|
+
const perResourceLimit = Math.min(Math.max(opts?.perResourceLimit ?? 5, 1), 20);
|
|
69
|
+
const whitelist = opts?.resources ? new Set(opts.resources.map((v) => v.toLowerCase())) : null;
|
|
70
|
+
const out: Array<{ resource: string; resourceLabel: string; id: string; title: string }> = [];
|
|
71
|
+
|
|
72
|
+
for (const resource of resources) {
|
|
73
|
+
if (whitelist && !whitelist.has(resource.name.toLowerCase())) continue;
|
|
74
|
+
if (!this.has(user, resource.permissions.read)) continue;
|
|
75
|
+
const searchable = Object.entries(resource.fields).filter(([, f]) => f.searchable).map(([name]) => name);
|
|
76
|
+
if (!searchable.length) continue;
|
|
77
|
+
|
|
78
|
+
const scope = shouldApplyListScope(resource, user.permissions) ? listScopeWhereClause(resource, user.id) : undefined;
|
|
79
|
+
const where = mergeWhereClauses(
|
|
80
|
+
{
|
|
81
|
+
OR: searchable.map((field) => ({ [field]: { contains: q, mode: "insensitive" } }))
|
|
82
|
+
},
|
|
83
|
+
scope
|
|
84
|
+
);
|
|
85
|
+
const rows = await this.delegate(resource).findMany({
|
|
86
|
+
where,
|
|
87
|
+
take: perResourceLimit,
|
|
88
|
+
orderBy: this.buildOrderBy(resource, "createdAt:desc")
|
|
89
|
+
});
|
|
90
|
+
for (const row of rows) {
|
|
91
|
+
const safe = this.sanitizeRecord(resource, row) as Record<string, unknown>;
|
|
92
|
+
const id = String(safe.id ?? "");
|
|
93
|
+
if (!id) continue;
|
|
94
|
+
const tf = resource.titleField ?? "id";
|
|
95
|
+
const title = String(safe[tf] ?? safe.name ?? safe.title ?? id);
|
|
96
|
+
out.push({ resource: resource.name, resourceLabel: String(resource.label), id, title });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return out.slice(0, 60);
|
|
101
|
+
}
|
|
102
|
+
|
|
57
103
|
async list(name: string, query: Record<string, unknown>, user: UserContext) {
|
|
58
104
|
const resource = this.authorizedResource(name, user, "read");
|
|
59
105
|
const delegate = this.delegate(resource);
|
|
@@ -203,6 +249,194 @@ export class AdminResourceService {
|
|
|
203
249
|
throw new NotFoundException({ message: "Action not implemented for this resource", code: "ACTION_NOT_IMPLEMENTED" });
|
|
204
250
|
}
|
|
205
251
|
|
|
252
|
+
async bulk(
|
|
253
|
+
name: string,
|
|
254
|
+
dto: { action: string; ids: string[]; input?: Record<string, unknown> },
|
|
255
|
+
user: UserContext
|
|
256
|
+
): Promise<{ ok: number; failures: { id: string; message: string }[] }> {
|
|
257
|
+
const uniqueIds = [...new Set(dto.ids.map(String).filter(Boolean))];
|
|
258
|
+
if (!uniqueIds.length) throw new BadRequestException({ message: "No ids provided", code: "BULK_EMPTY" });
|
|
259
|
+
|
|
260
|
+
const failures: { id: string; message: string }[] = [];
|
|
261
|
+
let ok = 0;
|
|
262
|
+
|
|
263
|
+
if (dto.action === "delete") {
|
|
264
|
+
this.authorizedResource(name, user, "delete");
|
|
265
|
+
for (const id of uniqueIds) {
|
|
266
|
+
try {
|
|
267
|
+
await this.delete(name, id, user);
|
|
268
|
+
ok += 1;
|
|
269
|
+
} catch (err: unknown) {
|
|
270
|
+
failures.push({ id, message: this.bulkErrorMessage(err) });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return { ok, failures };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const resource = getResource(name);
|
|
277
|
+
const config = resource?.actions?.[dto.action];
|
|
278
|
+
if (!resource || !config?.handler) {
|
|
279
|
+
throw new NotFoundException({ message: "Action not found", code: "ACTION_NOT_FOUND" });
|
|
280
|
+
}
|
|
281
|
+
if (!this.has(user, config.permission)) throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
|
|
282
|
+
|
|
283
|
+
for (const id of uniqueIds) {
|
|
284
|
+
try {
|
|
285
|
+
await this.action(name, id, dto.action, user, dto.input);
|
|
286
|
+
ok += 1;
|
|
287
|
+
} catch (err: unknown) {
|
|
288
|
+
failures.push({ id, message: this.bulkErrorMessage(err) });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return { ok, failures };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async reorder(name: string, orderedIds: string[], user: UserContext, baseIndex = 0): Promise<{ ok: true }> {
|
|
295
|
+
const resource = this.authorizedResource(name, user, "update");
|
|
296
|
+
const orderField = resource.fields.order;
|
|
297
|
+
if (!orderField || orderField.type !== "number" || orderField.edit === false) {
|
|
298
|
+
throw new BadRequestException({ message: "Resource does not support drag-and-drop ordering", code: "REORDER_UNSUPPORTED" });
|
|
299
|
+
}
|
|
300
|
+
const uniqueIds = [...new Set(orderedIds.map(String).filter(Boolean))];
|
|
301
|
+
if (!uniqueIds.length) throw new BadRequestException({ message: "No ids provided", code: "REORDER_EMPTY" });
|
|
302
|
+
|
|
303
|
+
const delegate = this.delegate(resource);
|
|
304
|
+
const rows = await delegate.findMany({ where: { id: { in: uniqueIds } } });
|
|
305
|
+
if (rows.length !== uniqueIds.length) {
|
|
306
|
+
throw new BadRequestException({ message: "One or more records were not found", code: "REORDER_IDS_INVALID" });
|
|
307
|
+
}
|
|
308
|
+
for (const row of rows) {
|
|
309
|
+
if (this.isOutOfListScope(resource, user, row)) {
|
|
310
|
+
throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
await this.prisma.$transaction(async (tx) => {
|
|
315
|
+
const txDelegate = (tx as unknown as Record<string, PrismaDelegate>)[resource.model];
|
|
316
|
+
if (!txDelegate) throw new NotFoundException({ message: "Prisma model not found", code: "MODEL_NOT_FOUND" });
|
|
317
|
+
for (let i = 0; i < uniqueIds.length; i++) {
|
|
318
|
+
await txDelegate.update({
|
|
319
|
+
where: { id: uniqueIds[i] },
|
|
320
|
+
data: { order: baseIndex + i }
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
await this.prisma.auditLog.create({
|
|
326
|
+
data: {
|
|
327
|
+
userId: user.id,
|
|
328
|
+
resource: name,
|
|
329
|
+
resourceId: uniqueIds[0],
|
|
330
|
+
action: "reorder",
|
|
331
|
+
before: { ids: uniqueIds, previous: rows.map((r) => ({ id: (r as { id: string }).id, order: (r as { order?: number }).order })) } as object,
|
|
332
|
+
after: { ids: uniqueIds, baseIndex, order: uniqueIds.map((id, index) => ({ id, order: baseIndex + index })) } as object
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
return { ok: true };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async uploadFile(
|
|
340
|
+
input: { filename: string; mimeType: string; contentBase64: string; targetPath?: string },
|
|
341
|
+
user: UserContext
|
|
342
|
+
): Promise<Record<string, unknown>> {
|
|
343
|
+
const filesResource = this.authorizedResource("files", user, "create");
|
|
344
|
+
const filename = String(input.filename ?? "").trim();
|
|
345
|
+
const mimeType = String(input.mimeType ?? "").trim().toLowerCase();
|
|
346
|
+
const rawBase64 = String(input.contentBase64 ?? "").trim();
|
|
347
|
+
if (!filename || !mimeType || !rawBase64) {
|
|
348
|
+
throw new BadRequestException({ message: "filename, mimeType and contentBase64 are required", code: "UPLOAD_INVALID" });
|
|
349
|
+
}
|
|
350
|
+
if (!defaultFileValidation.mimeTypes.includes(mimeType)) {
|
|
351
|
+
throw new BadRequestException({ message: "MIME type is not allowed", code: "UPLOAD_MIME_DENIED" });
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
let contentBase64 = rawBase64;
|
|
355
|
+
for (const mediaHook of pluginRuntime.getMediaHooks()) {
|
|
356
|
+
await mediaHook.beforeStore?.({
|
|
357
|
+
filename,
|
|
358
|
+
mimeType,
|
|
359
|
+
size: Math.floor((contentBase64.length * 3) / 4),
|
|
360
|
+
contentBase64,
|
|
361
|
+
user: { ...user, email: user.email ?? "" }
|
|
362
|
+
});
|
|
363
|
+
const transformed = await mediaHook.transform?.({
|
|
364
|
+
filename,
|
|
365
|
+
mimeType,
|
|
366
|
+
contentBase64,
|
|
367
|
+
user: { ...user, email: user.email ?? "" }
|
|
368
|
+
});
|
|
369
|
+
if (transformed) {
|
|
370
|
+
contentBase64 = transformed.contentBase64;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const fileBuffer = Buffer.from(contentBase64, "base64");
|
|
375
|
+
if (fileBuffer.byteLength > defaultFileValidation.maxSizeBytes) {
|
|
376
|
+
throw new BadRequestException({ message: "File is too large", code: "UPLOAD_TOO_LARGE" });
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const now = Date.now();
|
|
380
|
+
const safeFilename = filename.replace(/[^a-zA-Z0-9._-]+/g, "_");
|
|
381
|
+
const relPath = this.resolveStorageRelativePath(input.targetPath, `uploads/${now}-${safeFilename}`);
|
|
382
|
+
const absPath = join(process.cwd(), relPath);
|
|
383
|
+
await mkdir(dirname(absPath), { recursive: true });
|
|
384
|
+
await writeFile(absPath, fileBuffer);
|
|
385
|
+
|
|
386
|
+
const record = await this.create(
|
|
387
|
+
"files",
|
|
388
|
+
{ filename, path: relPath, mimeType, size: fileBuffer.byteLength },
|
|
389
|
+
user
|
|
390
|
+
);
|
|
391
|
+
|
|
392
|
+
for (const mediaHook of pluginRuntime.getMediaHooks()) {
|
|
393
|
+
await mediaHook.afterStore?.({
|
|
394
|
+
fileId: String((record as Record<string, unknown>).id ?? ""),
|
|
395
|
+
filename,
|
|
396
|
+
mimeType,
|
|
397
|
+
size: fileBuffer.byteLength,
|
|
398
|
+
user: { ...user, email: user.email ?? "" }
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
return record as Record<string, unknown>;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Resolve a relative storage path strictly under {@link process.cwd} (no traversal, no absolute paths).
|
|
407
|
+
*/
|
|
408
|
+
private resolveStorageRelativePath(targetPath: string | undefined, fallbackRelative: string): string {
|
|
409
|
+
const raw = (targetPath?.trim() || fallbackRelative).replace(/^[\\/]+/, "");
|
|
410
|
+
if (!raw || raw.includes("\0")) {
|
|
411
|
+
throw new BadRequestException({ message: "Invalid storage path", code: "UPLOAD_PATH_INVALID" });
|
|
412
|
+
}
|
|
413
|
+
if (raw.split(/[/\\]/).some((seg) => seg === "..")) {
|
|
414
|
+
throw new BadRequestException({ message: "Path traversal is not allowed", code: "UPLOAD_PATH_INVALID" });
|
|
415
|
+
}
|
|
416
|
+
const cwd = resolve(process.cwd());
|
|
417
|
+
const absolute = resolve(cwd, raw);
|
|
418
|
+
const rel = relative(cwd, absolute);
|
|
419
|
+
if (!rel || rel.startsWith("..") || rel === "..") {
|
|
420
|
+
throw new BadRequestException({ message: "Path must stay within project directory", code: "UPLOAD_PATH_INVALID" });
|
|
421
|
+
}
|
|
422
|
+
return rel.replace(/\\/g, "/");
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
private bulkErrorMessage(err: unknown): string {
|
|
426
|
+
if (err instanceof HttpException) {
|
|
427
|
+
const r = err.getResponse();
|
|
428
|
+
if (typeof r === "string") return r;
|
|
429
|
+
if (r && typeof r === "object" && "message" in r) {
|
|
430
|
+
const m = (r as { message: unknown }).message;
|
|
431
|
+
if (Array.isArray(m)) return m.join(", ");
|
|
432
|
+
if (typeof m === "string") return m;
|
|
433
|
+
}
|
|
434
|
+
return err.message;
|
|
435
|
+
}
|
|
436
|
+
if (err instanceof Error) return err.message;
|
|
437
|
+
return "Request failed";
|
|
438
|
+
}
|
|
439
|
+
|
|
206
440
|
private isOutOfListScope(resource: ResourceConfig, user: UserContext, record: unknown): boolean {
|
|
207
441
|
if (!shouldApplyListScope(resource, user.permissions)) return false;
|
|
208
442
|
const clause = listScopeWhereClause(resource, user.id);
|
|
@@ -4,6 +4,9 @@ import { RequireAuthRealm } from "../common/auth-realm.decorator";
|
|
|
4
4
|
import { CurrentUser } from "../common/current-user.decorator";
|
|
5
5
|
import { AdminResourceService } from "./admin-resource.service";
|
|
6
6
|
import { AdminAnalyticsService } from "./admin-analytics.service";
|
|
7
|
+
import { ResourceBulkDto } from "./dto/resource-bulk.dto";
|
|
8
|
+
import { ResourceReorderDto } from "./dto/resource-reorder.dto";
|
|
9
|
+
import { ResourceUploadDto } from "./dto/resource-upload.dto";
|
|
7
10
|
import { PaymentService } from "../store/payment/payment.service";
|
|
8
11
|
|
|
9
12
|
type UserContext = { id: string; email?: string; permissions: string[] };
|
|
@@ -28,11 +31,43 @@ export class AdminController {
|
|
|
28
31
|
return this.resources.listResources(user, locale);
|
|
29
32
|
}
|
|
30
33
|
|
|
34
|
+
@Get("search")
|
|
35
|
+
search(
|
|
36
|
+
@Query("q") q: string | undefined,
|
|
37
|
+
@Query("limit") limit: string | undefined,
|
|
38
|
+
@CurrentUser() user: UserContext
|
|
39
|
+
) {
|
|
40
|
+
return this.resources.globalSearch(q ?? "", user, { perResourceLimit: Number(limit ?? 5) });
|
|
41
|
+
}
|
|
42
|
+
|
|
31
43
|
@Get(":resource")
|
|
32
44
|
list(@Param("resource") resource: string, @Query() query: Record<string, unknown>, @CurrentUser() user: UserContext) {
|
|
33
45
|
return this.resources.list(resource, query, user);
|
|
34
46
|
}
|
|
35
47
|
|
|
48
|
+
@Post(":resource/bulk")
|
|
49
|
+
bulk(
|
|
50
|
+
@Param("resource") resource: string,
|
|
51
|
+
@Body() body: ResourceBulkDto,
|
|
52
|
+
@CurrentUser() user: UserContext
|
|
53
|
+
) {
|
|
54
|
+
return this.resources.bulk(resource, body, user);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
@Post(":resource/reorder")
|
|
58
|
+
reorder(
|
|
59
|
+
@Param("resource") resource: string,
|
|
60
|
+
@Body() body: ResourceReorderDto,
|
|
61
|
+
@CurrentUser() user: UserContext
|
|
62
|
+
) {
|
|
63
|
+
return this.resources.reorder(resource, body.ids, user, body.baseIndex ?? 0);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
@Post("files/upload")
|
|
67
|
+
uploadFile(@Body() body: ResourceUploadDto, @CurrentUser() user: UserContext) {
|
|
68
|
+
return this.resources.uploadFile(body, user);
|
|
69
|
+
}
|
|
70
|
+
|
|
36
71
|
@Get(":resource/:id")
|
|
37
72
|
get(@Param("resource") resource: string, @Param("id") id: string, @CurrentUser() user: UserContext) {
|
|
38
73
|
return this.resources.get(resource, id, user);
|