TaskBuilderChapter.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. import {
  2. Button,
  3. Divider,
  4. Input,
  5. Modal,
  6. notification,
  7. Space,
  8. Steps,
  9. Typography,
  10. } from "antd";
  11. import { useState } from "react";
  12. import Workflow from "./Workflow";
  13. import type {
  14. IProjectTreeData,
  15. IProjectTreeInsertRequest,
  16. IProjectTreeResponse,
  17. ITaskData,
  18. ITaskGroupInsertData,
  19. ITaskGroupInsertRequest,
  20. ITaskGroupResponse,
  21. } from "../../api/task";
  22. import ChapterToc from "../article/ChapterToc";
  23. import type { IChapterToc } from "../../api/Corpus";
  24. import { post } from "../../request";
  25. import TaskBuilderProp, { type IParam, IProp } from "./TaskBuilderProp";
  26. import type {
  27. IPayload,
  28. ITokenCreate,
  29. ITokenCreateResponse,
  30. ITokenData,
  31. TPower,
  32. } from "../../api/token";
  33. import ProjectWithTasks from "./ProjectWithTasks";
  34. import { useIntl } from "react-intl";
  35. import React from "react";
  36. const { Text, Paragraph } = Typography;
  37. interface IModal {
  38. studioName?: string;
  39. channels?: string[];
  40. book?: number;
  41. para?: number;
  42. open?: boolean;
  43. onClose?: () => void;
  44. }
  45. export const TaskBuilderChapterModal = ({
  46. studioName,
  47. channels,
  48. book,
  49. para,
  50. open = false,
  51. onClose,
  52. }: IModal) => {
  53. return (
  54. <>
  55. <Modal
  56. destroyOnHidden={true}
  57. maskClosable={false}
  58. width={1400}
  59. style={{ top: 10 }}
  60. title={""}
  61. footer={false}
  62. open={open}
  63. onOk={onClose}
  64. onCancel={onClose}
  65. >
  66. <TaskBuilderChapter
  67. style={{ marginTop: 20 }}
  68. studioName={studioName}
  69. channels={channels}
  70. book={book}
  71. para={para}
  72. />
  73. </Modal>
  74. </>
  75. );
  76. };
  77. type NotificationType = "success" | "info" | "warning" | "error";
  78. interface IWidget {
  79. studioName?: string;
  80. channels?: string[];
  81. book?: number;
  82. para?: number;
  83. style?: React.CSSProperties;
  84. }
  85. const TaskBuilderChapter = ({
  86. studioName,
  87. book,
  88. para,
  89. style,
  90. channels,
  91. }: IWidget) => {
  92. const intl = useIntl();
  93. const [current, setCurrent] = useState(0);
  94. const [workflow, setWorkflow] = useState<ITaskData[]>();
  95. const [chapter, setChapter] = useState<IChapterToc[]>();
  96. const [tokens, setTokens] = useState<ITokenData[]>();
  97. const [messages, setMessages] = useState<string[]>([]);
  98. const [prop, setProp] = useState<IProp[]>();
  99. const [title, setTitle] = useState<string>();
  100. const [loading, setLoading] = useState(false);
  101. const [projects, setProjects] = useState<IProjectTreeData[]>();
  102. const [done, setDone] = useState(false);
  103. const steps = [
  104. {
  105. title: "选择章节",
  106. content: (
  107. <div style={{ padding: 8 }}>
  108. <Space key={1}>
  109. <Text type="secondary">{"任务组标题"}</Text>
  110. <Input
  111. value={title}
  112. onChange={(e) => {
  113. setTitle(e.target.value);
  114. }}
  115. />
  116. </Space>
  117. <ChapterToc
  118. key={2}
  119. book={book}
  120. para={para}
  121. maxLevel={7}
  122. onData={(data: IChapterToc[]) => {
  123. setChapter(data);
  124. if (data.length > 0) {
  125. if (!title && data[0].text) {
  126. setTitle(data[0].text);
  127. }
  128. }
  129. }}
  130. />
  131. </div>
  132. ),
  133. },
  134. {
  135. title: "选择工作流",
  136. content: (
  137. <Workflow
  138. studioName={studioName}
  139. onSelect={(data) => {
  140. if (typeof data === "undefined") {
  141. setWorkflow(undefined);
  142. }
  143. }}
  144. onData={(data) => {
  145. console.debug("workflow", data);
  146. setWorkflow(data);
  147. }}
  148. />
  149. ),
  150. },
  151. {
  152. title: "参数设置",
  153. content: (
  154. <div>
  155. <TaskBuilderProp
  156. book={book}
  157. para={para}
  158. workflow={workflow}
  159. channelsId={channels}
  160. onChange={(data: IProp[] | undefined) => {
  161. console.info("TaskBuilderProp prop value", data);
  162. setProp(data);
  163. const channels = new Map<string, number>();
  164. data?.forEach((value) => {
  165. value.param?.forEach((param) => {
  166. if (param.type.includes("channel")) {
  167. channels.set(param.value, 1);
  168. }
  169. });
  170. });
  171. //获取channel token
  172. let payload: IPayload[] = [];
  173. if (chapter) {
  174. channels.forEach((_value, key) => {
  175. const [channelId, power] = key.split("@");
  176. payload = payload.concat(
  177. chapter.map((item) => {
  178. return {
  179. res_id: channelId,
  180. res_type: "channel",
  181. book: item.book,
  182. para_start: item.paragraph,
  183. para_end: item.paragraph + item.chapter_len,
  184. power: power as TPower,
  185. };
  186. })
  187. );
  188. });
  189. const url = "/v2/access-token";
  190. const values = { payload: payload };
  191. console.info("api request", url, values);
  192. post<ITokenCreate, ITokenCreateResponse>(url, values).then(
  193. (json) => {
  194. console.info("api response token", json);
  195. setTokens(json.data.rows);
  196. }
  197. );
  198. }
  199. }}
  200. />
  201. </div>
  202. ),
  203. },
  204. {
  205. title: "生成任务",
  206. content: (
  207. <div style={{ padding: 8 }}>
  208. <div>
  209. <Space>
  210. <Text type="secondary">title</Text>
  211. <Text>{title}</Text>
  212. </Space>
  213. </div>
  214. <div>
  215. <Space>
  216. <Text type="secondary">新增任务组</Text>
  217. <Text>{chapter?.length}</Text>
  218. </Space>
  219. </div>
  220. <div>
  221. <Space>
  222. <Text type="secondary">每个任务组任务数量</Text>
  223. <Text>{workflow?.length}</Text>
  224. </Space>
  225. </div>
  226. <div>
  227. <Paragraph>点击生成按钮生成</Paragraph>
  228. </div>
  229. <div>
  230. {messages?.map((item, id) => {
  231. return <div key={id}>{item}</div>;
  232. })}
  233. </div>
  234. </div>
  235. ),
  236. },
  237. {
  238. title: "完成",
  239. content: projects ? (
  240. <ProjectWithTasks projectId={projects[0].id} />
  241. ) : (
  242. <></>
  243. ),
  244. },
  245. ];
  246. const next = () => {
  247. setCurrent(current + 1);
  248. };
  249. const prev = () => {
  250. setCurrent(current - 1);
  251. };
  252. const items = steps.map((item) => ({ key: item.title, title: item.title }));
  253. const [api, contextHolder] = notification.useNotification();
  254. const openNotification = (
  255. type: NotificationType,
  256. title: string,
  257. description?: string
  258. ) => {
  259. api[type]({
  260. message: title,
  261. description: description,
  262. });
  263. };
  264. //生成任务组
  265. const projectGroup = async () => {
  266. if (!studioName || !chapter) {
  267. console.error("缺少参数", studioName, chapter);
  268. return;
  269. }
  270. const url = "/v2/project-tree";
  271. const values: IProjectTreeInsertRequest = {
  272. studio_name: studioName,
  273. data: chapter.map((item, id) => {
  274. return {
  275. id: item.paragraph.toString(),
  276. title: id === 0 && title ? title : (item.text ?? ""),
  277. type: "instance",
  278. weight: item.chapter_strlen,
  279. parent_id: item.parent.toString(),
  280. res_id: `${item.book}-${item.paragraph}`,
  281. };
  282. }),
  283. };
  284. let res;
  285. try {
  286. console.info("api request", url, values);
  287. res = await post<IProjectTreeInsertRequest, IProjectTreeResponse>(
  288. url,
  289. values
  290. );
  291. console.info("api response", res);
  292. // 检查响应状态
  293. if (!res.ok) {
  294. throw new Error(`HTTP error! status: `);
  295. }
  296. setProjects(res.data.rows);
  297. setMessages((origin) => [...origin, "生成任务组成功"]);
  298. } catch (error) {
  299. console.error("Fetch error:", error);
  300. openNotification("error", "生成任务组失败");
  301. throw error;
  302. }
  303. return res.data.rows;
  304. };
  305. const DoButton = () => {
  306. return (
  307. <>
  308. <Button
  309. loading={loading}
  310. disabled={loading}
  311. type="primary"
  312. onClick={async () => {
  313. if (!studioName || !chapter) {
  314. console.error("缺少参数", studioName, chapter);
  315. return;
  316. }
  317. setLoading(true);
  318. //生成projects
  319. setMessages((origin) => [...origin, "正在生成任务组……"]);
  320. const res = await projectGroup();
  321. if (!res) {
  322. return;
  323. }
  324. //生成tasks
  325. setMessages((origin) => [...origin, "正在生成任务……"]);
  326. const taskUrl = "/v2/task-group";
  327. if (!workflow) {
  328. return;
  329. }
  330. const taskData: ITaskGroupInsertData[] = res
  331. .filter((value) => value.isLeaf)
  332. .map((project, pId) => {
  333. return {
  334. project_id: project.id,
  335. tasks: workflow.map((task, _tId) => {
  336. let newContent = task.description;
  337. prop
  338. ?.find((pValue) => pValue.taskId === task.id)
  339. ?.param?.forEach((value: IParam) => {
  340. //替换数字参数
  341. if (value.type === "number") {
  342. const searchValue = `${value.key}=${value.value}`;
  343. const replaceValue =
  344. `${value.key}=` +
  345. (value.initValue + value.step * pId).toString();
  346. newContent = newContent?.replace(
  347. searchValue,
  348. replaceValue
  349. );
  350. } else {
  351. //替换book
  352. if (project.resId) {
  353. const [book, paragraph] = project.resId.split("-");
  354. newContent = newContent?.replace(
  355. "book=#",
  356. `book=${book}`
  357. );
  358. newContent = newContent?.replace(
  359. "paragraphs=#",
  360. `paragraphs=${paragraph}`
  361. );
  362. //替换channel
  363. //查找toke
  364. const [channel, power] = value.value.split("@");
  365. const mToken = tokens?.find(
  366. (token) =>
  367. token.payload.book?.toString() === book &&
  368. token.payload.para_start?.toString() ===
  369. paragraph &&
  370. token.payload.res_id === channel &&
  371. (power && power.length > 0
  372. ? token.payload.power === power
  373. : true)
  374. );
  375. if (!mToken) {
  376. console.warn(
  377. "token not found",
  378. book,
  379. paragraph,
  380. channel,
  381. power
  382. );
  383. }
  384. newContent = newContent?.replace(
  385. value.key,
  386. channel + (mToken ? "@" + mToken?.token : "")
  387. );
  388. }
  389. }
  390. });
  391. console.debug("description", newContent);
  392. return {
  393. ...task,
  394. type: "instance",
  395. description: newContent,
  396. };
  397. }),
  398. };
  399. });
  400. console.info("api request", taskUrl, taskData);
  401. const taskRes = await post<
  402. ITaskGroupInsertRequest,
  403. ITaskGroupResponse
  404. >(taskUrl, { data: taskData });
  405. if (taskRes.ok) {
  406. setMessages((origin) => [...origin, "生成任务成功"]);
  407. setMessages((origin) => [
  408. ...origin,
  409. "生成任务" + taskRes.data.taskCount,
  410. ]);
  411. setMessages((origin) => [
  412. ...origin,
  413. "生成任务关联" + taskRes.data.taskRelationCount,
  414. ]);
  415. setMessages((origin) => [
  416. ...origin,
  417. "打开译经楼-我的任务查看已经生成的任务",
  418. ]);
  419. openNotification("success", "生成任务成功");
  420. setDone(true);
  421. }
  422. setLoading(false);
  423. }}
  424. >
  425. Done
  426. </Button>
  427. </>
  428. );
  429. };
  430. return (
  431. <div style={style}>
  432. {contextHolder}
  433. <Steps current={current} items={items} />
  434. <div className="steps-content" style={{ minHeight: 400 }}>
  435. {steps[current].content}
  436. </div>
  437. <Divider></Divider>
  438. <div style={{ display: "flex", justifyContent: "space-between" }}>
  439. {current < steps.length - 1 ? (
  440. <Button
  441. style={{ margin: "0 8px" }}
  442. disabled={current === 0}
  443. onClick={() => prev()}
  444. >
  445. {intl.formatMessage({ id: "buttons.previous" })}
  446. </Button>
  447. ) : (
  448. <></>
  449. )}
  450. {current < steps.length - 2 && (
  451. <Button
  452. type="primary"
  453. disabled={current === 1 && typeof workflow === "undefined"}
  454. onClick={() => next()}
  455. >
  456. {intl.formatMessage({ id: "buttons.next" })}
  457. </Button>
  458. )}
  459. {current === steps.length - 2 && (
  460. <>
  461. {done ? (
  462. <Button type="primary" onClick={() => next()}>
  463. 完成
  464. </Button>
  465. ) : (
  466. <DoButton />
  467. )}
  468. </>
  469. )}
  470. </div>
  471. </div>
  472. );
  473. };
  474. export default TaskBuilderChapter;