feat: 实现小程序代码发布任务闭环
This commit is contained in:
1 parent
9b35b8e7a7
commit
526a9db789
14 files changed
+7242
-249
No files matched your search
@@ -0,0 +1,129 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Req,
|
||||
} from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { existsSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
||||
import {
|
||||
CreateMiniAppReleaseDto,
|
||||
UpdateMiniAppReleaseStatusDto,
|
||||
UploadMiniAppReleaseDto,
|
||||
} from "./admin-miniapp-release.dto.js";
|
||||
|
||||
interface MiniprogramCi {
|
||||
Project: new (options: {
|
||||
projectPath: string;
|
||||
type: "miniProgram";
|
||||
appid: string;
|
||||
privateKey: string;
|
||||
}) => unknown;
|
||||
upload: (options: {
|
||||
project: unknown;
|
||||
version: string;
|
||||
desc: string;
|
||||
robot: number;
|
||||
setting: { es6: boolean; minified: boolean };
|
||||
}) => Promise<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
@Controller("admin/miniapp-releases")
|
||||
export class AdminMiniAppReleaseController {
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly releases: AdminMiniAppReleaseService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
list(@Req() request: FastifyRequest): Promise<unknown[]> {
|
||||
return this.identity(request).then(({ brandId }) => this.releases.list(brandId));
|
||||
}
|
||||
|
||||
@Post()
|
||||
create(@Req() request: FastifyRequest, @Body() body: CreateMiniAppReleaseDto): Promise<unknown> {
|
||||
return this.identity(request).then(({ brandId, subject }) =>
|
||||
this.releases.create(brandId, subject, body),
|
||||
);
|
||||
}
|
||||
|
||||
@Post(":id/upload")
|
||||
async upload(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") taskId: string,
|
||||
@Body() body: UploadMiniAppReleaseDto,
|
||||
): Promise<unknown> {
|
||||
const identity = await this.identity(request);
|
||||
const task = await this.prisma.miniAppReleaseTask.findFirst({
|
||||
where: { id: taskId, brandId: identity.brandId },
|
||||
});
|
||||
if (!task) throw new BadRequestException("小程序发布任务不存在");
|
||||
if (task.status !== "built") throw new BadRequestException("当前小程序发布任务不能重复上传");
|
||||
const appid = this.requiredEnv("WECHAT_APP_ID");
|
||||
const privateKey = this.requiredEnv("WECHAT_UPLOAD_PRIVATE_KEY");
|
||||
const artifactPath = process.env.WEAPP_ARTIFACT_PATH;
|
||||
if (!artifactPath) throw new BadRequestException("WEAPP_ARTIFACT_PATH 未配置");
|
||||
const projectPath = resolve(artifactPath);
|
||||
if (!existsSync(projectPath) || !existsSync(resolve(projectPath, "app.json")))
|
||||
throw new BadRequestException("小程序构建产物不存在");
|
||||
const ci = (await import("miniprogram-ci")) as unknown as MiniprogramCi;
|
||||
const project = new ci.Project({
|
||||
projectPath,
|
||||
type: "miniProgram",
|
||||
appid,
|
||||
privateKey,
|
||||
});
|
||||
try {
|
||||
const result = await ci.upload({
|
||||
project,
|
||||
version: body.version ?? String(task.version),
|
||||
desc: body.desc ?? `brand content v${task.version}`,
|
||||
robot: body.robot ?? 1,
|
||||
setting: { es6: false, minified: true },
|
||||
});
|
||||
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
||||
status: "uploaded",
|
||||
weappUploadId:
|
||||
typeof result.strUint64Version === "string"
|
||||
? result.strUint64Version
|
||||
: String(task.version),
|
||||
});
|
||||
} catch (error) {
|
||||
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
||||
status: "failed",
|
||||
error: error instanceof Error ? error.message : "微信代码上传失败",
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@Patch(":id/status")
|
||||
async updateStatus(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") taskId: string,
|
||||
@Body() body: UpdateMiniAppReleaseStatusDto,
|
||||
): Promise<unknown> {
|
||||
const identity = await this.identity(request);
|
||||
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, body);
|
||||
}
|
||||
|
||||
private async identity(request: FastifyRequest): Promise<{ subject: string; brandId: string }> {
|
||||
const { subject, brandId } = await this.access.requireBrand(request);
|
||||
return { subject, brandId };
|
||||
}
|
||||
|
||||
private requiredEnv(name: string): string {
|
||||
const value = process.env[name];
|
||||
if (!value) throw new BadRequestException(`${name} 未配置`);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Type } from "class-transformer";
|
||||
import { IsIn, IsOptional, IsString, IsUUID, MaxLength } from "class-validator";
|
||||
|
||||
export class CreateMiniAppReleaseDto {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
releaseId?: string;
|
||||
}
|
||||
|
||||
export class UpdateMiniAppReleaseStatusDto {
|
||||
@IsIn(["uploaded", "under_review", "approved", "rejected", "failed", "built", "published"])
|
||||
status!: "uploaded" | "under_review" | "approved" | "rejected" | "failed" | "built" | "published";
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(2000)
|
||||
error?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
weappUploadId?: string;
|
||||
}
|
||||
|
||||
export class UploadMiniAppReleaseDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
version?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(500)
|
||||
desc?: string;
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsIn([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
|
||||
robot?: number;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
|
||||
const transitions: Record<string, string[]> = {
|
||||
built: ["uploaded", "under_review", "failed"],
|
||||
uploaded: ["under_review", "failed"],
|
||||
under_review: ["approved", "rejected", "failed"],
|
||||
approved: ["published", "failed"],
|
||||
rejected: [],
|
||||
failed: ["built"],
|
||||
published: [],
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class AdminMiniAppReleaseService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async list(brandId: string): Promise<unknown[]> {
|
||||
return this.prisma.miniAppReleaseTask.findMany({
|
||||
where: { brandId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
});
|
||||
}
|
||||
|
||||
async create(brandId: string, actorId: string, input: { releaseId?: string }): Promise<unknown> {
|
||||
return this.prisma.$transaction(
|
||||
async (tx) => {
|
||||
const release = input.releaseId
|
||||
? await tx.brandRelease.findFirst({ where: { id: input.releaseId, brandId } })
|
||||
: await tx.brandRelease.findFirst({
|
||||
where: { brandId, status: "published" },
|
||||
orderBy: { version: "desc" },
|
||||
});
|
||||
if (!release) throw new BadRequestException("请先发布品牌内容版本");
|
||||
const existing = await tx.miniAppReleaseTask.findUnique({
|
||||
where: { brandId_version: { brandId, version: release.version } },
|
||||
});
|
||||
if (existing) return existing;
|
||||
return tx.miniAppReleaseTask.create({
|
||||
data: {
|
||||
brandId,
|
||||
releaseId: release.id,
|
||||
version: release.version,
|
||||
actorId,
|
||||
status: "built",
|
||||
audit: { action: "created", actorId, at: new Date().toISOString() },
|
||||
},
|
||||
});
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
|
||||
);
|
||||
}
|
||||
|
||||
async updateStatus(
|
||||
brandId: string,
|
||||
actorId: string,
|
||||
taskId: string,
|
||||
input: {
|
||||
status:
|
||||
"uploaded" | "under_review" | "approved" | "rejected" | "failed" | "built" | "published";
|
||||
error?: string;
|
||||
weappUploadId?: string;
|
||||
},
|
||||
): Promise<unknown> {
|
||||
return this.prisma.$transaction(
|
||||
async (tx) => {
|
||||
const task = await tx.miniAppReleaseTask.findFirst({ where: { id: taskId, brandId } });
|
||||
if (!task) throw new NotFoundException("小程序发布任务不存在");
|
||||
if (!transitions[task.status]?.includes(input.status))
|
||||
throw new ConflictException("小程序发布状态不能按此顺序变更");
|
||||
const audit = this.audit(task.audit, {
|
||||
action: "status-updated",
|
||||
actorId,
|
||||
from: task.status,
|
||||
to: input.status,
|
||||
at: new Date().toISOString(),
|
||||
...(input.error ? { error: input.error } : {}),
|
||||
});
|
||||
const updated = await tx.miniAppReleaseTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: input.status,
|
||||
error: input.error ?? null,
|
||||
...(input.weappUploadId ? { weappUploadId: input.weappUploadId } : {}),
|
||||
audit,
|
||||
},
|
||||
});
|
||||
return {
|
||||
...updated,
|
||||
status: input.status,
|
||||
};
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
|
||||
);
|
||||
}
|
||||
|
||||
private audit(value: Prisma.JsonValue | null, entry: Record<string, unknown>) {
|
||||
return [...(Array.isArray(value) ? value : []), entry] as Prisma.InputJsonValue[];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user