refactor: 拆分小程序发布与后台发布页面职责
This commit is contained in:
1 parent
8973338c64
commit
7c0f22ad7a
19 files changed
+797
-538
No files matched your search
@@ -4,7 +4,7 @@ import type { TemplateAdminSection } from "@personal-brand/api-client";
|
|||||||
import { TemplateListField } from "./TemplateListField.js";
|
import { TemplateListField } from "./TemplateListField.js";
|
||||||
import { TemplateFieldRenderer } from "./TemplateFieldRenderer.js";
|
import { TemplateFieldRenderer } from "./TemplateFieldRenderer.js";
|
||||||
import { MutationError } from "./QueryState.js";
|
import { MutationError } from "./QueryState.js";
|
||||||
import { presentationFieldName } from "../features/brand/presentation-bindings.js";
|
import { presentationFieldName } from "../lib/presentation/presentation-bindings.js";
|
||||||
import { useRecordContentEditorState } from "./record-content/useRecordContentEditorState.js";
|
import { useRecordContentEditorState } from "./record-content/useRecordContentEditorState.js";
|
||||||
import type { RecordContentEditorProps, RecordContentSource } from "./record-content/types.js";
|
import type { RecordContentEditorProps, RecordContentSource } from "./record-content/types.js";
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client";
|
import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client";
|
||||||
import type { PresentationValues } from "../../features/brand/presentation-bindings.js";
|
import type { PresentationValues } from "../../lib/presentation/presentation-bindings.js";
|
||||||
|
|
||||||
export type RecordContentSource = "offering" | "trust";
|
export type RecordContentSource = "offering" | "trust";
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import {
|
|||||||
presentationFieldName,
|
presentationFieldName,
|
||||||
readPresentationValue,
|
readPresentationValue,
|
||||||
type PresentationValues,
|
type PresentationValues,
|
||||||
} from "../../features/brand/presentation-bindings.js";
|
} from "../../lib/presentation/presentation-bindings.js";
|
||||||
import type { RecordContentSource } from "./types.js";
|
import type { RecordContentSource } from "./types.js";
|
||||||
|
|
||||||
function createInitialValues(
|
function createInitialValues(
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ import {
|
|||||||
filterSectionsForPreviewTarget,
|
filterSectionsForPreviewTarget,
|
||||||
presentationFieldName,
|
presentationFieldName,
|
||||||
type PresentationValues,
|
type PresentationValues,
|
||||||
} from "./presentation-bindings.js";
|
} from "../../lib/presentation/presentation-bindings.js";
|
||||||
import "./PresentationEditor.css";
|
import "./PresentationEditor.css";
|
||||||
import { useEditorDraft } from "./use-editor-draft.js";
|
import { useEditorDraft } from "./use-editor-draft.js";
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import type { Offering, TrustContent } from "@personal-brand/api-client";
|
import type { Offering, TrustContent } from "@personal-brand/api-client";
|
||||||
import type { TemplateAdminSection } from "@personal-brand/api-client";
|
import type { TemplateAdminSection } from "@personal-brand/api-client";
|
||||||
import { applyPresentationValues, applyStandardEntityValues } from "./presentation-bindings.js";
|
import {
|
||||||
import type { PresentationValues } from "./presentation-bindings.js";
|
applyPresentationValues,
|
||||||
|
applyStandardEntityValues,
|
||||||
|
} from "../../lib/presentation/presentation-bindings.js";
|
||||||
|
import type { PresentationValues } from "../../lib/presentation/presentation-bindings.js";
|
||||||
|
|
||||||
export interface RecordDraft {
|
export interface RecordDraft {
|
||||||
source: "offering" | "trust";
|
source: "offering" | "trust";
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import {
|
|||||||
presentationFieldName,
|
presentationFieldName,
|
||||||
readPresentationValue,
|
readPresentationValue,
|
||||||
type PresentationValues,
|
type PresentationValues,
|
||||||
} from "./presentation-bindings.js";
|
} from "../../lib/presentation/presentation-bindings.js";
|
||||||
|
|
||||||
const standardBrandBindings = [
|
const standardBrandBindings = [
|
||||||
"brand.name",
|
"brand.name",
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { Alert, Button, Form, Input, Space } from "antd";
|
||||||
|
import type { FormInstance } from "antd";
|
||||||
|
import type { MiniAppReleaseSettings } from "@personal-brand/api-client";
|
||||||
|
import { AdminSection } from "../../components/AdminSection.js";
|
||||||
|
import { MutationError } from "../../components/QueryState.js";
|
||||||
|
import { StatusTag } from "../../components/StatusTag.js";
|
||||||
|
|
||||||
|
export type MiniAppSettingsValues = {
|
||||||
|
appId: string;
|
||||||
|
apiBaseUrl: string;
|
||||||
|
privateKey?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface MiniAppSettingsTabProps {
|
||||||
|
form: FormInstance<MiniAppSettingsValues>;
|
||||||
|
settings: MiniAppReleaseSettings | undefined;
|
||||||
|
saving: boolean;
|
||||||
|
error?: unknown;
|
||||||
|
onSave: (values: MiniAppSettingsValues) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MiniAppSettingsTab({
|
||||||
|
form,
|
||||||
|
settings,
|
||||||
|
saving,
|
||||||
|
error,
|
||||||
|
onSave,
|
||||||
|
}: MiniAppSettingsTabProps) {
|
||||||
|
return (
|
||||||
|
<div className="admin-stack admin-stack-lg">
|
||||||
|
<AdminSection
|
||||||
|
title="小程序上传配置"
|
||||||
|
description="AppID 用于服务端调用微信官方上传工具;上传私钥保存前会使用 AES-256-GCM 加密。"
|
||||||
|
>
|
||||||
|
{settings?.buildError ? (
|
||||||
|
<Alert
|
||||||
|
type="warning"
|
||||||
|
showIcon
|
||||||
|
className="admin-offset-bottom"
|
||||||
|
message="小程序构建参数未就绪"
|
||||||
|
description={settings.buildError}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
className="admin-offset-bottom"
|
||||||
|
message={`请求域名 ${settings?.requestDomain ?? "未确认"}`}
|
||||||
|
description="该域名在构建时写入小程序包,必须与微信后台“开发设置 → 服务器域名 → request 合法域名”一致;不一致会导致小程序打开即加载失败。"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Form form={form} layout="vertical" onFinish={onSave}>
|
||||||
|
<Form.Item
|
||||||
|
name="appId"
|
||||||
|
label="微信 AppID"
|
||||||
|
rules={[{ required: true, message: "请输入微信 AppID" }]}
|
||||||
|
>
|
||||||
|
<Input maxLength={100} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="apiBaseUrl"
|
||||||
|
label="小程序请求地址"
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: "请输入小程序请求地址" },
|
||||||
|
{
|
||||||
|
validator: (_rule, value: string) =>
|
||||||
|
!value || /^https:\/\/[^/]+/.test(value)
|
||||||
|
? Promise.resolve()
|
||||||
|
: Promise.reject(
|
||||||
|
new Error(
|
||||||
|
"公网地址必须以 https:// 开头,例如 https://wechat.app.que01.top/api",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
extra="构建时写入小程序包,必须与微信后台“开发设置 → 服务器域名 → request 合法域名”一致。修改后需重新构建并上传代码才生效。"
|
||||||
|
>
|
||||||
|
<Input maxLength={200} placeholder="https://wechat.app.que01.top/api" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="privateKey"
|
||||||
|
label="上传私钥"
|
||||||
|
help={
|
||||||
|
settings?.hasStoredCredentials
|
||||||
|
? "已加密保存。留空保持现有私钥,输入新值可替换。"
|
||||||
|
: "粘贴微信开发者工具导出的 private.<appid>.key 全文,必须保留换行。"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Input.TextArea
|
||||||
|
rows={5}
|
||||||
|
autoComplete="off"
|
||||||
|
spellCheck={false}
|
||||||
|
placeholder={"-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"}
|
||||||
|
className="admin-code-input"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Space>
|
||||||
|
<Button type="primary" loading={saving} htmlType="submit">
|
||||||
|
保存上传配置
|
||||||
|
</Button>
|
||||||
|
{settings?.hasStoredCredentials ? (
|
||||||
|
<StatusTag tone="success" label="已加密保存上传凭据" />
|
||||||
|
) : (
|
||||||
|
<StatusTag tone="warning" label="未配置上传私钥" />
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
<MutationError error={error} />
|
||||||
|
</Form>
|
||||||
|
</AdminSection>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
Button,
|
Button,
|
||||||
@@ -23,6 +23,9 @@ import { EmptyState } from "../../components/EmptyState.js";
|
|||||||
import { ErrorNote, MutationError, QueryState } from "../../components/QueryState.js";
|
import { ErrorNote, MutationError, QueryState } from "../../components/QueryState.js";
|
||||||
import { StatusTag, statusLabel } from "../../components/StatusTag.js";
|
import { StatusTag, statusLabel } from "../../components/StatusTag.js";
|
||||||
import { MiniAppReleaseCard } from "./MiniAppReleaseCard.js";
|
import { MiniAppReleaseCard } from "./MiniAppReleaseCard.js";
|
||||||
|
import { MiniAppSettingsTab, type MiniAppSettingsValues } from "./MiniAppSettingsTab.js";
|
||||||
|
import { usePublicationQueries } from "./use-publication-queries.js";
|
||||||
|
import { usePublicationMutations } from "./use-publication-mutations.js";
|
||||||
|
|
||||||
const client = createApiClient();
|
const client = createApiClient();
|
||||||
|
|
||||||
@@ -44,66 +47,22 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
|||||||
const [rollbackVersion, setRollbackVersion] = useState<number | null>(null);
|
const [rollbackVersion, setRollbackVersion] = useState<number | null>(null);
|
||||||
const [note, setNote] = useState("");
|
const [note, setNote] = useState("");
|
||||||
const [activeTab, setActiveTab] = useState("content");
|
const [activeTab, setActiveTab] = useState("content");
|
||||||
const [miniAppSettingsForm] = Form.useForm<{
|
const [miniAppSettingsForm] = Form.useForm<MiniAppSettingsValues>();
|
||||||
appId: string;
|
const queries = usePublicationQueries(miniAppSettingsForm);
|
||||||
apiBaseUrl: string;
|
const {
|
||||||
privateKey?: string;
|
brand,
|
||||||
}>();
|
workspace,
|
||||||
const brand = useQuery({
|
catalog,
|
||||||
queryKey: ["publication-brand"],
|
sample,
|
||||||
queryFn: () => client.getAdminBrand(),
|
readiness,
|
||||||
});
|
releases,
|
||||||
const workspace = useQuery({
|
miniAppReleases,
|
||||||
queryKey: ["publication-workspace"],
|
miniAppSettings,
|
||||||
queryFn: () => client.getAdminWorkspace(),
|
templatePreview,
|
||||||
});
|
loading,
|
||||||
const catalog = useQuery({
|
error,
|
||||||
queryKey: ["publication-catalog"],
|
retry,
|
||||||
queryFn: () => client.listPublicTemplates(),
|
} = queries;
|
||||||
});
|
|
||||||
const sample = useQuery({
|
|
||||||
queryKey: ["publication-sample"],
|
|
||||||
queryFn: () => client.previewAdminSampleContent(),
|
|
||||||
enabled: Boolean(workspace.data),
|
|
||||||
});
|
|
||||||
const readiness = useQuery({
|
|
||||||
queryKey: ["publication-readiness"],
|
|
||||||
queryFn: () => client.getAdminReleaseReadiness(),
|
|
||||||
});
|
|
||||||
const releases = useQuery({
|
|
||||||
queryKey: ["publication-releases"],
|
|
||||||
queryFn: () => client.listAdminReleases(),
|
|
||||||
});
|
|
||||||
const miniAppReleases = useQuery({
|
|
||||||
queryKey: ["publication-miniapp-releases"],
|
|
||||||
queryFn: () => client.listAdminMiniAppReleases(),
|
|
||||||
});
|
|
||||||
const miniAppSettings = useQuery({
|
|
||||||
queryKey: ["publication-miniapp-settings"],
|
|
||||||
queryFn: () => client.getAdminMiniAppSettings(),
|
|
||||||
});
|
|
||||||
const templatePreview = useQuery({
|
|
||||||
queryKey: ["publication-template-preview"],
|
|
||||||
queryFn: () => client.getAdminTemplateUpgradePreview(),
|
|
||||||
});
|
|
||||||
useEffect(() => {
|
|
||||||
if (!miniAppSettings.data) return;
|
|
||||||
miniAppSettingsForm.setFieldsValue({
|
|
||||||
appId: miniAppSettings.data.appId,
|
|
||||||
apiBaseUrl: miniAppSettings.data.apiBaseUrl,
|
|
||||||
privateKey: "",
|
|
||||||
});
|
|
||||||
}, [miniAppSettings.data, miniAppSettingsForm]);
|
|
||||||
useEffect(() => {
|
|
||||||
const building = miniAppReleases.data?.find(
|
|
||||||
(task) =>
|
|
||||||
task.buildStatus === "building" &&
|
|
||||||
Date.now() - new Date(task.updatedAt).getTime() < 15 * 60 * 1000,
|
|
||||||
);
|
|
||||||
if (!building) return;
|
|
||||||
const timer = setInterval(() => void miniAppReleases.refetch(), 1500);
|
|
||||||
return () => clearInterval(timer);
|
|
||||||
}, [miniAppReleases.data, miniAppReleases]);
|
|
||||||
const refresh = () => {
|
const refresh = () => {
|
||||||
for (const key of [
|
for (const key of [
|
||||||
"publication-brand",
|
"publication-brand",
|
||||||
@@ -120,144 +79,28 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
|||||||
void queryClient.invalidateQueries({ queryKey: [key] });
|
void queryClient.invalidateQueries({ queryKey: [key] });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const install = useMutation({
|
const mutations = usePublicationMutations({
|
||||||
mutationFn: (key: BrandTemplateKey) => client.installAdminTemplate(key),
|
refresh,
|
||||||
onSuccess: () => {
|
brandConfig: brand.data?.config,
|
||||||
setIndustryTarget(null);
|
onInstallClose: () => setIndustryTarget(null),
|
||||||
message.success("行业模板已安装");
|
onPublishClose: () => setConfirmAction(null),
|
||||||
refresh();
|
onNoteClear: () => setNote(""),
|
||||||
},
|
onRollbackClose: () => setRollbackVersion(null),
|
||||||
});
|
});
|
||||||
const upgradeTemplate = useMutation({
|
const {
|
||||||
mutationFn: () => client.upgradeAdminTemplate(),
|
install,
|
||||||
onSuccess: () => {
|
upgradeTemplate,
|
||||||
message.success("行业模板已升级,现有内容未被覆盖");
|
rollbackTemplate,
|
||||||
refresh();
|
selectVisual,
|
||||||
},
|
importSample,
|
||||||
});
|
publish,
|
||||||
const rollbackTemplate = useMutation({
|
revoke,
|
||||||
mutationFn: () => client.rollbackAdminTemplate(),
|
rollback,
|
||||||
onSuccess: () => {
|
uploadLatestMiniAppRelease,
|
||||||
message.success("行业模板配置基线已回滚");
|
saveMiniAppSettings,
|
||||||
refresh();
|
uploadMiniAppRelease,
|
||||||
},
|
updateMiniAppStatus,
|
||||||
});
|
} = mutations;
|
||||||
const selectVisual = useMutation({
|
|
||||||
mutationFn: (key: string) =>
|
|
||||||
client.updateAdminBrand({
|
|
||||||
config: { ...(brand.data?.config ?? {}), visualTemplateKey: key },
|
|
||||||
}),
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("视觉模板已保存到草稿");
|
|
||||||
refresh();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const importSample = useMutation({
|
|
||||||
mutationFn: () => client.importAdminSampleContent(),
|
|
||||||
onSuccess: ({ counts }) => {
|
|
||||||
message.success(
|
|
||||||
counts.inquiryForms
|
|
||||||
? "示例内容和客户咨询表单已导入草稿"
|
|
||||||
: "示例内容已导入草稿,现有客户咨询表单已保留",
|
|
||||||
);
|
|
||||||
refresh();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const publish = useMutation({
|
|
||||||
mutationFn: () => client.publishAdminRelease(note.trim() || undefined),
|
|
||||||
onSuccess: () => {
|
|
||||||
setConfirmAction(null);
|
|
||||||
setNote("");
|
|
||||||
message.success("品牌已发布");
|
|
||||||
refresh();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const revoke = useMutation({
|
|
||||||
mutationFn: () => client.revokeAdminRelease(),
|
|
||||||
onSuccess: () => {
|
|
||||||
setConfirmAction(null);
|
|
||||||
message.success("品牌已撤回,小程序将显示未发布状态");
|
|
||||||
refresh();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const rollback = useMutation({
|
|
||||||
mutationFn: (version: number) => client.rollbackAdminRelease(version),
|
|
||||||
onSuccess: () => {
|
|
||||||
setRollbackVersion(null);
|
|
||||||
message.success("历史版本已重新发布");
|
|
||||||
refresh();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const uploadLatestMiniAppRelease = useMutation({
|
|
||||||
mutationFn: async () => {
|
|
||||||
const latest = await client.getLatestAdminMiniAppRelease();
|
|
||||||
const task = latest ?? (await client.createAdminMiniAppRelease());
|
|
||||||
return client.uploadAdminMiniAppRelease(task.id);
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("小程序代码已上传");
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-releases"] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const saveMiniAppSettings = useMutation({
|
|
||||||
mutationFn: (values: { appId: string; apiBaseUrl: string; privateKey?: string }) =>
|
|
||||||
client.updateAdminMiniAppSettings({
|
|
||||||
appId: values.appId,
|
|
||||||
apiBaseUrl: values.apiBaseUrl,
|
|
||||||
...(values.privateKey ? { privateKey: values.privateKey } : {}),
|
|
||||||
}),
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("小程序上传配置已保存");
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-settings"] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const uploadMiniAppRelease = useMutation({
|
|
||||||
mutationFn: (id: string) => client.uploadAdminMiniAppRelease(id),
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("小程序代码已上传");
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-releases"] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const updateMiniAppStatus = useMutation({
|
|
||||||
mutationFn: ({
|
|
||||||
id,
|
|
||||||
status,
|
|
||||||
}: {
|
|
||||||
id: string;
|
|
||||||
status: Parameters<typeof client.updateAdminMiniAppReleaseStatus>[1]["status"];
|
|
||||||
}) => client.updateAdminMiniAppReleaseStatus(id, { status }),
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("小程序发布状态已更新");
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-releases"] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const loading = [
|
|
||||||
brand,
|
|
||||||
workspace,
|
|
||||||
catalog,
|
|
||||||
readiness,
|
|
||||||
releases,
|
|
||||||
miniAppReleases,
|
|
||||||
miniAppSettings,
|
|
||||||
].some((query) => query.isLoading);
|
|
||||||
const error = [
|
|
||||||
brand,
|
|
||||||
workspace,
|
|
||||||
catalog,
|
|
||||||
readiness,
|
|
||||||
releases,
|
|
||||||
miniAppReleases,
|
|
||||||
miniAppSettings,
|
|
||||||
].find((query) => query.isError)?.error;
|
|
||||||
const retry = () => {
|
|
||||||
void brand.refetch();
|
|
||||||
void workspace.refetch();
|
|
||||||
void catalog.refetch();
|
|
||||||
void readiness.refetch();
|
|
||||||
void releases.refetch();
|
|
||||||
void miniAppReleases.refetch();
|
|
||||||
void miniAppSettings.refetch();
|
|
||||||
};
|
|
||||||
const industryKey =
|
const industryKey =
|
||||||
workspace.data?.installations[0]?.templateKey ??
|
workspace.data?.installations[0]?.templateKey ??
|
||||||
workspace.data?.brand?.templateKey ??
|
workspace.data?.brand?.templateKey ??
|
||||||
@@ -391,7 +234,16 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
|||||||
{
|
{
|
||||||
key: "settings",
|
key: "settings",
|
||||||
label: "小程序配置",
|
label: "小程序配置",
|
||||||
children: activeTab === "settings" ? miniAppSettingsTab : null,
|
children:
|
||||||
|
activeTab === "settings" ? (
|
||||||
|
<MiniAppSettingsTab
|
||||||
|
form={miniAppSettingsForm}
|
||||||
|
settings={miniAppSettings.data}
|
||||||
|
saving={saveMiniAppSettings.isPending}
|
||||||
|
error={saveMiniAppSettings.error}
|
||||||
|
onSave={(values) => saveMiniAppSettings.mutate(values)}
|
||||||
|
/>
|
||||||
|
) : null,
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
@@ -695,7 +547,7 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
|||||||
title={confirmAction === "revoke" ? "确认撤回品牌" : "确认发布品牌"}
|
title={confirmAction === "revoke" ? "确认撤回品牌" : "确认发布品牌"}
|
||||||
open={confirmAction !== null}
|
open={confirmAction !== null}
|
||||||
onCancel={() => setConfirmAction(null)}
|
onCancel={() => setConfirmAction(null)}
|
||||||
onOk={() => (confirmAction === "revoke" ? revoke.mutate() : publish.mutate())}
|
onOk={() => (confirmAction === "revoke" ? revoke.mutate() : publish.mutate(note.trim()))}
|
||||||
confirmLoading={publish.isPending || revoke.isPending}
|
confirmLoading={publish.isPending || revoke.isPending}
|
||||||
okText={confirmAction === "revoke" ? "确认撤回" : "确认发布"}
|
okText={confirmAction === "revoke" ? "确认撤回" : "确认发布"}
|
||||||
okButtonProps={{ danger: confirmAction === "revoke" }}
|
okButtonProps={{ danger: confirmAction === "revoke" }}
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { message } from "antd";
|
||||||
|
import type { BrandTemplateKey } from "@personal-brand/api-client";
|
||||||
|
import { createApiClient } from "../../lib/api.js";
|
||||||
|
|
||||||
|
const client = createApiClient();
|
||||||
|
|
||||||
|
interface MutationOptions {
|
||||||
|
refresh: () => void;
|
||||||
|
brandConfig: Record<string, unknown> | null | undefined;
|
||||||
|
onInstallClose: () => void;
|
||||||
|
onPublishClose: () => void;
|
||||||
|
onNoteClear: () => void;
|
||||||
|
onRollbackClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePublicationMutations({
|
||||||
|
refresh,
|
||||||
|
onInstallClose,
|
||||||
|
onPublishClose,
|
||||||
|
onNoteClear,
|
||||||
|
onRollbackClose,
|
||||||
|
brandConfig,
|
||||||
|
}: MutationOptions) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const install = useMutation({
|
||||||
|
mutationFn: (key: BrandTemplateKey) => client.installAdminTemplate(key),
|
||||||
|
onSuccess: () => {
|
||||||
|
onInstallClose();
|
||||||
|
message.success("行业模板已安装");
|
||||||
|
refresh();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const upgradeTemplate = useMutation({
|
||||||
|
mutationFn: () => client.upgradeAdminTemplate(),
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("行业模板已升级,现有内容未被覆盖");
|
||||||
|
refresh();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const rollbackTemplate = useMutation({
|
||||||
|
mutationFn: () => client.rollbackAdminTemplate(),
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("行业模板配置基线已回滚");
|
||||||
|
refresh();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const selectVisual = useMutation({
|
||||||
|
mutationFn: (key: string) =>
|
||||||
|
client.updateAdminBrand({
|
||||||
|
config: { ...(brandConfig ?? {}), visualTemplateKey: key },
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("视觉模板已保存到草稿");
|
||||||
|
refresh();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const importSample = useMutation<Awaited<ReturnType<typeof client.importAdminSampleContent>>>({
|
||||||
|
mutationFn: () => client.importAdminSampleContent(),
|
||||||
|
onSuccess: ({ counts }) => {
|
||||||
|
message.success(
|
||||||
|
counts.inquiryForms
|
||||||
|
? "示例内容和客户咨询表单已导入草稿"
|
||||||
|
: "示例内容已导入草稿,现有客户咨询表单已保留",
|
||||||
|
);
|
||||||
|
refresh();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const publish = useMutation({
|
||||||
|
mutationFn: (note: string) => client.publishAdminRelease(note || undefined),
|
||||||
|
onSuccess: () => {
|
||||||
|
onPublishClose();
|
||||||
|
onNoteClear();
|
||||||
|
message.success("品牌已发布");
|
||||||
|
refresh();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const revoke = useMutation({
|
||||||
|
mutationFn: () => client.revokeAdminRelease(),
|
||||||
|
onSuccess: () => {
|
||||||
|
onPublishClose();
|
||||||
|
message.success("品牌已撤回,小程序将显示未发布状态");
|
||||||
|
refresh();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const rollback = useMutation({
|
||||||
|
mutationFn: (version: number) => client.rollbackAdminRelease(version),
|
||||||
|
onSuccess: () => {
|
||||||
|
onRollbackClose();
|
||||||
|
message.success("历史版本已重新发布");
|
||||||
|
refresh();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const uploadLatestMiniAppRelease = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
const latest = await client.getLatestAdminMiniAppRelease();
|
||||||
|
const task = latest ?? (await client.createAdminMiniAppRelease());
|
||||||
|
return client.uploadAdminMiniAppRelease(task.id);
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("小程序代码已上传");
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-releases"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const saveMiniAppSettings = useMutation({
|
||||||
|
mutationFn: (values: { appId: string; apiBaseUrl: string; privateKey?: string }) =>
|
||||||
|
client.updateAdminMiniAppSettings({
|
||||||
|
appId: values.appId,
|
||||||
|
apiBaseUrl: values.apiBaseUrl,
|
||||||
|
...(values.privateKey ? { privateKey: values.privateKey } : {}),
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("小程序上传配置已保存");
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-settings"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const uploadMiniAppRelease = useMutation({
|
||||||
|
mutationFn: (id: string) => client.uploadAdminMiniAppRelease(id),
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("小程序代码已上传");
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-releases"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const updateMiniAppStatus = useMutation({
|
||||||
|
mutationFn: ({
|
||||||
|
id,
|
||||||
|
status,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
status: Parameters<typeof client.updateAdminMiniAppReleaseStatus>[1]["status"];
|
||||||
|
}) => client.updateAdminMiniAppReleaseStatus(id, { status }),
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("小程序发布状态已更新");
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-releases"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
install,
|
||||||
|
upgradeTemplate,
|
||||||
|
rollbackTemplate,
|
||||||
|
selectVisual,
|
||||||
|
importSample,
|
||||||
|
publish,
|
||||||
|
revoke,
|
||||||
|
rollback,
|
||||||
|
uploadLatestMiniAppRelease,
|
||||||
|
saveMiniAppSettings,
|
||||||
|
uploadMiniAppRelease,
|
||||||
|
updateMiniAppStatus,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import { useEffect } from "react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import type { FormInstance } from "antd";
|
||||||
|
import { createApiClient } from "../../lib/api.js";
|
||||||
|
|
||||||
|
const client = createApiClient();
|
||||||
|
|
||||||
|
export function usePublicationQueries(
|
||||||
|
miniAppSettingsForm: FormInstance<{
|
||||||
|
appId: string;
|
||||||
|
apiBaseUrl: string;
|
||||||
|
privateKey?: string;
|
||||||
|
}>,
|
||||||
|
) {
|
||||||
|
const brand = useQuery<Awaited<ReturnType<typeof client.getAdminBrand>>>({
|
||||||
|
queryKey: ["publication-brand"],
|
||||||
|
queryFn: () => client.getAdminBrand(),
|
||||||
|
});
|
||||||
|
const workspace = useQuery<Awaited<ReturnType<typeof client.getAdminWorkspace>>>({
|
||||||
|
queryKey: ["publication-workspace"],
|
||||||
|
queryFn: () => client.getAdminWorkspace(),
|
||||||
|
});
|
||||||
|
const catalog = useQuery<Awaited<ReturnType<typeof client.listPublicTemplates>>>({
|
||||||
|
queryKey: ["publication-catalog"],
|
||||||
|
queryFn: () => client.listPublicTemplates(),
|
||||||
|
});
|
||||||
|
const sample = useQuery<Awaited<ReturnType<typeof client.previewAdminSampleContent>>>({
|
||||||
|
queryKey: ["publication-sample"],
|
||||||
|
queryFn: () => client.previewAdminSampleContent(),
|
||||||
|
enabled: Boolean(workspace.data),
|
||||||
|
});
|
||||||
|
const readiness = useQuery<Awaited<ReturnType<typeof client.getAdminReleaseReadiness>>>({
|
||||||
|
queryKey: ["publication-readiness"],
|
||||||
|
queryFn: () => client.getAdminReleaseReadiness(),
|
||||||
|
});
|
||||||
|
const releases = useQuery<Awaited<ReturnType<typeof client.listAdminReleases>>>({
|
||||||
|
queryKey: ["publication-releases"],
|
||||||
|
queryFn: () => client.listAdminReleases(),
|
||||||
|
});
|
||||||
|
const miniAppReleases = useQuery<Awaited<ReturnType<typeof client.listAdminMiniAppReleases>>>({
|
||||||
|
queryKey: ["publication-miniapp-releases"],
|
||||||
|
queryFn: () => client.listAdminMiniAppReleases(),
|
||||||
|
});
|
||||||
|
const miniAppSettings = useQuery<Awaited<ReturnType<typeof client.getAdminMiniAppSettings>>>({
|
||||||
|
queryKey: ["publication-miniapp-settings"],
|
||||||
|
queryFn: () => client.getAdminMiniAppSettings(),
|
||||||
|
});
|
||||||
|
const templatePreview = useQuery<
|
||||||
|
Awaited<ReturnType<typeof client.getAdminTemplateUpgradePreview>>
|
||||||
|
>({
|
||||||
|
queryKey: ["publication-template-preview"],
|
||||||
|
queryFn: () => client.getAdminTemplateUpgradePreview(),
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!miniAppSettings.data) return;
|
||||||
|
miniAppSettingsForm.setFieldsValue({
|
||||||
|
appId: miniAppSettings.data.appId,
|
||||||
|
apiBaseUrl: miniAppSettings.data.apiBaseUrl,
|
||||||
|
privateKey: "",
|
||||||
|
});
|
||||||
|
}, [miniAppSettings.data, miniAppSettingsForm]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const building = miniAppReleases.data?.find(
|
||||||
|
(task) =>
|
||||||
|
task.buildStatus === "building" &&
|
||||||
|
Date.now() - new Date(task.updatedAt).getTime() < 15 * 60 * 1000,
|
||||||
|
);
|
||||||
|
if (!building) return;
|
||||||
|
const timer = setInterval(() => void miniAppReleases.refetch(), 1500);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
}, [miniAppReleases]);
|
||||||
|
|
||||||
|
const loading = [
|
||||||
|
brand,
|
||||||
|
workspace,
|
||||||
|
catalog,
|
||||||
|
readiness,
|
||||||
|
releases,
|
||||||
|
miniAppReleases,
|
||||||
|
miniAppSettings,
|
||||||
|
].some((query) => query.isLoading);
|
||||||
|
const error = [
|
||||||
|
brand,
|
||||||
|
workspace,
|
||||||
|
catalog,
|
||||||
|
readiness,
|
||||||
|
releases,
|
||||||
|
miniAppReleases,
|
||||||
|
miniAppSettings,
|
||||||
|
].find((query) => query.isError)?.error;
|
||||||
|
const retry = () => {
|
||||||
|
void brand.refetch();
|
||||||
|
void workspace.refetch();
|
||||||
|
void catalog.refetch();
|
||||||
|
void readiness.refetch();
|
||||||
|
void releases.refetch();
|
||||||
|
void miniAppReleases.refetch();
|
||||||
|
void miniAppSettings.refetch();
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
brand,
|
||||||
|
workspace,
|
||||||
|
catalog,
|
||||||
|
sample,
|
||||||
|
readiness,
|
||||||
|
releases,
|
||||||
|
miniAppReleases,
|
||||||
|
miniAppSettings,
|
||||||
|
templatePreview,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
retry,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
applyPresentationValues,
|
applyPresentationValues,
|
||||||
presentationFieldName,
|
presentationFieldName,
|
||||||
readPresentationValue,
|
readPresentationValue,
|
||||||
} from "../brand/presentation-bindings.js";
|
} from "../../lib/presentation/presentation-bindings.js";
|
||||||
|
|
||||||
export type OfferingFormValues = Record<string, unknown>;
|
export type OfferingFormValues = Record<string, unknown>;
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import type {
|
|||||||
TemplateAdminField,
|
TemplateAdminField,
|
||||||
} from "@personal-brand/api-client";
|
} from "@personal-brand/api-client";
|
||||||
import type { PreviewTarget } from "../brand/preview-selection.js";
|
import type { PreviewTarget } from "../brand/preview-selection.js";
|
||||||
import { applyPresentationValues } from "../brand/presentation-bindings.js";
|
import { applyPresentationValues } from "../../lib/presentation/presentation-bindings.js";
|
||||||
|
|
||||||
export function previewTargetsByPage(
|
export function previewTargetsByPage(
|
||||||
sections: AdminTemplateContent["admin"]["sections"],
|
sections: AdminTemplateContent["admin"]["sections"],
|
||||||
|
|||||||
File renamed without changes.
@@ -6,7 +6,7 @@ import {
|
|||||||
filterSectionsForPreviewTarget,
|
filterSectionsForPreviewTarget,
|
||||||
presentationFieldName,
|
presentationFieldName,
|
||||||
readPresentationValue,
|
readPresentationValue,
|
||||||
} from "../src/features/brand/presentation-bindings.ts";
|
} from "../src/lib/presentation/presentation-bindings.ts";
|
||||||
import {
|
import {
|
||||||
resolvePreviewSelection,
|
resolvePreviewSelection,
|
||||||
previewTrustRecordId,
|
previewTrustRecordId,
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ import { BrandReleaseApiService } from "./brand-release-api.service.js";
|
|||||||
import { AdminReleaseController } from "./modules/admin/admin-release.controller.js";
|
import { AdminReleaseController } from "./modules/admin/admin-release.controller.js";
|
||||||
import { AdminMiniAppReleaseController } from "./modules/admin/admin-miniapp-release.controller.js";
|
import { AdminMiniAppReleaseController } from "./modules/admin/admin-miniapp-release.controller.js";
|
||||||
import { AdminMiniAppReleaseService } from "./modules/admin/admin-miniapp-release.service.js";
|
import { AdminMiniAppReleaseService } from "./modules/admin/admin-miniapp-release.service.js";
|
||||||
|
import { AdminMiniAppBuildService } from "./modules/admin/admin-miniapp-build.service.js";
|
||||||
|
import { AdminMiniAppSettingsService } from "./modules/admin/admin-miniapp-settings.service.js";
|
||||||
|
import { AdminMiniAppUploadService } from "./modules/admin/admin-miniapp-upload.service.js";
|
||||||
import {
|
import {
|
||||||
CustomerSessionController,
|
CustomerSessionController,
|
||||||
AdminSessionController,
|
AdminSessionController,
|
||||||
@@ -90,6 +93,9 @@ export class HealthController {
|
|||||||
BrandReleaseService,
|
BrandReleaseService,
|
||||||
BrandReleaseApiService,
|
BrandReleaseApiService,
|
||||||
AdminMiniAppReleaseService,
|
AdminMiniAppReleaseService,
|
||||||
|
AdminMiniAppBuildService,
|
||||||
|
AdminMiniAppSettingsService,
|
||||||
|
AdminMiniAppUploadService,
|
||||||
AdminBrandConfigService,
|
AdminBrandConfigService,
|
||||||
TenantService,
|
TenantService,
|
||||||
CustomerInquirySubmissionService,
|
CustomerInquirySubmissionService,
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { spawn } from "node:child_process";
|
||||||
|
import { REPOSITORY_ROOT } from "./miniapp-artifact.js";
|
||||||
|
|
||||||
|
interface BuildProcess {
|
||||||
|
stdout: NodeJS.ReadableStream;
|
||||||
|
stderr: NodeJS.ReadableStream;
|
||||||
|
on: (event: "close" | "error", listener: (code: number | null) => void) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdminMiniAppBuildService {
|
||||||
|
run(
|
||||||
|
templateKey: string,
|
||||||
|
buildConfig: { apiBaseUrl: string; appId: string },
|
||||||
|
onLog: (message: string, stream: "stdout" | "stderr") => void,
|
||||||
|
): Promise<{ exitCode: number }> {
|
||||||
|
return new Promise((resolvePromise, rejectPromise) => {
|
||||||
|
const child = spawn("pnpm", ["--filter", "@personal-brand/taro", "build:weapp"], {
|
||||||
|
cwd: REPOSITORY_ROOT,
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
TEMPLATE_KEY: templateKey,
|
||||||
|
TARO_ENV: "weapp",
|
||||||
|
API_BASE_URL: buildConfig.apiBaseUrl,
|
||||||
|
WEAPP_APP_ID: buildConfig.appId,
|
||||||
|
},
|
||||||
|
shell: process.platform === "win32",
|
||||||
|
}) as BuildProcess;
|
||||||
|
const readStream = (stream: NodeJS.ReadableStream, name: "stdout" | "stderr") => {
|
||||||
|
let buffer = "";
|
||||||
|
stream.on("data", (chunk: Buffer | string) => {
|
||||||
|
buffer += chunk.toString();
|
||||||
|
for (const message of buffer.split("\n").slice(0, -1)) onLog(message, name);
|
||||||
|
buffer = buffer.slice(buffer.lastIndexOf("\n") + 1);
|
||||||
|
});
|
||||||
|
stream.on("end", () => {
|
||||||
|
if (buffer) onLog(buffer, name);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
readStream(child.stdout, "stdout");
|
||||||
|
readStream(child.stderr, "stderr");
|
||||||
|
child.on("close", (code) => resolvePromise({ exitCode: code ?? 1 }));
|
||||||
|
child.on("error", () => rejectPromise(new Error("小程序构建进程启动失败")));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,116 +1,37 @@
|
|||||||
import {
|
import { Body, Controller, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||||
BadRequestException,
|
|
||||||
BadGatewayException,
|
|
||||||
Body,
|
|
||||||
ConflictException,
|
|
||||||
Controller,
|
|
||||||
Get,
|
|
||||||
Param,
|
|
||||||
Patch,
|
|
||||||
Post,
|
|
||||||
Req,
|
|
||||||
} from "@nestjs/common";
|
|
||||||
import type { FastifyRequest } from "fastify";
|
import type { FastifyRequest } from "fastify";
|
||||||
import { existsSync } from "node:fs";
|
|
||||||
import { spawn } from "node:child_process";
|
|
||||||
import { resolve } from "node:path";
|
|
||||||
import { Prisma } from "@prisma/client";
|
|
||||||
import { getTemplatePackageManifest, templatePackageRegistry } from "@personal-brand/config";
|
|
||||||
import { AdminAccessService } from "../../admin-access.service.js";
|
import { AdminAccessService } from "../../admin-access.service.js";
|
||||||
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
||||||
|
import { AdminMiniAppSettingsService } from "./admin-miniapp-settings.service.js";
|
||||||
|
import { AdminMiniAppUploadService } from "./admin-miniapp-upload.service.js";
|
||||||
import { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
|
import { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
|
||||||
import { miniappArtifactRoot, miniappProjectPath, REPOSITORY_ROOT } from "./miniapp-artifact.js";
|
|
||||||
import { miniappApiBaseUrl, validateApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
|
||||||
import { buildingStaleMs, isStaleBuilding } from "./miniapp-build-status.js";
|
|
||||||
import { decryptMiniAppCredential, encryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
|
||||||
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
|
||||||
import { runMiniAppUpload } from "./miniapp-upload.js";
|
|
||||||
import {
|
import {
|
||||||
CreateMiniAppReleaseDto,
|
CreateMiniAppReleaseDto,
|
||||||
UpdateMiniAppReleaseStatusDto,
|
UpdateMiniAppReleaseStatusDto,
|
||||||
UploadMiniAppReleaseDto,
|
UploadMiniAppReleaseDto,
|
||||||
} from "./admin-miniapp-release.dto.js";
|
} from "./admin-miniapp-release.dto.js";
|
||||||
|
|
||||||
function miniAppTemplateKey(industryTemplateKey: string): string | null {
|
type AdminIdentity = { subject: string; brandId: string };
|
||||||
return (
|
|
||||||
getTemplatePackageManifest(industryTemplateKey)?.packageKey ??
|
|
||||||
templatePackageRegistry.find((item) =>
|
|
||||||
item.supportedIndustryTemplates.includes(industryTemplateKey),
|
|
||||||
)?.packageKey ??
|
|
||||||
null
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
interface BuildLog {
|
|
||||||
at: string;
|
|
||||||
message: string;
|
|
||||||
stream: "stdout" | "stderr";
|
|
||||||
}
|
|
||||||
|
|
||||||
interface BuildProcess {
|
|
||||||
stdout: NodeJS.ReadableStream;
|
|
||||||
stderr: NodeJS.ReadableStream;
|
|
||||||
on: (event: "close" | "error", listener: (code: number | null) => void) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Controller("admin/miniapp-releases")
|
@Controller("admin/miniapp-releases")
|
||||||
export class AdminMiniAppReleaseController {
|
export class AdminMiniAppReleaseController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly access: AdminAccessService,
|
private readonly access: AdminAccessService,
|
||||||
private readonly releases: AdminMiniAppReleaseService,
|
private readonly releases: AdminMiniAppReleaseService,
|
||||||
|
private readonly settingsService: AdminMiniAppSettingsService,
|
||||||
|
private readonly uploads: AdminMiniAppUploadService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Get("latest")
|
@Get("latest")
|
||||||
async latest(@Req() request: FastifyRequest): Promise<unknown> {
|
async latest(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const identity = await this.identity(request);
|
const identity = await this.identity(request);
|
||||||
const task = await this.releases.latest(identity.brandId);
|
return (await this.releases.latest(identity.brandId)) ?? null;
|
||||||
return task ?? null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get("settings")
|
@Get("settings")
|
||||||
async settings(@Req() request: FastifyRequest): Promise<unknown> {
|
async settings(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const identity = await this.identity(request);
|
const identity = await this.identity(request);
|
||||||
const settings = this.jsonObject(await this.releases.settings(identity.brandId));
|
return this.settingsService.get(identity.brandId);
|
||||||
const buildConfig = this.buildConfigSummary(settings.apiBaseUrl, settings.appId);
|
|
||||||
return {
|
|
||||||
appId: "",
|
|
||||||
artifactPath: miniappArtifactRoot(),
|
|
||||||
build: {},
|
|
||||||
...settings,
|
|
||||||
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
|
|
||||||
privateKey: undefined,
|
|
||||||
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
|
|
||||||
hasStoredCredentials: Boolean(settings.credential),
|
|
||||||
...buildConfig,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private buildConfigSummary(
|
|
||||||
storedApiBaseUrl: unknown,
|
|
||||||
storedAppId: unknown,
|
|
||||||
): {
|
|
||||||
requestDomain: string | null;
|
|
||||||
buildError: string | null;
|
|
||||||
} {
|
|
||||||
try {
|
|
||||||
const base = miniappApiBaseUrl(storedApiBaseUrl);
|
|
||||||
weappAppId(storedAppId);
|
|
||||||
return { requestDomain: new URL(base).host, buildError: null };
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
requestDomain: null,
|
|
||||||
buildError: error instanceof Error ? error.message : "小程序构建参数未配置",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 表单回显:品牌未显式配置时展示环境推导出的默认地址,便于管理员在其基础上修改。 */
|
|
||||||
private effectiveApiBaseUrl(storedApiBaseUrl: unknown): string {
|
|
||||||
try {
|
|
||||||
return miniappApiBaseUrl(storedApiBaseUrl);
|
|
||||||
} catch {
|
|
||||||
return typeof storedApiBaseUrl === "string" ? storedApiBaseUrl : "";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch("settings")
|
@Patch("settings")
|
||||||
@@ -120,53 +41,7 @@ export class AdminMiniAppReleaseController {
|
|||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = await this.identity(request);
|
const identity = await this.identity(request);
|
||||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||||
if (body.privateKey !== undefined) {
|
return this.settingsService.update(identity.brandId, body);
|
||||||
if (!body.privateKey.trim().startsWith("-----BEGIN"))
|
|
||||||
throw new BadRequestException("上传私钥格式无效:应为 -----BEGIN 开头的 PEM 内容");
|
|
||||||
const inspection = inspectPrivateKey(body.privateKey);
|
|
||||||
if (!inspection.valid)
|
|
||||||
throw new BadRequestException(
|
|
||||||
`上传私钥无法解析(${inspection.reason ?? "PEM 格式错误"})。请粘贴微信开发者工具生成的完整私钥,注意保留换行。`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const current = this.jsonObject(await this.releases.settings(identity.brandId));
|
|
||||||
let apiBaseUrl: string | undefined;
|
|
||||||
if (body.apiBaseUrl !== undefined) {
|
|
||||||
const trimmed = body.apiBaseUrl.trim();
|
|
||||||
if (!trimmed) throw new BadRequestException("小程序请求地址不能为空");
|
|
||||||
try {
|
|
||||||
apiBaseUrl = validateApiBaseUrl(trimmed);
|
|
||||||
} catch (error) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
error instanceof Error ? error.message : "小程序请求地址无效",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const credential =
|
|
||||||
body.privateKey === undefined
|
|
||||||
? current.credential
|
|
||||||
: encryptMiniAppCredential(normalizePrivateKey(body.privateKey));
|
|
||||||
const settings = {
|
|
||||||
...current,
|
|
||||||
appId: body.appId ?? current.appId ?? "",
|
|
||||||
apiBaseUrl: apiBaseUrl ?? current.apiBaseUrl ?? "",
|
|
||||||
build: {
|
|
||||||
...this.jsonObject(current.build),
|
|
||||||
...this.jsonObject(body.build),
|
|
||||||
} as Prisma.InputJsonObject,
|
|
||||||
...(credential ? { credential } : {}),
|
|
||||||
templateKey: current.templateKey ?? null,
|
|
||||||
} satisfies Prisma.InputJsonObject;
|
|
||||||
await this.releases.saveSettings(identity.brandId, settings);
|
|
||||||
return {
|
|
||||||
appId: settings.appId,
|
|
||||||
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
|
|
||||||
artifactPath: miniappArtifactRoot(),
|
|
||||||
build: settings.build,
|
|
||||||
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
|
|
||||||
hasStoredCredentials: Boolean(settings.credential),
|
|
||||||
...this.buildConfigSummary(settings.apiBaseUrl, settings.appId),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@@ -182,213 +57,29 @@ export class AdminMiniAppReleaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post(":id/upload")
|
@Post(":id/upload")
|
||||||
async upload(
|
upload(
|
||||||
@Req() request: FastifyRequest,
|
@Req() request: FastifyRequest,
|
||||||
@Param("id") taskId: string,
|
@Param("id") taskId: string,
|
||||||
@Body() body: UploadMiniAppReleaseDto,
|
@Body() body: UploadMiniAppReleaseDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = await this.identity(request);
|
return this.identity(request).then(({ brandId, subject }) =>
|
||||||
const { task, brand } = await this.releases.uploadContext(identity.brandId, taskId);
|
this.uploads.run(brandId, subject, taskId, body),
|
||||||
if (task.status !== "built" && task.status !== "failed")
|
);
|
||||||
throw new BadRequestException("当前小程序发布任务不能重复上传");
|
|
||||||
const staleBuilding = isStaleBuilding(task);
|
|
||||||
if (task.buildStatus === "building" && !staleBuilding)
|
|
||||||
throw new ConflictException("小程序构建正在进行中,请稍后");
|
|
||||||
const settings = this.jsonObject(brand.miniAppSettings);
|
|
||||||
const appid = (() => {
|
|
||||||
try {
|
|
||||||
return weappAppId(settings.appId);
|
|
||||||
} catch (error) {
|
|
||||||
throw new BadRequestException(error instanceof Error ? error.message : "未配置微信 AppID");
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
const privateKey = settings.credential
|
|
||||||
? decryptMiniAppCredential(settings.credential)
|
|
||||||
: this.requiredEnv("WECHAT_UPLOAD_PRIVATE_KEY");
|
|
||||||
const normalizedPrivateKey = normalizePrivateKey(privateKey);
|
|
||||||
const keyInspection = inspectPrivateKey(normalizedPrivateKey);
|
|
||||||
if (!keyInspection.valid)
|
|
||||||
throw new BadRequestException(
|
|
||||||
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序上传配置”里重新粘贴完整私钥。`,
|
|
||||||
);
|
|
||||||
const templateKey = miniAppTemplateKey(brand.templateKey);
|
|
||||||
if (!templateKey) throw new BadRequestException("当前品牌模板没有可上传的小程序包");
|
|
||||||
let buildConfig: { apiBaseUrl: string; appId: string };
|
|
||||||
try {
|
|
||||||
buildConfig = {
|
|
||||||
apiBaseUrl: miniappApiBaseUrl(settings.apiBaseUrl),
|
|
||||||
appId: weappAppId(settings.appId),
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
error instanceof Error ? error.message : "小程序构建参数未配置",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const projectPath = miniappProjectPath(templateKey);
|
|
||||||
const buildLogs: BuildLog[] = [
|
|
||||||
{
|
|
||||||
at: new Date().toISOString(),
|
|
||||||
message: `开始构建 ${templateKey} 微信小程序`,
|
|
||||||
stream: "stdout",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
at: new Date().toISOString(),
|
|
||||||
message: `请求地址 ${buildConfig.apiBaseUrl},AppID ${buildConfig.appId}`,
|
|
||||||
stream: "stdout",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
if (staleBuilding)
|
|
||||||
buildLogs.push({
|
|
||||||
at: new Date().toISOString(),
|
|
||||||
message: `上一次构建已超过 ${Math.round(buildingStaleMs() / 60000)} 分钟没有进展,按中断处理并重新构建`,
|
|
||||||
stream: "stderr",
|
|
||||||
});
|
|
||||||
if (task.status === "failed") {
|
|
||||||
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
|
||||||
status: "built",
|
|
||||||
buildLogs,
|
|
||||||
buildStatus: "building",
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
|
|
||||||
buildLogs,
|
|
||||||
buildStatus: "building",
|
|
||||||
error: null,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const result = await this.buildWeApp(templateKey, buildConfig, (message, stream) => {
|
|
||||||
buildLogs.push({ at: new Date().toISOString(), message, stream });
|
|
||||||
void this.releases
|
|
||||||
.updateBuild(identity.brandId, identity.subject, taskId, {
|
|
||||||
buildLogs,
|
|
||||||
buildStatus: "building",
|
|
||||||
})
|
|
||||||
.catch(() => undefined);
|
|
||||||
});
|
|
||||||
if (result.exitCode !== 0) {
|
|
||||||
buildLogs.push({
|
|
||||||
at: new Date().toISOString(),
|
|
||||||
message: `构建失败,退出码 ${result.exitCode}`,
|
|
||||||
stream: "stderr",
|
|
||||||
});
|
|
||||||
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
|
|
||||||
error: `小程序构建失败,请查看构建日志`,
|
|
||||||
buildLogs,
|
|
||||||
buildStatus: "failed",
|
|
||||||
});
|
|
||||||
throw new BadRequestException("小程序构建失败,请查看构建日志");
|
|
||||||
}
|
|
||||||
if (!existsSync(projectPath) || !existsSync(resolve(projectPath, "app.json"))) {
|
|
||||||
buildLogs.push({
|
|
||||||
at: new Date().toISOString(),
|
|
||||||
message: `构建完成但缺少产物:${projectPath}/app.json`,
|
|
||||||
stream: "stderr",
|
|
||||||
});
|
|
||||||
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
|
|
||||||
error: "小程序构建产物缺少 app.json",
|
|
||||||
buildLogs,
|
|
||||||
buildStatus: "failed",
|
|
||||||
});
|
|
||||||
throw new BadRequestException(`小程序构建产物缺少 app.json:${projectPath}`);
|
|
||||||
}
|
|
||||||
buildLogs.push({
|
|
||||||
at: new Date().toISOString(),
|
|
||||||
message: "构建完成,开始上传微信",
|
|
||||||
stream: "stdout",
|
|
||||||
});
|
|
||||||
await this.releases.updateBuild(identity.brandId, identity.subject, taskId, {
|
|
||||||
buildLogs,
|
|
||||||
buildStatus: "success",
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
const uploadResult = await runMiniAppUpload({
|
|
||||||
projectPath,
|
|
||||||
appid,
|
|
||||||
privateKey: normalizedPrivateKey,
|
|
||||||
version: body.version ?? String(task.version),
|
|
||||||
desc: body.desc ?? `brand content v${task.version}`,
|
|
||||||
robot: body.robot ?? 1,
|
|
||||||
});
|
|
||||||
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
|
||||||
status: "uploaded",
|
|
||||||
buildLogs,
|
|
||||||
buildStatus: "success",
|
|
||||||
weappUploadId:
|
|
||||||
typeof uploadResult.strUint64Version === "string"
|
|
||||||
? uploadResult.strUint64Version
|
|
||||||
: String(task.version),
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
const message = error instanceof Error ? error.message : "微信代码上传失败";
|
|
||||||
await this.releases.updateStatus(identity.brandId, identity.subject, taskId, {
|
|
||||||
status: "failed",
|
|
||||||
buildLogs,
|
|
||||||
buildStatus: "failed",
|
|
||||||
error: message,
|
|
||||||
});
|
|
||||||
throw new BadGatewayException(message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(":id/status")
|
@Patch(":id/status")
|
||||||
async updateStatus(
|
updateStatus(
|
||||||
@Req() request: FastifyRequest,
|
@Req() request: FastifyRequest,
|
||||||
@Param("id") taskId: string,
|
@Param("id") taskId: string,
|
||||||
@Body() body: UpdateMiniAppReleaseStatusDto,
|
@Body() body: UpdateMiniAppReleaseStatusDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = await this.identity(request);
|
return this.identity(request).then(({ brandId, subject }) =>
|
||||||
return this.releases.updateStatus(identity.brandId, identity.subject, taskId, body);
|
this.releases.updateStatus(brandId, subject, taskId, body),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async identity(request: FastifyRequest): Promise<{ subject: string; brandId: string }> {
|
private async identity(request: FastifyRequest): Promise<AdminIdentity> {
|
||||||
const { subject, brandId } = await this.access.requireBrand(request);
|
const { subject, brandId } = await this.access.requireBrand(request);
|
||||||
return { subject, brandId };
|
return { subject, brandId };
|
||||||
}
|
}
|
||||||
|
|
||||||
private requiredEnv(name: string): string {
|
|
||||||
const value = process.env[name];
|
|
||||||
if (!value) throw new BadRequestException(`${name} 未配置`);
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
private buildWeApp(
|
|
||||||
templateKey: string,
|
|
||||||
buildConfig: { apiBaseUrl: string; appId: string },
|
|
||||||
onLog: (message: string, stream: "stdout" | "stderr") => void,
|
|
||||||
): Promise<{ exitCode: number }> {
|
|
||||||
return new Promise((resolvePromise, rejectPromise) => {
|
|
||||||
const child = spawn("pnpm", ["--filter", "@personal-brand/taro", "build:weapp"], {
|
|
||||||
cwd: REPOSITORY_ROOT,
|
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
TEMPLATE_KEY: templateKey,
|
|
||||||
TARO_ENV: "weapp",
|
|
||||||
API_BASE_URL: buildConfig.apiBaseUrl,
|
|
||||||
WEAPP_APP_ID: buildConfig.appId,
|
|
||||||
},
|
|
||||||
shell: process.platform === "win32",
|
|
||||||
}) as BuildProcess;
|
|
||||||
const readStream = (stream: NodeJS.ReadableStream, name: "stdout" | "stderr") => {
|
|
||||||
let buffer = "";
|
|
||||||
stream.on("data", (chunk: Buffer | string) => {
|
|
||||||
buffer += chunk.toString();
|
|
||||||
for (const message of buffer.split("\n").slice(0, -1)) onLog(message, name);
|
|
||||||
buffer = buffer.slice(buffer.lastIndexOf("\n") + 1);
|
|
||||||
});
|
|
||||||
stream.on("end", () => {
|
|
||||||
if (buffer) onLog(buffer, name);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
readStream(child.stdout, "stdout");
|
|
||||||
readStream(child.stderr, "stderr");
|
|
||||||
child.on("close", (code) => resolvePromise({ exitCode: code ?? 1 }));
|
|
||||||
child.on("error", () => rejectPromise(new Error("小程序构建进程启动失败")));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private jsonObject(value: unknown): Record<string, unknown> {
|
|
||||||
return value && typeof value === "object" && !Array.isArray(value)
|
|
||||||
? (value as Record<string, unknown>)
|
|
||||||
: {};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
|
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
||||||
|
import { miniappArtifactRoot } from "./miniapp-artifact.js";
|
||||||
|
import { miniappApiBaseUrl, validateApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
||||||
|
import { encryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
||||||
|
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
||||||
|
import type { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdminMiniAppSettingsService {
|
||||||
|
constructor(private readonly releases: AdminMiniAppReleaseService) {}
|
||||||
|
|
||||||
|
async get(brandId: string): Promise<unknown> {
|
||||||
|
const settings = this.jsonObject(await this.releases.settings(brandId));
|
||||||
|
return this.present(settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(brandId: string, body: UpdateMiniAppSettingsDto & { privateKey?: string }) {
|
||||||
|
if (body.privateKey !== undefined) this.validatePrivateKey(body.privateKey);
|
||||||
|
const current = this.jsonObject(await this.releases.settings(brandId));
|
||||||
|
const settings = {
|
||||||
|
...current,
|
||||||
|
appId: body.appId ?? current.appId ?? "",
|
||||||
|
apiBaseUrl:
|
||||||
|
body.apiBaseUrl === undefined ? (current.apiBaseUrl ?? "") : this.apiBaseUrl(body),
|
||||||
|
build: {
|
||||||
|
...this.jsonObject(current.build),
|
||||||
|
...this.jsonObject(body.build),
|
||||||
|
} as Prisma.InputJsonObject,
|
||||||
|
...(body.privateKey === undefined
|
||||||
|
? {}
|
||||||
|
: { credential: encryptMiniAppCredential(normalizePrivateKey(body.privateKey)) }),
|
||||||
|
templateKey: current.templateKey ?? null,
|
||||||
|
} satisfies Prisma.InputJsonObject;
|
||||||
|
await this.releases.saveSettings(brandId, settings);
|
||||||
|
return this.present(settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
private validatePrivateKey(privateKey: string) {
|
||||||
|
if (!privateKey.trim().startsWith("-----BEGIN"))
|
||||||
|
throw new BadRequestException("上传私钥格式无效:应为 -----BEGIN 开头的 PEM 内容");
|
||||||
|
const inspection = inspectPrivateKey(privateKey);
|
||||||
|
if (!inspection.valid)
|
||||||
|
throw new BadRequestException(
|
||||||
|
`上传私钥无法解析(${inspection.reason ?? "PEM 格式错误"})。请粘贴微信开发者工具生成的完整私钥,注意保留换行。`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private apiBaseUrl(body: UpdateMiniAppSettingsDto) {
|
||||||
|
const trimmed = body.apiBaseUrl?.trim();
|
||||||
|
if (!trimmed) throw new BadRequestException("小程序请求地址不能为空");
|
||||||
|
try {
|
||||||
|
return validateApiBaseUrl(trimmed);
|
||||||
|
} catch (error) {
|
||||||
|
throw new BadRequestException(error instanceof Error ? error.message : "小程序请求地址无效");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private present(settings: Record<string, unknown>) {
|
||||||
|
return {
|
||||||
|
appId: "",
|
||||||
|
artifactPath: miniappArtifactRoot(),
|
||||||
|
build: {},
|
||||||
|
...settings,
|
||||||
|
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
|
||||||
|
privateKey: undefined,
|
||||||
|
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
|
||||||
|
hasStoredCredentials: Boolean(settings.credential),
|
||||||
|
...this.buildConfigSummary(settings.apiBaseUrl, settings.appId),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildConfigSummary(
|
||||||
|
storedApiBaseUrl: unknown,
|
||||||
|
storedAppId: unknown,
|
||||||
|
): {
|
||||||
|
requestDomain: string | null;
|
||||||
|
buildError: string | null;
|
||||||
|
} {
|
||||||
|
try {
|
||||||
|
const base = miniappApiBaseUrl(storedApiBaseUrl);
|
||||||
|
weappAppId(storedAppId);
|
||||||
|
return { requestDomain: new URL(base).host, buildError: null };
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
requestDomain: null,
|
||||||
|
buildError: error instanceof Error ? error.message : "小程序构建参数未配置",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 表单回显:品牌未显式配置时展示环境推导出的默认地址,便于管理员在其基础上修改。 */
|
||||||
|
private effectiveApiBaseUrl(storedApiBaseUrl: unknown) {
|
||||||
|
try {
|
||||||
|
return miniappApiBaseUrl(storedApiBaseUrl);
|
||||||
|
} catch {
|
||||||
|
return typeof storedApiBaseUrl === "string" ? storedApiBaseUrl : "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private jsonObject(value: unknown): Record<string, unknown> {
|
||||||
|
return value && typeof value === "object" && !Array.isArray(value)
|
||||||
|
? (value as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import {
|
||||||
|
BadGatewayException,
|
||||||
|
BadRequestException,
|
||||||
|
ConflictException,
|
||||||
|
Injectable,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import { existsSync } from "node:fs";
|
||||||
|
import { resolve } from "node:path";
|
||||||
|
import { getTemplatePackageManifest, templatePackageRegistry } from "@personal-brand/config";
|
||||||
|
import { AdminMiniAppBuildService } from "./admin-miniapp-build.service.js";
|
||||||
|
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
||||||
|
import { miniappProjectPath } from "./miniapp-artifact.js";
|
||||||
|
import { miniappApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
||||||
|
import { buildingStaleMs, isStaleBuilding } from "./miniapp-build-status.js";
|
||||||
|
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
||||||
|
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
||||||
|
import { runMiniAppUpload } from "./miniapp-upload.js";
|
||||||
|
|
||||||
|
interface BuildLog {
|
||||||
|
at: string;
|
||||||
|
message: string;
|
||||||
|
stream: "stdout" | "stderr";
|
||||||
|
}
|
||||||
|
|
||||||
|
function miniAppTemplateKey(industryTemplateKey: string): string | null {
|
||||||
|
return (
|
||||||
|
getTemplatePackageManifest(industryTemplateKey)?.packageKey ??
|
||||||
|
templatePackageRegistry.find((item) =>
|
||||||
|
item.supportedIndustryTemplates.includes(industryTemplateKey),
|
||||||
|
)?.packageKey ??
|
||||||
|
null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function log(message: string, stream: "stdout" | "stderr"): BuildLog {
|
||||||
|
return { at: new Date().toISOString(), message, stream };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdminMiniAppUploadService {
|
||||||
|
constructor(
|
||||||
|
private readonly releases: AdminMiniAppReleaseService,
|
||||||
|
private readonly builds: AdminMiniAppBuildService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async run(
|
||||||
|
brandId: string,
|
||||||
|
actorId: string,
|
||||||
|
taskId: string,
|
||||||
|
input: { version?: string; desc?: string; robot?: number },
|
||||||
|
): Promise<unknown> {
|
||||||
|
const { task, brand } = await this.releases.uploadContext(brandId, taskId);
|
||||||
|
if (task.status !== "built" && task.status !== "failed")
|
||||||
|
throw new BadRequestException("当前小程序发布任务不能重复上传");
|
||||||
|
const staleBuilding = isStaleBuilding(task);
|
||||||
|
if (task.buildStatus === "building" && !staleBuilding)
|
||||||
|
throw new ConflictException("小程序构建正在进行中,请稍后");
|
||||||
|
|
||||||
|
const settings = this.jsonObject(brand.miniAppSettings);
|
||||||
|
const appId = weappAppId(settings.appId);
|
||||||
|
const privateKey = settings.credential
|
||||||
|
? decryptMiniAppCredential(settings.credential)
|
||||||
|
: this.requiredEnv("WECHAT_UPLOAD_PRIVATE_KEY");
|
||||||
|
const normalizedPrivateKey = normalizePrivateKey(privateKey);
|
||||||
|
const keyInspection = inspectPrivateKey(normalizedPrivateKey);
|
||||||
|
if (!keyInspection.valid)
|
||||||
|
throw new BadRequestException(
|
||||||
|
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序上传配置”里重新粘贴完整私钥。`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const templateKey = miniAppTemplateKey(brand.templateKey);
|
||||||
|
if (!templateKey) throw new BadRequestException("当前品牌模板没有可上传的小程序包");
|
||||||
|
const buildConfig = { apiBaseUrl: miniappApiBaseUrl(settings.apiBaseUrl), appId };
|
||||||
|
const projectPath = miniappProjectPath(templateKey);
|
||||||
|
const buildLogs = [
|
||||||
|
log(`开始构建 ${templateKey} 微信小程序`, "stdout"),
|
||||||
|
log(`请求地址 ${buildConfig.apiBaseUrl},AppID ${buildConfig.appId}`, "stdout"),
|
||||||
|
];
|
||||||
|
if (staleBuilding)
|
||||||
|
buildLogs.push(
|
||||||
|
log(
|
||||||
|
`上一次构建已超过 ${Math.round(buildingStaleMs() / 60000)} 分钟没有进展,按中断处理并重新构建`,
|
||||||
|
"stderr",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (task.status === "failed") {
|
||||||
|
await this.releases.updateStatus(brandId, actorId, taskId, {
|
||||||
|
status: "built",
|
||||||
|
buildLogs,
|
||||||
|
buildStatus: "building",
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await this.releases.updateBuild(brandId, actorId, taskId, {
|
||||||
|
buildLogs,
|
||||||
|
buildStatus: "building",
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.builds.run(templateKey, buildConfig, (message, stream) => {
|
||||||
|
buildLogs.push(log(message, stream));
|
||||||
|
void this.releases
|
||||||
|
.updateBuild(brandId, actorId, taskId, { buildLogs, buildStatus: "building" })
|
||||||
|
.catch(() => undefined);
|
||||||
|
});
|
||||||
|
if (result.exitCode !== 0) {
|
||||||
|
buildLogs.push(log(`构建失败,退出码 ${result.exitCode}`, "stderr"));
|
||||||
|
await this.releases.updateBuild(brandId, actorId, taskId, {
|
||||||
|
error: "小程序构建失败,请查看构建日志",
|
||||||
|
buildLogs,
|
||||||
|
buildStatus: "failed",
|
||||||
|
});
|
||||||
|
throw new BadRequestException("小程序构建失败,请查看构建日志");
|
||||||
|
}
|
||||||
|
if (!existsSync(projectPath) || !existsSync(resolve(projectPath, "app.json"))) {
|
||||||
|
buildLogs.push(log(`构建完成但缺少产物:${projectPath}/app.json`, "stderr"));
|
||||||
|
await this.releases.updateBuild(brandId, actorId, taskId, {
|
||||||
|
error: "小程序构建产物缺少 app.json",
|
||||||
|
buildLogs,
|
||||||
|
buildStatus: "failed",
|
||||||
|
});
|
||||||
|
throw new BadRequestException(`小程序构建产物缺少 app.json:${projectPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
buildLogs.push(log("构建完成,开始上传微信", "stdout"));
|
||||||
|
await this.releases.updateBuild(brandId, actorId, taskId, {
|
||||||
|
buildLogs,
|
||||||
|
buildStatus: "success",
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const uploadResult = await runMiniAppUpload({
|
||||||
|
projectPath,
|
||||||
|
appid: appId,
|
||||||
|
privateKey: normalizedPrivateKey,
|
||||||
|
version: input.version ?? String(task.version),
|
||||||
|
desc: input.desc ?? `brand content v${task.version}`,
|
||||||
|
robot: input.robot ?? 1,
|
||||||
|
});
|
||||||
|
return this.releases.updateStatus(brandId, actorId, taskId, {
|
||||||
|
status: "uploaded",
|
||||||
|
buildLogs,
|
||||||
|
buildStatus: "success",
|
||||||
|
weappUploadId:
|
||||||
|
typeof uploadResult.strUint64Version === "string"
|
||||||
|
? uploadResult.strUint64Version
|
||||||
|
: String(task.version),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : "微信代码上传失败";
|
||||||
|
await this.releases.updateStatus(brandId, actorId, taskId, {
|
||||||
|
status: "failed",
|
||||||
|
buildLogs,
|
||||||
|
buildStatus: "failed",
|
||||||
|
error: message,
|
||||||
|
});
|
||||||
|
throw new BadGatewayException(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private requiredEnv(name: string): string {
|
||||||
|
const value = process.env[name];
|
||||||
|
if (!value) throw new BadRequestException(`${name} 未配置`);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private jsonObject(value: unknown): Record<string, unknown> {
|
||||||
|
return value && typeof value === "object" && !Array.isArray(value)
|
||||||
|
? (value as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user