openadminjs 0.2.0 → 0.3.0-rc.1
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/README.md +106 -151
- package/dist/adapt-package-manager.js +4 -1
- package/dist/create-project.d.ts +46 -0
- package/dist/create-project.js +417 -150
- package/dist/doctor.d.ts +13 -0
- package/dist/doctor.js +35 -6
- package/dist/index.d.ts +1 -0
- package/dist/index.js +257 -39
- package/dist/render-schema.d.ts +0 -17
- package/dist/render-schema.js +25 -29
- package/dist/resource-slug.d.ts +1 -0
- package/dist/resource-slug.js +7 -0
- package/dist/runtime-mode.d.ts +16 -0
- package/dist/runtime-mode.js +138 -0
- package/dist/upgrade.d.ts +10 -0
- package/dist/upgrade.js +133 -0
- package/package.json +14 -11
- package/template/.dockerignore +15 -0
- package/template/.env.production.example +5 -0
- package/template/Dockerfile +12 -0
- package/template/README.md +4 -3
- package/template/apps/admin/app/api/auth/login/route.ts +9 -9
- package/template/apps/admin/app/api/auth/logout/route.ts +11 -3
- package/template/apps/admin/app/api/auth/oidc/callback/route.ts +19 -0
- package/template/apps/admin/app/api/auth/oidc/start/route.ts +11 -0
- package/template/apps/admin/app/api/auth/oidc/status/route.ts +6 -0
- package/template/apps/admin/app/api/auth/refresh/route.ts +18 -11
- package/template/apps/admin/app/api/backend/[...path]/route.ts +48 -0
- package/template/apps/admin/app/api-tokens/page.tsx +39 -39
- package/template/apps/admin/app/assistant/page.tsx +11 -0
- package/template/apps/admin/app/dashboard/page.tsx +45 -462
- package/template/apps/admin/app/globals.css +52 -16
- package/template/apps/admin/app/layout.tsx +1 -1
- package/template/apps/admin/app/login/page.tsx +13 -145
- package/template/apps/admin/app/plugins/page.tsx +16 -402
- package/template/apps/admin/app/profile/page.tsx +5 -2
- package/template/apps/admin/app/settings/page.tsx +14 -265
- package/template/apps/admin/components/ai-assistant-widget.tsx +3 -6
- package/template/apps/admin/components/app-shell.tsx +25 -373
- package/template/apps/admin/components/auth-guard.tsx +8 -28
- package/template/apps/admin/components/logo.tsx +1 -30
- package/template/apps/admin/components/resource-form.tsx +3 -3
- package/template/apps/admin/components/resource-table.tsx +12 -8
- package/template/apps/admin/lib/api.ts +45 -107
- package/template/apps/admin/lib/resource-table-prefs.ts +1 -57
- package/template/apps/admin/lib/server-api.ts +7 -0
- package/template/apps/admin/lib/tokens.ts +9 -81
- package/template/apps/admin/middleware.ts +9 -50
- package/template/apps/admin/next.config.mjs +4 -0
- package/template/apps/admin/package.json +2 -1
- package/template/apps/admin/public/brand/favicon.svg +4 -1
- package/template/apps/admin/tailwind.config.ts +9 -8
- package/template/apps/api/package.json +10 -6
- package/template/apps/api/src/access/catalog.ts +4 -0
- package/template/apps/api/src/admin/admin-ai.controller.ts +15 -125
- package/template/apps/api/src/admin/admin-analytics.service.ts +16 -148
- package/template/apps/api/src/admin/admin-logs.controller.ts +4 -1
- package/template/apps/api/src/admin/admin-plugins.controller.ts +8 -8
- package/template/apps/api/src/admin/admin-plugins.service.ts +15 -259
- package/template/apps/api/src/admin/admin-resource.service.ts +105 -254
- package/template/apps/api/src/admin/admin.controller.ts +17 -4
- package/template/apps/api/src/admin/admin.module.ts +2 -2
- package/template/apps/api/src/admin/resource-policy.ts +1 -0
- package/template/apps/api/src/admin/resource-query.ts +1 -0
- package/template/apps/api/src/admin/safe-ai.service.ts +43 -0
- package/template/apps/api/src/admin/validate-resource-payload.ts +2 -0
- package/template/apps/api/src/auth/auth.controller.ts +4 -2
- package/template/apps/api/src/auth/auth.service.ts +68 -83
- package/template/apps/api/src/auth/sso-oidc.controller.ts +12 -74
- package/template/apps/api/src/auth/sso-oidc.service.ts +51 -268
- package/template/apps/api/src/common/api-exception.filter.ts +1 -0
- package/template/apps/api/src/common/auth.guard.ts +66 -39
- package/template/apps/api/src/common/json-field-codec.ts +12 -13
- package/template/apps/api/src/common/prisma.service.ts +9 -17
- package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
- package/template/apps/api/src/graphql/graphql.module.ts +5 -4
- package/template/apps/api/src/health/health.controller.ts +6 -0
- package/template/apps/api/src/main.ts +11 -2
- package/template/apps/api/src/plugins/plugin-loader.ts +5 -3
- package/template/apps/api/src/resources/commerce.resource.ts +3 -34
- package/template/apps/api/src/resources/operations.resource.ts +1 -0
- package/template/apps/api/src/store/payment/payment.controller.ts +15 -92
- package/template/apps/api/src/store/payment/payment.module.ts +2 -3
- package/template/apps/api/src/store/payment/payment.service.ts +121 -227
- package/template/apps/api/webpack.config.cjs +2 -1
- package/template/apps/web/next.config.mjs +4 -0
- package/template/apps/web/public/brand/favicon.svg +4 -1
- package/template/compose.yaml +56 -0
- package/template/examples/crm-admin/README.md +31 -0
- package/template/examples/crm-admin/package.json +17 -0
- package/template/examples/crm-admin/prisma/models.fragment.prisma +50 -0
- package/template/examples/crm-admin/src/index.ts +7 -0
- package/template/examples/crm-admin/src/resources/activities.resource.ts +29 -0
- package/template/examples/crm-admin/src/resources/companies.resource.ts +21 -0
- package/template/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
- package/template/examples/crm-admin/src/resources/deals.resource.ts +30 -0
- package/template/examples/crm-admin/tsconfig.json +7 -0
- package/template/package.json +6 -1
- package/template/packages/admin-client/package.json +18 -0
- package/template/packages/admin-client/src/contracts.ts +29 -0
- package/template/packages/admin-client/src/index.ts +2 -0
- package/template/packages/admin-client/src/preferences.ts +57 -0
- package/template/packages/admin-client/tsconfig.json +12 -0
- package/template/packages/auth/package.json +1 -1
- package/template/packages/brand/site/assets/brand/favicon.svg +4 -1
- package/template/packages/brand/src/generate-assets.mjs +17 -186
- package/template/packages/core/package.json +1 -1
- package/template/packages/mail/package.json +1 -1
- package/template/packages/nest/package.json +22 -0
- package/template/packages/nest/src/api-exception.filter.ts +23 -0
- package/template/packages/nest/src/index.ts +3 -0
- package/template/packages/nest/src/resource-policy.ts +64 -0
- package/template/packages/nest/src/resource-query.ts +103 -0
- package/template/packages/nest/tsconfig.json +12 -0
- package/template/packages/notifications/package.json +1 -1
- package/template/packages/payments/package.json +1 -1
- package/template/packages/permissions/package.json +1 -1
- package/template/packages/permissions/src/index.ts +2 -2
- package/template/packages/plugin-sdk/package.json +1 -1
- package/template/packages/plugin-sdk/src/index.ts +2 -2
- package/template/packages/prisma/package.json +21 -0
- package/template/packages/prisma/schema/ai.prisma +36 -0
- package/template/packages/prisma/schema/audit.prisma +13 -0
- package/template/packages/prisma/schema/commerce.prisma +79 -0
- package/template/packages/prisma/schema/content.prisma +27 -0
- package/template/packages/prisma/schema/core.prisma +106 -0
- package/template/packages/prisma/schema/header.prisma +8 -0
- package/template/packages/prisma/schema/jobs.prisma +9 -0
- package/template/packages/prisma/schema/media.prisma +9 -0
- package/template/packages/prisma/schema/modules.json +47 -0
- package/template/packages/prisma/schema/notifications.prisma +9 -0
- package/template/packages/prisma/schema/settings.prisma +8 -0
- package/template/packages/prisma/schema/tokens.prisma +10 -0
- package/template/packages/prisma/src/index.d.ts +12 -0
- package/template/packages/prisma/src/index.mjs +138 -0
- package/template/packages/queue/package.json +1 -1
- package/template/packages/resource/package.json +1 -1
- package/template/packages/resource/src/index.ts +1 -0
- package/template/packages/storage/package.json +1 -1
- package/template/packages/storage/src/index.ts +37 -0
- package/template/prisma/migrations/20261126130000_add_sessions/migration.sql +26 -0
- package/template/prisma/migrations/20261126140000_api_token_hash/migration.sql +3 -0
- package/template/prisma/migrations/20261126150000_payment_idempotency/migration.sql +6 -0
- package/template/prisma/schema.prisma +82 -54
- package/template/prisma/seed.ts +14 -38
- package/template/runtime-versions.json +15 -0
- package/template/scripts/db-init.mjs +33 -0
- package/template/scripts/install-crm.mjs +50 -0
- package/template/scripts/migrate-existing.mjs +65 -0
- package/template/scripts/schema.mjs +48 -0
- package/template/tsconfig.base.json +23 -5
- package/LICENSE +0 -21
- package/dist/adapt-package-manager.test.d.ts +0 -1
- package/dist/adapt-package-manager.test.js +0 -76
- package/dist/cli.e2e.test.d.ts +0 -1
- package/dist/cli.e2e.test.js +0 -87
- package/dist/create-project.test.d.ts +0 -1
- package/dist/create-project.test.js +0 -275
- package/dist/database-providers.integration.test.d.ts +0 -1
- package/dist/database-providers.integration.test.js +0 -64
- package/dist/db-commands.test.d.ts +0 -1
- package/dist/db-commands.test.js +0 -27
- package/dist/doctor.test.d.ts +0 -1
- package/dist/doctor.test.js +0 -102
- package/dist/index.test.d.ts +0 -1
- package/dist/index.test.js +0 -11
- package/dist/render-schema.test.d.ts +0 -1
- package/dist/render-schema.test.js +0 -57
- package/dist/resource-slug.test.d.ts +0 -1
- package/dist/resource-slug.test.js +0 -9
- package/dist/secrets.test.d.ts +0 -1
- package/dist/secrets.test.js +0 -36
- package/dist/security.test.d.ts +0 -1
- package/dist/security.test.js +0 -54
- package/dist/validate-name.test.d.ts +0 -1
- package/dist/validate-name.test.js +0 -63
- package/template/apps/admin/.storybook/main.ts +0 -12
- package/template/apps/admin/.storybook/preview.ts +0 -10
- package/template/apps/admin/app/login/page.test.tsx +0 -18
- package/template/apps/admin/components/auth-guard.test.tsx +0 -55
- package/template/apps/admin/components/logo.stories.tsx +0 -24
- package/template/apps/admin/lib/api.test.ts +0 -118
- package/template/apps/admin/lib/auth-flow.e2e.test.ts +0 -79
- package/template/apps/admin/vitest.config.ts +0 -7
- package/template/apps/api/src/access/derive-permissions.test.ts +0 -26
- package/template/apps/api/src/admin/admin-resource.service.test.ts +0 -118
- package/template/apps/api/src/admin/validate-resource-payload.test.ts +0 -44
- package/template/apps/api/src/app.module.test.ts +0 -12
- package/template/apps/api/src/auth/auth.service.test.ts +0 -78
- package/template/apps/api/src/auth/sso-oidc.service.test.ts +0 -84
- package/template/apps/api/src/common/auth.guard.test.ts +0 -62
- package/template/apps/api/src/common/casl-ability.factory.test.ts +0 -33
- package/template/apps/api/src/common/json-field-codec.test.ts +0 -76
- package/template/apps/api/src/common/prisma.service.test.ts +0 -19
- package/template/apps/api/src/common/request-logging.interceptor.test.ts +0 -39
- package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +0 -45
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +0 -44
- package/template/apps/api/src/graphql/graphql-apollo-config.test.ts +0 -26
- package/template/apps/api/src/graphql/graphql-schema.test.ts +0 -26
- package/template/apps/api/src/plugins/manifest.schema.test.ts +0 -36
- package/template/apps/api/src/plugins/plugin-runtime.test.ts +0 -24
- package/template/apps/api/src/queue/queue.service.test.ts +0 -33
- package/template/apps/api/src/resources/resource-hooks.registry.test.ts +0 -72
- package/template/apps/api/vitest.config.ts +0 -21
- package/template/apps/web/lib/seo.test.ts +0 -41
- package/template/apps/web/vitest.config.ts +0 -19
- package/template/packages/auth/src/index.test.ts +0 -10
- package/template/packages/brand/src/index.test.ts +0 -9
- package/template/packages/core/src/index.test.ts +0 -27
- package/template/packages/core/vitest.config.ts +0 -9
- package/template/packages/mail/src/index.test.ts +0 -23
- package/template/packages/notifications/src/index.test.ts +0 -9
- package/template/packages/permissions/src/blueprints.test.ts +0 -62
- package/template/packages/permissions/src/index.test.ts +0 -34
- package/template/packages/plugin-sdk/src/sdk.test.ts +0 -13
- package/template/packages/plugin-sdk/vitest.config.ts +0 -5
- package/template/packages/queue/src/index.test.ts +0 -12
- package/template/packages/resource/src/index.test.ts +0 -196
- package/template/packages/storage/src/index.test.ts +0 -10
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import type { Request, Response, NextFunction } from "express";
|
|
4
|
+
import { ApiExceptionFilter } from "./common/api-exception.filter";
|
|
2
5
|
import cookieParser from "cookie-parser";
|
|
3
6
|
import helmet from "helmet";
|
|
7
|
+
import type { NestExpressApplication } from "@nestjs/platform-express";
|
|
4
8
|
import { NestFactory } from "@nestjs/core";
|
|
5
9
|
import { ValidationPipe } from "@nestjs/common";
|
|
6
10
|
import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger";
|
|
7
11
|
import { AppModule } from "./app.module";
|
|
8
12
|
|
|
9
13
|
async function bootstrap() {
|
|
10
|
-
const app = await NestFactory.create(AppModule);
|
|
14
|
+
const app = await NestFactory.create<NestExpressApplication>(AppModule, { rawBody: true });
|
|
15
|
+
app.use((_req:Request,res:Response,next:NextFunction)=>{res.setHeader("x-request-id",randomUUID());next();});
|
|
16
|
+
app.useGlobalFilters(new ApiExceptionFilter());
|
|
17
|
+
app.useBodyParser("json", { limit: "15mb" });
|
|
11
18
|
app.use(cookieParser());
|
|
12
19
|
app.use(helmet());
|
|
13
20
|
const prodOrigins = (process.env.ADMIN_ORIGIN ?? "")
|
|
@@ -24,6 +31,8 @@ async function bootstrap() {
|
|
|
24
31
|
credentials: true
|
|
25
32
|
});
|
|
26
33
|
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
|
|
34
|
+
// Flush DB connections / queues on SIGTERM/SIGINT so restarts are clean.
|
|
35
|
+
app.enableShutdownHooks();
|
|
27
36
|
|
|
28
37
|
const config = new DocumentBuilder()
|
|
29
38
|
.setTitle("OpenAdminJS API")
|
|
@@ -31,7 +40,7 @@ async function bootstrap() {
|
|
|
31
40
|
.setVersion("0.1.0")
|
|
32
41
|
.addBearerAuth()
|
|
33
42
|
.build();
|
|
34
|
-
SwaggerModule.setup("api/docs", app, SwaggerModule.createDocument(app, config));
|
|
43
|
+
if (process.env.NODE_ENV !== "production" || process.env.OPENADMIN_SWAGGER === "1") SwaggerModule.setup("api/docs", app, SwaggerModule.createDocument(app, config));
|
|
35
44
|
|
|
36
45
|
await app.listen(Number(process.env.API_PORT ?? 4000));
|
|
37
46
|
}
|
|
@@ -62,7 +62,6 @@ function createContext(entry: PluginManifestEntry): PluginRegistrationContext {
|
|
|
62
62
|
const config = (entry.config ?? {}) as Record<string, unknown>;
|
|
63
63
|
const capabilities = new Set(entry.capabilities ?? []);
|
|
64
64
|
const ensureCap = (name: string) => {
|
|
65
|
-
if ((entry.trustMode ?? "trusted") === "trusted" && capabilities.size === 0) return;
|
|
66
65
|
if (!capabilities.has(name as never)) {
|
|
67
66
|
throw new Error(`Plugin "${entry.id}" attempted to use capability "${name}" but it is not declared in manifest.`);
|
|
68
67
|
}
|
|
@@ -87,8 +86,10 @@ function createContext(entry: PluginManifestEntry): PluginRegistrationContext {
|
|
|
87
86
|
config,
|
|
88
87
|
trustMode: entry.trustMode ?? "trusted",
|
|
89
88
|
capabilities: [...capabilities],
|
|
90
|
-
registerResourceHooks: (resourceName, hooks, options) =>
|
|
91
|
-
|
|
89
|
+
registerResourceHooks: (resourceName, hooks, options) => {
|
|
90
|
+
ensureCap("resource.hooks");
|
|
91
|
+
registerResourceHooks(resourceName, hooks, { ...options, source: entry.id });
|
|
92
|
+
},
|
|
92
93
|
registerSurface
|
|
93
94
|
};
|
|
94
95
|
}
|
|
@@ -96,6 +97,7 @@ function createContext(entry: PluginManifestEntry): PluginRegistrationContext {
|
|
|
96
97
|
/** Register hooks for one manifest entry (same as bootstrap). Throws on failure. */
|
|
97
98
|
export async function applyManifestPluginEntry(entry: PluginManifestEntry): Promise<void> {
|
|
98
99
|
if (entry.enabled === false) return;
|
|
100
|
+
if (entry.trustMode === "sandboxed") throw new Error("Sandboxed plugins are unsupported: Node modules are not isolated");
|
|
99
101
|
const plugin: OpenAdminPlugin = entry.bundled ? resolveBundledPlugin(entry) : resolveNpmPlugin(entry);
|
|
100
102
|
const ctx = createContext(entry);
|
|
101
103
|
await plugin.register(ctx as PluginRegistrationContext);
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { PrismaClient } from "@prisma/client";
|
|
2
1
|
import { defineResource } from "@openadminjs/core";
|
|
3
2
|
|
|
4
3
|
export const productsResource = defineResource({
|
|
@@ -58,7 +57,9 @@ export const ordersResource = defineResource({
|
|
|
58
57
|
status: {
|
|
59
58
|
type: "badge",
|
|
60
59
|
label: { en: "Status", ru: "Статус" },
|
|
61
|
-
options: ["pending", "paid", "failed", "refunded", "cancelled"],
|
|
60
|
+
options: ["pending", "paid", "failed", "refund_pending", "refunded", "cancelled"],
|
|
61
|
+
edit: false,
|
|
62
|
+
create: false,
|
|
62
63
|
filterable: true,
|
|
63
64
|
sortable: true
|
|
64
65
|
},
|
|
@@ -66,38 +67,6 @@ export const ordersResource = defineResource({
|
|
|
66
67
|
currency: { type: "text", label: "Currency", edit: false },
|
|
67
68
|
notes: { type: "textarea", label: { en: "Notes", ru: "Заметки" }, list: false },
|
|
68
69
|
createdAt: { type: "datetime", label: { en: "Created", ru: "Создан" }, create: false, edit: false, sortable: true }
|
|
69
|
-
},
|
|
70
|
-
actions: {
|
|
71
|
-
refund: {
|
|
72
|
-
label: { en: "Refund", ru: "Возврат" },
|
|
73
|
-
variant: "destructive",
|
|
74
|
-
confirm: true,
|
|
75
|
-
permission: "orders.refund",
|
|
76
|
-
async handler(ctx) {
|
|
77
|
-
const db = ctx.prisma as PrismaClient;
|
|
78
|
-
const order = await db.order.findUnique({
|
|
79
|
-
where: { id: ctx.id },
|
|
80
|
-
include: { transactions: true }
|
|
81
|
-
});
|
|
82
|
-
if (!order || order.status !== "paid") {
|
|
83
|
-
throw new Error("Order is not paid or not found");
|
|
84
|
-
}
|
|
85
|
-
return db.order.update({ where: { id: ctx.id }, data: { status: "refunded" } });
|
|
86
|
-
}
|
|
87
|
-
},
|
|
88
|
-
cancel: {
|
|
89
|
-
label: { en: "Cancel", ru: "Отменить" },
|
|
90
|
-
variant: "destructive",
|
|
91
|
-
confirm: true,
|
|
92
|
-
permission: "orders.update",
|
|
93
|
-
async handler(ctx) {
|
|
94
|
-
const db = ctx.prisma as PrismaClient;
|
|
95
|
-
return db.order.update({
|
|
96
|
-
where: { id: ctx.id },
|
|
97
|
-
data: { status: "cancelled" }
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
70
|
}
|
|
102
71
|
});
|
|
103
72
|
|
|
@@ -7,6 +7,7 @@ export const apiTokensResource = defineResource({
|
|
|
7
7
|
model: "apiToken",
|
|
8
8
|
titleField: "name",
|
|
9
9
|
icon: "KeyRound",
|
|
10
|
+
listScope: { type: "userOwns", field: "userId", bypassPermissions: [] },
|
|
10
11
|
i18n: { defaultLocale: "en", locales: ["en", "ru"] },
|
|
11
12
|
permissions: {
|
|
12
13
|
read: "api-tokens.read",
|
|
@@ -1,99 +1,22 @@
|
|
|
1
|
-
import {
|
|
2
|
-
Body,
|
|
3
|
-
Controller,
|
|
4
|
-
Get,
|
|
5
|
-
Headers,
|
|
6
|
-
Inject,
|
|
7
|
-
Param,
|
|
8
|
-
Post,
|
|
9
|
-
Query,
|
|
10
|
-
Req,
|
|
11
|
-
UseGuards
|
|
12
|
-
} from "@nestjs/common";
|
|
1
|
+
import { Body,Controller,Get,Post,Param,Query,Headers,Inject,Req,UseGuards,ForbiddenException,BadRequestException } from "@nestjs/common";
|
|
13
2
|
import type { RawBodyRequest } from "@nestjs/common";
|
|
3
|
+
import type { Request } from "express";
|
|
14
4
|
import { AuthGuard } from "../../common/auth.guard";
|
|
15
5
|
import { CurrentUser } from "../../common/current-user.decorator";
|
|
6
|
+
import { RequireAuthRealm } from "../../common/auth-realm.decorator";
|
|
16
7
|
import { PaymentService } from "./payment.service";
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
type UserContext = { id: string; email?: string; permissions: string[] };
|
|
20
|
-
type RequestLike = { user?: UserContext; rawBody?: Buffer };
|
|
21
|
-
|
|
8
|
+
type User={id:string;email?:string;permissions:string[]};
|
|
9
|
+
const requirePermission=(u:User,p:string)=>{if(!u.permissions.includes(p)&&!u.permissions.includes("*"))throw new ForbiddenException("Missing permission");};
|
|
22
10
|
@Controller("store")
|
|
23
11
|
export class PaymentController {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
@Get("products")
|
|
35
|
-
products() {
|
|
36
|
-
return this.paymentService.listProducts(true);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* POST /store/checkout
|
|
41
|
-
* Create an order + payment session.
|
|
42
|
-
* Works for guests (no auth) and authenticated users.
|
|
43
|
-
*/
|
|
44
|
-
@Post("checkout")
|
|
45
|
-
checkout(
|
|
46
|
-
@Body() body: CreateOrderInput & { guestEmail?: string },
|
|
47
|
-
@Req() req: RequestLike
|
|
48
|
-
) {
|
|
49
|
-
return this.paymentService.createCheckout({
|
|
50
|
-
...body,
|
|
51
|
-
userId: req.user?.id,
|
|
52
|
-
email: body.email ?? body.guestEmail ?? req.user?.email
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* GET /store/orders/:id/status
|
|
58
|
-
* Public order status check (e.g. success page after redirect).
|
|
59
|
-
*/
|
|
60
|
-
@Get("orders/:id/status")
|
|
61
|
-
orderStatus(@Param("id") id: string) {
|
|
62
|
-
return this.paymentService.getOrderStatus(id);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* POST /store/webhook/:provider
|
|
67
|
-
* Receive payment events from the provider.
|
|
68
|
-
* Authentication is signature-based (handled in PaymentService).
|
|
69
|
-
*/
|
|
70
|
-
@Post("webhook/:provider")
|
|
71
|
-
webhook(
|
|
72
|
-
@Param("provider") provider: string,
|
|
73
|
-
@Headers("stripe-signature") stripeSignature: string | undefined,
|
|
74
|
-
@Headers("x-webhook-signature") genericSignature: string | undefined,
|
|
75
|
-
@Req() req: RawBodyRequest<RequestLike>
|
|
76
|
-
) {
|
|
77
|
-
const signature = stripeSignature ?? genericSignature ?? "";
|
|
78
|
-
const rawBody = req.rawBody ?? Buffer.from("{}");
|
|
79
|
-
return this.paymentService.handleWebhook(provider, rawBody, signature);
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// ──────────────────────────────────────────────
|
|
83
|
-
// Authenticated user endpoints
|
|
84
|
-
// ──────────────────────────────────────────────
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* GET /store/orders
|
|
88
|
-
* List orders belonging to the current user.
|
|
89
|
-
*/
|
|
90
|
-
@UseGuards(AuthGuard)
|
|
91
|
-
@Get("orders")
|
|
92
|
-
myOrders(
|
|
93
|
-
@CurrentUser() user: UserContext,
|
|
94
|
-
@Query("page") page?: string,
|
|
95
|
-
@Query("limit") limit?: string
|
|
96
|
-
) {
|
|
97
|
-
return this.paymentService.getUserOrders(user.id, Number(page ?? 1), Number(limit ?? 20));
|
|
98
|
-
}
|
|
12
|
+
constructor(@Inject(PaymentService) private readonly payments:PaymentService){}
|
|
13
|
+
@Get("products") products(){return this.payments.listProducts();}
|
|
14
|
+
@UseGuards(AuthGuard) @RequireAuthRealm("public") @Post("checkout")
|
|
15
|
+
checkout(@Body() body:unknown,@CurrentUser() user:User){requirePermission(user,"public.orders.create");return this.payments.createCheckout(body,user);}
|
|
16
|
+
@UseGuards(AuthGuard) @RequireAuthRealm("public") @Get("orders/:id/status")
|
|
17
|
+
status(@Param("id") id:string,@CurrentUser() user:User){requirePermission(user,"public.orders.read_own");return this.payments.getOrderStatus(id,user.id);}
|
|
18
|
+
@Post("webhook/:provider")
|
|
19
|
+
webhook(@Param("provider") provider:string,@Headers("stripe-signature") signature:string|undefined,@Req() req:RawBodyRequest<Request>){if(!req.rawBody||!signature)throw new BadRequestException("Missing signature or raw body");return this.payments.handleWebhook(provider,req.rawBody,signature);}
|
|
20
|
+
@UseGuards(AuthGuard) @RequireAuthRealm("public") @Get("orders")
|
|
21
|
+
orders(@CurrentUser() user:User,@Query("page") page?:string,@Query("limit") limit?:string){requirePermission(user,"public.orders.read_own");return this.payments.getUserOrders(user.id,Number(page??1),Number(limit??20));}
|
|
99
22
|
}
|
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
import { Module } from "@nestjs/common";
|
|
2
2
|
import { PrismaService } from "../../common/prisma.service";
|
|
3
3
|
import { AuthModule } from "../../auth/auth.module";
|
|
4
|
-
import { PaymentProviderService } from "./payment.provider";
|
|
5
4
|
import { PaymentService } from "./payment.service";
|
|
6
5
|
import { PaymentController } from "./payment.controller";
|
|
7
6
|
|
|
8
7
|
@Module({
|
|
9
8
|
imports: [AuthModule],
|
|
10
9
|
controllers: [PaymentController],
|
|
11
|
-
providers: [PrismaService,
|
|
12
|
-
exports: [PaymentService
|
|
10
|
+
providers: [PrismaService, PaymentService],
|
|
11
|
+
exports: [PaymentService]
|
|
13
12
|
})
|
|
14
13
|
export class PaymentModule {}
|
|
@@ -1,235 +1,129 @@
|
|
|
1
|
-
import { BadRequestException, Inject, Injectable, NotFoundException } from "@nestjs/common";
|
|
1
|
+
import { BadRequestException, ConflictException, ForbiddenException, Inject, Injectable, NotFoundException, ServiceUnavailableException } from "@nestjs/common";
|
|
2
|
+
import { Prisma } from "@prisma/client";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import Stripe from "stripe";
|
|
2
5
|
import { PrismaService } from "../../common/prisma.service";
|
|
3
|
-
import { PaymentProviderService } from "./payment.provider";
|
|
4
|
-
|
|
5
|
-
export type CreateOrderInput = {
|
|
6
|
-
items: Array<{
|
|
7
|
-
productId?: string;
|
|
8
|
-
name: string;
|
|
9
|
-
price: number;
|
|
10
|
-
quantity: number;
|
|
11
|
-
}>;
|
|
12
|
-
currency?: string;
|
|
13
|
-
email?: string;
|
|
14
|
-
userId?: string;
|
|
15
|
-
notes?: string;
|
|
16
|
-
successUrl: string;
|
|
17
|
-
cancelUrl: string;
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
export type OrderStatusResponse = {
|
|
21
|
-
id: string;
|
|
22
|
-
status: string;
|
|
23
|
-
total: number;
|
|
24
|
-
currency: string;
|
|
25
|
-
items: Array<{ name: string; price: number; quantity: number }>;
|
|
26
|
-
createdAt: Date;
|
|
27
|
-
};
|
|
28
6
|
|
|
7
|
+
const hash=(x:string)=>createHash("sha256").update(x).digest("hex");
|
|
8
|
+
type Buyer={id:string;email?:string};
|
|
9
|
+
type Line={productId:string;quantity:number};
|
|
10
|
+
|
|
11
|
+
export function parseCheckout(body:unknown):{items:Line[];key:string}{
|
|
12
|
+
if(!body||typeof body!=="object"||Array.isArray(body))throw new BadRequestException("Invalid checkout");
|
|
13
|
+
const data=body as Record<string,unknown>;
|
|
14
|
+
if(Object.keys(data).some(k=>!["items","idempotencyKey"].includes(k))||typeof data.idempotencyKey!=="string"||!/^[a-zA-Z0-9_-]{16,80}$/.test(data.idempotencyKey)||!Array.isArray(data.items)||!data.items.length||data.items.length>50)throw new BadRequestException("Invalid checkout items or idempotency key");
|
|
15
|
+
const seen=new Set<string>();const items:Line[]=[];
|
|
16
|
+
for(const item of data.items){
|
|
17
|
+
if(!item||typeof item!=="object"||Object.keys(item).some(k=>!["productId","quantity"].includes(k))||typeof item.productId!=="string"||!item.productId||item.productId.length>128||seen.has(item.productId)||!Number.isSafeInteger(item.quantity)||item.quantity<1||item.quantity>100)throw new BadRequestException("Invalid product or quantity");
|
|
18
|
+
seen.add(item.productId);items.push({productId:item.productId,quantity:item.quantity});
|
|
19
|
+
}
|
|
20
|
+
return {items:items.sort((a,b)=>a.productId.localeCompare(b.productId)),key:data.idempotencyKey};
|
|
21
|
+
}
|
|
29
22
|
@Injectable()
|
|
30
23
|
export class PaymentService {
|
|
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
|
-
name: item.name,
|
|
61
|
-
price: item.price,
|
|
62
|
-
quantity: item.quantity
|
|
63
|
-
}))
|
|
64
|
-
});
|
|
65
|
-
|
|
66
|
-
return created;
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
const provider = this.paymentProvider.get();
|
|
70
|
-
const checkout = await provider.createCheckout({
|
|
71
|
-
orderId: order.id,
|
|
72
|
-
lineItems: items.map((item) => ({
|
|
73
|
-
name: item.name,
|
|
74
|
-
unitAmount: item.price,
|
|
75
|
-
quantity: item.quantity
|
|
76
|
-
})),
|
|
77
|
-
currency,
|
|
78
|
-
successUrl,
|
|
79
|
-
cancelUrl,
|
|
80
|
-
customerEmail: email
|
|
24
|
+
constructor(@Inject(PrismaService) private readonly prisma:PrismaService){}
|
|
25
|
+
private stripe(){
|
|
26
|
+
// Test-mode only until provider reconciliation has passed end-to-end acceptance.
|
|
27
|
+
const key=process.env.STRIPE_SECRET_KEY;
|
|
28
|
+
if(process.env.OPENADMIN_COMMERCE_ENABLED!=="1"||!key?.startsWith("sk_test_")||!process.env.STRIPE_WEBHOOK_SECRET)throw new ForbiddenException("Commerce test profile is disabled");
|
|
29
|
+
return new Stripe(key,{apiVersion:"2025-02-24.acacia",timeout:15000,maxNetworkRetries:1});
|
|
30
|
+
}
|
|
31
|
+
private redirectUrl(name:string){
|
|
32
|
+
let url:URL;
|
|
33
|
+
try{url=new URL(process.env[name]??"");}catch{throw new ServiceUnavailableException("Checkout redirect is not configured");}
|
|
34
|
+
if(url.protocol!=="https:"||url.username||url.password)throw new ServiceUnavailableException("Checkout redirect must use HTTPS");
|
|
35
|
+
return url.toString();
|
|
36
|
+
}
|
|
37
|
+
async createCheckout(body:unknown,buyer:Buyer){
|
|
38
|
+
const stripe=this.stripe(),success_url=this.redirectUrl("CHECKOUT_SUCCESS_URL"),cancel_url=this.redirectUrl("CHECKOUT_CANCEL_URL");
|
|
39
|
+
const {items,key}=parseCheckout(body);
|
|
40
|
+
const checkoutKey=hash(buyer.id+":"+key),requestHash=hash(JSON.stringify(items));
|
|
41
|
+
let order=await this.prisma.order.findUnique({where:{checkoutKey},include:{items:true}});
|
|
42
|
+
if(!order){
|
|
43
|
+
try{
|
|
44
|
+
order=await this.prisma.$transaction(async tx=>{
|
|
45
|
+
const products=await tx.product.findMany({where:{id:{in:items.map(i=>i.productId)},active:true}});
|
|
46
|
+
if(products.length!==items.length)throw new BadRequestException("Product unavailable");
|
|
47
|
+
const currency=products[0]!.currency.toUpperCase();
|
|
48
|
+
if(!/^[A-Z]{3}$/.test(currency)||products.some(p=>p.currency.toUpperCase()!==currency||!Number.isSafeInteger(p.price)||p.price<=0))throw new BadRequestException("Incompatible price or currency");
|
|
49
|
+
const lines=items.map(i=>{const p=products.find(p=>p.id===i.productId)!;return {productId:p.id,name:p.name,price:p.price,quantity:i.quantity};});
|
|
50
|
+
const total=lines.reduce((s,x)=>s+x.price*x.quantity,0);
|
|
51
|
+
if(!Number.isSafeInteger(total)||total>2147483647)throw new BadRequestException("Order total too large");
|
|
52
|
+
return tx.order.create({data:{userId:buyer.id,email:buyer.email,currency,total,checkoutKey,checkoutRequestHash:requestHash,items:{create:lines}},include:{items:true}});
|
|
81
53
|
});
|
|
82
|
-
|
|
83
|
-
// Log the initial transaction attempt
|
|
84
|
-
await this.prisma.transaction.create({
|
|
85
|
-
data: {
|
|
86
|
-
orderId: order.id,
|
|
87
|
-
provider: this.paymentProvider.name,
|
|
88
|
-
providerTxId: checkout.providerSessionId,
|
|
89
|
-
status: "pending",
|
|
90
|
-
amount: total,
|
|
91
|
-
currency,
|
|
92
|
-
metadata: { sessionId: checkout.providerSessionId }
|
|
93
|
-
}
|
|
94
|
-
});
|
|
95
|
-
|
|
96
|
-
return { orderId: order.id, checkoutUrl: checkout.checkoutUrl };
|
|
54
|
+
}catch(e){if(!(e instanceof Prisma.PrismaClientKnownRequestError)||e.code!=="P2002")throw e;order=await this.prisma.order.findUnique({where:{checkoutKey},include:{items:true}});}
|
|
97
55
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
try {
|
|
106
|
-
const event = await this.paymentProvider.get().verifyWebhook(rawBody, signature);
|
|
107
|
-
|
|
108
|
-
await this.prisma.webhookLog.update({
|
|
109
|
-
where: { id: logEntry.id },
|
|
110
|
-
data: { eventType: event.type, payload: event.raw as object, status: "processed" }
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
if (event.orderId) {
|
|
114
|
-
await this.applyWebhookEvent(event.orderId, event.type, event.providerEventId, event.amount, event.currency);
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
return { received: true, type: event.type };
|
|
118
|
-
} catch (error) {
|
|
119
|
-
await this.prisma.webhookLog.update({
|
|
120
|
-
where: { id: logEntry.id },
|
|
121
|
-
data: { status: "failed", error: error instanceof Error ? error.message : "unknown" }
|
|
122
|
-
});
|
|
123
|
-
throw error;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
private async applyWebhookEvent(
|
|
128
|
-
orderId: string,
|
|
129
|
-
type: string,
|
|
130
|
-
providerEventId: string,
|
|
131
|
-
amount?: number,
|
|
132
|
-
currency?: string
|
|
133
|
-
) {
|
|
134
|
-
const statusMap: Record<string, string> = {
|
|
135
|
-
"payment.succeeded": "paid",
|
|
136
|
-
"payment.failed": "failed",
|
|
137
|
-
"payment.refunded": "refunded",
|
|
138
|
-
"checkout.expired": "cancelled"
|
|
139
|
-
};
|
|
140
|
-
|
|
141
|
-
const newStatus = statusMap[type];
|
|
142
|
-
if (!newStatus) return;
|
|
143
|
-
|
|
144
|
-
await this.prisma.$transaction(async (tx) => {
|
|
145
|
-
await tx.order.update({ where: { id: orderId }, data: { status: newStatus } });
|
|
146
|
-
await tx.transaction.updateMany({
|
|
147
|
-
where: { orderId, providerTxId: providerEventId },
|
|
148
|
-
data: {
|
|
149
|
-
status: newStatus === "paid" ? "succeeded" : newStatus === "refunded" ? "refunded" : "failed",
|
|
150
|
-
...(amount ? { amount } : {}),
|
|
151
|
-
...(currency ? { currency } : {})
|
|
152
|
-
}
|
|
153
|
-
});
|
|
154
|
-
});
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/** Get order status (public — by orderId only, no auth needed). */
|
|
158
|
-
async getOrderStatus(orderId: string): Promise<OrderStatusResponse> {
|
|
159
|
-
const order = await this.prisma.order.findUnique({
|
|
160
|
-
where: { id: orderId },
|
|
161
|
-
include: { items: true }
|
|
162
|
-
});
|
|
163
|
-
if (!order) throw new NotFoundException({ message: "Order not found", code: "ORDER_NOT_FOUND" });
|
|
164
|
-
|
|
165
|
-
return {
|
|
166
|
-
id: order.id,
|
|
167
|
-
status: order.status,
|
|
168
|
-
total: order.total,
|
|
169
|
-
currency: order.currency,
|
|
170
|
-
items: order.items.map((item) => ({ name: item.name, price: item.price, quantity: item.quantity })),
|
|
171
|
-
createdAt: order.createdAt
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/** List orders for the authenticated user. */
|
|
176
|
-
async getUserOrders(userId: string, page = 1, limit = 20) {
|
|
177
|
-
const [data, total] = await Promise.all([
|
|
178
|
-
this.prisma.order.findMany({
|
|
179
|
-
where: { userId },
|
|
180
|
-
include: { items: true },
|
|
181
|
-
orderBy: { createdAt: "desc" },
|
|
182
|
-
skip: (page - 1) * limit,
|
|
183
|
-
take: limit
|
|
184
|
-
}),
|
|
185
|
-
this.prisma.order.count({ where: { userId } })
|
|
186
|
-
]);
|
|
187
|
-
return { data, meta: { page, limit, total, pages: Math.ceil(total / limit) || 1 } };
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/** Refund an order (admin only). */
|
|
191
|
-
async refundOrder(orderId: string) {
|
|
192
|
-
const order = await this.prisma.order.findUnique({
|
|
193
|
-
where: { id: orderId },
|
|
194
|
-
include: { transactions: true }
|
|
195
|
-
});
|
|
196
|
-
if (!order) throw new NotFoundException({ message: "Order not found", code: "ORDER_NOT_FOUND" });
|
|
197
|
-
if (order.status !== "paid") {
|
|
198
|
-
throw new BadRequestException({ message: `Cannot refund order with status "${order.status}"`, code: "INVALID_ORDER_STATUS" });
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
const successTx = order.transactions.find((tx) => tx.status === "succeeded");
|
|
202
|
-
if (!successTx?.providerTxId) {
|
|
203
|
-
throw new BadRequestException({ message: "No successful transaction found for this order", code: "NO_TRANSACTION" });
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
const refund = await this.paymentProvider.get().refund({
|
|
207
|
-
providerTransactionId: successTx.providerTxId,
|
|
208
|
-
amount: order.total
|
|
209
|
-
});
|
|
210
|
-
|
|
211
|
-
await this.prisma.$transaction(async (tx) => {
|
|
212
|
-
await tx.order.update({ where: { id: orderId }, data: { status: "refunded" } });
|
|
213
|
-
await tx.transaction.create({
|
|
214
|
-
data: {
|
|
215
|
-
orderId,
|
|
216
|
-
provider: this.paymentProvider.name,
|
|
217
|
-
providerTxId: refund.providerRefundId,
|
|
218
|
-
status: "refunded",
|
|
219
|
-
amount: refund.amount,
|
|
220
|
-
currency: order.currency
|
|
221
|
-
}
|
|
222
|
-
});
|
|
223
|
-
});
|
|
224
|
-
|
|
225
|
-
return { ok: true, refundId: refund.providerRefundId };
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
/** List products. */
|
|
229
|
-
async listProducts(onlyActive = true) {
|
|
230
|
-
return this.prisma.product.findMany({
|
|
231
|
-
where: onlyActive ? { active: true } : undefined,
|
|
232
|
-
orderBy: { createdAt: "desc" }
|
|
233
|
-
});
|
|
56
|
+
if(!order||order.checkoutRequestHash!==requestHash)throw new ConflictException("Idempotency key was used for another cart");
|
|
57
|
+
if(order.status!=="pending")throw new ConflictException("Order is not pending");
|
|
58
|
+
// Never create another provider session after one has been persisted.
|
|
59
|
+
if(order.checkoutSessionId){
|
|
60
|
+
const existing=await stripe.checkout.sessions.retrieve(order.checkoutSessionId);
|
|
61
|
+
if(existing.status!=="open"||!existing.url)throw new ConflictException("Checkout is no longer open");
|
|
62
|
+
return {orderId:order.id,checkoutUrl:existing.url};
|
|
234
63
|
}
|
|
64
|
+
// Stripe retains idempotency keys for at least 24h. Do not retry ambiguous old requests.
|
|
65
|
+
if(Date.now()-order.createdAt.getTime()>3600000)throw new ConflictException("Checkout requires reconciliation");
|
|
66
|
+
const session=await stripe.checkout.sessions.create({mode:"payment",payment_method_types:["card"],line_items:order.items.map(i=>({quantity:i.quantity,price_data:{currency:order!.currency.toLowerCase(),unit_amount:i.price,product_data:{name:i.name}}})),success_url,cancel_url,customer_email:order.email??undefined,metadata:{orderId:order.id},payment_intent_data:{metadata:{orderId:order.id}}},{idempotencyKey:"checkout-"+order.id});
|
|
67
|
+
if(!session.url)throw new ServiceUnavailableException("Payment session unavailable");
|
|
68
|
+
await this.prisma.order.updateMany({where:{id:order.id,status:"pending",checkoutSessionId:null},data:{checkoutSessionId:session.id}});
|
|
69
|
+
return {orderId:order.id,checkoutUrl:session.url};
|
|
70
|
+
}
|
|
71
|
+
async handleWebhook(provider:string,raw:Buffer,signature:string){
|
|
72
|
+
const stripe=this.stripe();if(provider!=="stripe"||!signature||!raw.length)throw new BadRequestException("Invalid webhook");
|
|
73
|
+
let event:Stripe.Event;try{event=stripe.webhooks.constructEvent(raw,signature,process.env.STRIPE_WEBHOOK_SECRET!);}catch{throw new BadRequestException("Invalid webhook signature");}
|
|
74
|
+
if(event.livemode)throw new BadRequestException("Live payments disabled");
|
|
75
|
+
try{await this.prisma.$transaction(async tx=>{
|
|
76
|
+
await tx.webhookLog.create({data:{provider:"stripe",providerEventId:event.id,eventType:event.type,payload:{id:event.id},status:"processed"}});
|
|
77
|
+
if(event.type==="checkout.session.completed"||event.type==="checkout.session.expired"){
|
|
78
|
+
const session=event.data.object;
|
|
79
|
+
const orderId=session.metadata?.orderId;if(!orderId)throw new BadRequestException("Missing order reference");
|
|
80
|
+
const order=await tx.order.findUnique({where:{id:orderId}});
|
|
81
|
+
if(!order||!order.checkoutSessionId)throw new ServiceUnavailableException("Checkout not reconciled yet");
|
|
82
|
+
if(order.checkoutSessionId!==session.id||session.amount_total!==order.total||session.currency?.toUpperCase()!==order.currency)throw new BadRequestException("Payment details mismatch");
|
|
83
|
+
if(event.type==="checkout.session.expired"){await tx.order.updateMany({where:{id:order.id,status:"pending"},data:{status:"cancelled"}});return;}
|
|
84
|
+
if(session.payment_status!=="paid"||typeof session.payment_intent!=="string")throw new BadRequestException("Payment not completed");
|
|
85
|
+
const changed=await tx.order.updateMany({where:{id:order.id,status:"pending"},data:{status:"paid",paymentIntentId:session.payment_intent}});
|
|
86
|
+
if(changed.count)await tx.transaction.create({data:{orderId:order.id,provider:"stripe",providerTxId:session.payment_intent,status:"succeeded",amount:order.total,currency:order.currency}});
|
|
87
|
+
}else if(event.type==="charge.refunded"){
|
|
88
|
+
const charge=event.data.object;if(typeof charge.payment_intent!=="string")return;
|
|
89
|
+
const order=await tx.order.findUnique({where:{paymentIntentId:charge.payment_intent}});
|
|
90
|
+
if(!order)return;
|
|
91
|
+
if(charge.amount_refunded!==order.total||charge.currency.toUpperCase()!==order.currency)return;
|
|
92
|
+
const updated=await tx.order.updateMany({where:{id:order.id,status:{in:["paid","refund_pending"]}},data:{status:"refunded"}});
|
|
93
|
+
if(updated.count)await tx.transaction.create({data:{orderId:order.id,provider:"stripe",providerTxId:charge.id,status:"refunded",amount:order.total,currency:order.currency}});
|
|
94
|
+
}
|
|
95
|
+
});}catch(e){if(e instanceof Prisma.PrismaClientKnownRequestError&&e.code==="P2002"&&await this.prisma.webhookLog.findUnique({where:{providerEventId:event.id}}))return {received:true,duplicate:true};throw e;}
|
|
96
|
+
return {received:true};
|
|
97
|
+
}
|
|
98
|
+
async getOrderStatus(id:string,userId:string){
|
|
99
|
+
const order=await this.prisma.order.findFirst({where:{id,userId},select:{id:true,status:true,total:true,currency:true,createdAt:true,items:{select:{name:true,price:true,quantity:true}}}});
|
|
100
|
+
if(!order)throw new NotFoundException("Order not found");return order;
|
|
101
|
+
}
|
|
102
|
+
async getUserOrders(userId:string,page=1,limit=20){
|
|
103
|
+
if(!Number.isSafeInteger(page)||page<1||page>100000||!Number.isSafeInteger(limit)||limit<1)throw new BadRequestException("Invalid pagination");limit=Math.min(limit,100);
|
|
104
|
+
const [data,total]=await Promise.all([this.prisma.order.findMany({where:{userId},orderBy:{createdAt:"desc"},skip:(page-1)*limit,take:limit,select:{id:true,status:true,total:true,currency:true,createdAt:true}}),this.prisma.order.count({where:{userId}})]);
|
|
105
|
+
return {data,meta:{page,limit,total,pages:Math.ceil(total/limit)||1}};
|
|
106
|
+
}
|
|
107
|
+
async refundOrder(id:string,actorId:string){
|
|
108
|
+
const stripe=this.stripe();
|
|
109
|
+
const order=await this.prisma.order.findUnique({where:{id}});
|
|
110
|
+
if(!order||!order.paymentIntentId)throw new NotFoundException("Payment not found");
|
|
111
|
+
if(order.status==="refunded")return {ok:true,status:"refunded"};
|
|
112
|
+
if(order.status==="refund_pending")return {ok:true,status:"refund_pending"}; // reconciliation via signed webhook; no second submission
|
|
113
|
+
const claimed=await this.prisma.$transaction(async tx=>{
|
|
114
|
+
const change=await tx.order.updateMany({where:{id,status:"paid"},data:{status:"refund_pending"}});
|
|
115
|
+
if(change.count)await tx.auditLog.create({data:{userId:actorId,resource:"orders",resourceId:id,action:"refund.requested"}});
|
|
116
|
+
return change.count;
|
|
117
|
+
});
|
|
118
|
+
if(!claimed)throw new ConflictException("Order not refundable");
|
|
119
|
+
try{
|
|
120
|
+
const refund=await stripe.refunds.create({payment_intent:order.paymentIntentId,amount:order.total},{idempotencyKey:"refund-"+id});
|
|
121
|
+
// Keep pending until signed full-refund confirmation. A failed or ambiguous provider
|
|
122
|
+
// response requires operator reconciliation and cannot trigger another refund automatically.
|
|
123
|
+
return {ok:true,status:"refund_pending",refundId:refund.id,providerStatus:refund.status};
|
|
124
|
+
}catch{throw new ServiceUnavailableException("Refund pending reconciliation; do not submit another refund");}
|
|
125
|
+
}
|
|
126
|
+
async listProducts(active=true){
|
|
127
|
+
return this.prisma.product.findMany({where:active?{active:true}:undefined,take:100,orderBy:{createdAt:"desc"},select:{id:true,name:true,slug:true,description:true,price:true,currency:true,imageUrl:true}});
|
|
128
|
+
}
|
|
235
129
|
}
|
|
@@ -4,9 +4,10 @@ const nodeExternals = require("webpack-node-externals");
|
|
|
4
4
|
module.exports = function configureWebpack(options) {
|
|
5
5
|
return {
|
|
6
6
|
...options,
|
|
7
|
+
resolve: {...options.resolve, extensionAlias: {...options.resolve?.extensionAlias, ".js": [".js", ".ts", ".tsx"]}},
|
|
7
8
|
externals: [
|
|
8
9
|
nodeExternals({
|
|
9
|
-
allowlist: [/^@openadminjs
|
|
10
|
+
allowlist: [/^@openadminjs\//, /^openid-client(?:\/|$)/, /^oauth4webapi(?:\/|$)/, /^jose(?:\/|$)/],
|
|
10
11
|
}),
|
|
11
12
|
],
|
|
12
13
|
};
|
|
@@ -1 +1,4 @@
|
|
|
1
|
-
<svg xmlns="http://www.w3.org/2000/svg"
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="OpenAdminJS">
|
|
2
|
+
<rect width="64" height="64" rx="13" fill="#101820"/>
|
|
3
|
+
<path fill="#B9F56D" d="M29 13a19 19 0 1 0 0 38h9l11-23 7 15H45l-4 8h18L42 13h-8L21 42a11 11 0 1 1 8-21l3-7z"/>
|
|
4
|
+
</svg>
|