func-tbook-export.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. import { replaceDocx, createZip, uploadFileToOSS, docxToPdf, renderDocx, toBarCode, downloadUrl } from "../../lib/docs";
  2. // const Parse = global.Parse;
  3. const path = require("path")
  4. const fs = require("fs")
  5. var TemplateDocxDir = path.join(__dirname,"template")
  6. if(!fs.existsSync(TemplateDocxDir)){
  7. TemplateDocxDir = path.join(__dirname,"../../template")
  8. }
  9. const tempDir = path.join(__dirname , "temp");
  10. const crypto = require('crypto');
  11. /**
  12. * 常用Word字符
  13. */
  14. // 圆圈选中未选 ○ 未选 ● 选中
  15. const circleCheck = ["○","●"];
  16. // 方块选中未选 ○ 未选 ● 选中
  17. const squareCheck = [`□`,String.fromCharCode(0xFE)];
  18. /**
  19. * 定义导出申报合集文档云函数
  20. * @example
  21. * Cloud Code test
  22. 导出流程
  23. curl -X POST -H "Content-Type: application/json" -H 'X-Parse-Application-Id: edu-textbook' -d '{ "processId": "FR7KZtefyR" }' http://127.0.0.1:61337/parse/functions/tbookExportReport
  24. curl -X POST -H "Content-Type: application/json" -H 'X-Parse-Application-Id: edu-textbook' -d '{ "processId": "FR7KZtefyR" }' http://8.140.98.43/parse/functions/tbookExportReport
  25. curl -X POST -H "Content-Type: application/json" -H 'X-Parse-Application-Id: edu-textbook' -d '{ "processId": "FR7KZtefyR" }' http://8.140.98.43/parse/api/tbook/export
  26. curl -X POST -H "Content-Type: application/json" -H 'X-Parse-Application-Id: edu-textbook' -d '{ "processId": "FR7KZtefyR" }' https://145.tbook.com.cn/parse/api/tbook/export
  27. 导出教材列表
  28. curl -X POST -H "Content-Type: application/json" -H 'X-Parse-Application-Id: edu-textbook' -d '{ "bookList": ["9V575dapEM","2YBKitpCJL","xLdiEaHGrX"] }' http://8.140.98.43/parse/functions/tbookExportReport
  29. */
  30. export function defineTbookExportReport(app){
  31. // 全新导出,每次都重新导出
  32. app.post("/parse/api/tbook/export",async (request,res)=>{
  33. let processId = request.body.processId;
  34. let bookList = request.body.bookList;
  35. console.log(request.body)
  36. try{
  37. let result
  38. if(processId){
  39. result = await exportProcessReportDocs(processId)
  40. }
  41. if(bookList?.length){
  42. result = await exportProcessReportDocs(null,bookList)
  43. }
  44. if(result?.docsList?.length==0){
  45. // throw new Parse.Error(404,"合集内无申报教材")
  46. res.json({
  47. code:400,
  48. err:"合集内无申报教材"
  49. })
  50. return
  51. }
  52. // return result
  53. res.json({
  54. code:200,
  55. result:result
  56. })
  57. return
  58. }catch(err){
  59. console.error(err)
  60. res.json({
  61. code:400,
  62. err:err
  63. })
  64. return
  65. // throw new Parse.Error(404,"导出申报合集失败")
  66. }
  67. // throw new Parse.Error(404,"未找到该流程合集")
  68. })
  69. // 预览导出:已导出直接返回
  70. // curl -X POST -H "Content-Type: application/json" -H 'X-Parse-Application-Id: edu-textbook' -d '{ "bookid": "j4pt2MMTXM" }' https://145.tbook.com.cn/parse/api/tbook/preview
  71. app.post("/parse/api/tbook/preview",async (request,res)=>{
  72. let bookid = request.body.bookid;
  73. let isNew = request.body.isNew || false;
  74. try{
  75. let result
  76. if(bookid){
  77. let book
  78. if(!isNew){
  79. let query = new Parse.Query("EduTextbook")
  80. query.include("childrens","department")
  81. book = await query.get(bookid);
  82. }
  83. if(book?.get("export")){
  84. res.json({
  85. code:200,
  86. data:{
  87. urlPdf:book?.get("export")
  88. }
  89. })
  90. return
  91. }
  92. result = await exportProcessReportDocs(null,[bookid])
  93. let urlPdf = result?.docsList?.[0]?.urlPdf;
  94. if(urlPdf){
  95. book.set('export',urlPdf);
  96. book.save();
  97. res.json({
  98. code:200,
  99. data:{
  100. urlPdf:urlPdf
  101. }
  102. })
  103. return
  104. }
  105. }
  106. console.log(result)
  107. if(result?.docsList?.length==0){
  108. // throw new Parse.Error(404,"合集内无申报教材")
  109. res.json({
  110. code:400,
  111. err:"无该教材"
  112. })
  113. return
  114. }
  115. // return result
  116. res.json({
  117. code:200,
  118. result:result
  119. })
  120. return
  121. }catch(err){
  122. console.error(err)
  123. res.json({
  124. code:400,
  125. err:err
  126. })
  127. return
  128. // throw new Parse.Error(404,"导出申报合集失败")
  129. }
  130. // throw new Parse.Error(404,"未找到该流程合集")
  131. })
  132. Parse.Cloud.define("tbookExportReport", async (request) => {
  133. let processId = request.params.processId;
  134. let bookList = request.params.bookList;
  135. try{
  136. let result
  137. if(processId){
  138. result = await exportProcessReportDocs(processId)
  139. }
  140. if(bookList?.length){
  141. result = await exportProcessReportDocs(null,bookList)
  142. }
  143. if(result?.docsList?.length==0){
  144. throw new Parse.Error(404,"合集内无申报教材")
  145. }
  146. return result
  147. }catch(err){
  148. console.error(err)
  149. throw new Parse.Error(404,"导出申报合集失败")
  150. }
  151. throw new Parse.Error(404,"未找到该流程合集")
  152. },{
  153. fields : {
  154. processId:{
  155. required:false
  156. },
  157. }
  158. });
  159. }
  160. /**
  161. * 导出流程教材申报文件
  162. * @returns
  163. * docsList
  164. * zipUrl
  165. */
  166. export async function exportProcessReportDocs(processId,bookList) {
  167. if(!processId && !bookList?.length) return {}
  168. let textbookList
  169. if(processId){ // 流程读取教材列表
  170. let query = new Parse.Query("EduTextbook")
  171. query.include("childrens","department")
  172. query.equalTo("recommend",true);
  173. query.equalTo("eduProcess",processId);
  174. textbookList = await query.find();
  175. }
  176. console.log(bookList)
  177. if(bookList?.length){ // 直接导出教材列表
  178. let query = new Parse.Query("EduTextbook")
  179. query.include("childrens","department")
  180. query.containedIn("objectId",bookList);
  181. textbookList = await query.find();
  182. }
  183. let docsList = []
  184. let plist = []
  185. for (let index = 0; index < textbookList.length; index++) {
  186. let textbook = textbookList[index];
  187. console.log("textbook",index)
  188. // 直接将异步调用的 Promise 添加到 plist
  189. plist.push(renderReportDocsByTextbook(textbook)); // 立即执行并返回 Promise
  190. }
  191. let presults = await Promise.all(plist);
  192. console.log(presults)
  193. presults.forEach(result=>{
  194. if(result?.filePath || result?.pdfPath){
  195. docsList.push(result)
  196. }
  197. })
  198. let zipPath,zipUrl
  199. if(docsList?.length){
  200. let now = new Date();
  201. let fileList = docsList?.map(item=>item?.pdfPath);
  202. // zip包md5生成
  203. let md5 = crypto.createHash('md5');
  204. let fileListMd5 = md5.update(fileList?.join("")).digest('hex')
  205. let zipName = `申报书导出-${now.getFullYear()}${now.getMonth()+1}${now.getDate()}${now.getHours()}${now.getMinutes()}${now.getSeconds()}${now.getMilliseconds()}-${fileListMd5}.zip`
  206. zipPath = await createZip(fileList,zipName,{tempDir:null})
  207. if(zipPath){
  208. zipUrl = (await uploadFileToOSS(zipPath))?.url || null
  209. fs.rmSync(zipPath)
  210. fileList.forEach(tempFile=>{
  211. console.log("rm",tempFile)
  212. fs.rmSync(path.dirname(tempFile),{recursive:true,force:true});
  213. })
  214. }
  215. docsList = docsList.map(item=>{return {code:item.code,objectId:item?.objectId,title:item.title,url:item?.url,urlPdf:item?.urlPdf}})
  216. }
  217. let result = {
  218. docsList,
  219. zipUrl
  220. }
  221. return result
  222. }
  223. module.exports.exportProcessReportDocs = exportProcessReportDocs
  224. function fixVolumeData(json,volumeData,index,totalJson,isChildren){
  225. let volumeIndex = index;
  226. json.index = index + 1;
  227. // 教材基本信息
  228. // 教材所属学科专业类:前四位 discipline
  229. let disciplineCode4 = volumeData?.discipline?.code?.slice(0,4) || json?.discipline?.code?.slice(0,4) || ""
  230. let disciplineName4 = volumeData?.discipline?.name || json?.discipline?.name || ""
  231. // 教材应用对象及所属学科专业类:前四位 majorPoniter
  232. let majorCode4 = volumeData?.majorPoniter?.code?.slice(0,4) || json?.majorPoniter?.code?.slice(0,4) || ""
  233. let majorName4 = volumeData?.majorPoniter?.name || json?.majorPoniter?.name || ""
  234. // 专业代码:前六位 major
  235. let majorCode6 = volumeData?.major?.code?.slice(0,6) || json?.major?.code?.slice(0,6) || ""
  236. let majorName6 = volumeData?.major?.name || json?.major?.name || ""
  237. // 初版时间
  238. let firstDate
  239. if(volumeData?.editionFirst?.iso){
  240. firstDate = new Date(volumeData?.editionFirst.iso);
  241. }
  242. let firstYear = firstDate&&firstDate?.getFullYear();
  243. let firstMonth = firstDate&&(firstDate?.getMonth()+1);
  244. // 本版时间印次
  245. let currentDate
  246. if(volumeData?.editionDate?.iso){
  247. currentDate = new Date(volumeData?.editionDate.iso);
  248. }
  249. let currentYear = currentDate&&currentDate?.getFullYear();
  250. let currentMonth = currentDate&&(currentDate?.getMonth()+1);
  251. // 最新时间印次
  252. let latestDate
  253. if(volumeData?.printDate?.iso){
  254. latestDate = new Date(volumeData?.printDate.iso);
  255. }
  256. let latestYear = latestDate&&latestDate?.getFullYear();
  257. let latestMonth = latestDate&&(latestDate?.getMonth()+1);
  258. let latestNum = volumeData?.printNumber || "";
  259. let currentNum = volumeData?.editionNumber || "";
  260. let printSum = volumeData?.printSum?volumeData?.printSum+"万":"" || "";
  261. // 是否重点立项
  262. let importantProject = volumeData?.importantProject?.join();
  263. // 初版至今重点项目
  264. let isBSQT = !((importantProject?.indexOf("建设")>-1) || (importantProject?.indexOf("本科国家")>-1) || (importantProject?.indexOf("省级优秀")>-1) || (importantProject?.indexOf("省级规划")>-1))// 是否其他省级奖项
  265. let bsqtName = (volumeData?.importantProject || [])?.filter(item=>(item?.indexOf("建设")==-1&&item?.indexOf("本科国家")==-1&&item?.indexOf("省级优秀")==-1&&item?.indexOf("省级规划")==-1));
  266. json.importantProject = importantProject
  267. json.firstDate = firstDate
  268. json.firstYear = firstYear || ""
  269. json.firstMonth = firstMonth || ""
  270. json.currentDate = currentDate
  271. json.currentYear = currentYear || ""
  272. json.currentMonth = currentMonth || ""
  273. json.latestDate = latestDate
  274. json.latestYear = latestYear || ""
  275. json.latestMonth = latestMonth || ""
  276. json.currentNum = currentNum
  277. json.latestMonth = latestMonth
  278. json.latestNum = latestNum
  279. json.printSum = printSum
  280. json.isBSQT = isBSQT
  281. json.bsqtName = (importantProject?.indexOf("其他省部级")>-1) && volumeData?.importantProjectOther ? volumeData?.importantProjectOther : bsqtName
  282. json.uBS = circleCheck[(volumeData?.unitType?.indexOf("部属")>-1)?1:0];
  283. json.uHJ = circleCheck[(volumeData?.unitType?.indexOf("合建")>-1)?1:0];
  284. json.uGJ = circleCheck[(volumeData?.unitType?.indexOf("共建")>-1)?1:0];
  285. json.uQT = circleCheck[(volumeData?.unitType?.indexOf("其他")>-1)?1:0];
  286. json.dc4 = disciplineCode4;
  287. json.dn4 = disciplineName4;
  288. json.mc4 = majorCode4;
  289. json.mn4 = majorName4;
  290. json.majorCodePad = disciplineCode4;
  291. json.mc6 = majorCode6;
  292. json.mn6 = majorName6;
  293. json.lCN = circleCheck[(volumeData?.lang=="中文")?1:0];
  294. json.lEN = circleCheck[(volumeData?.lang=="英文")?1:0];
  295. json.lMW = circleCheck[(volumeData?.lang=="盲文")?1:0];
  296. json.lOT = circleCheck[(volumeData?.lang?.indexOf("其他")>-1)?1:0];
  297. json.lSS = circleCheck[(volumeData?.lang?.indexOf("少数")>-1)?1:0];
  298. json.publisher = volumeData?.editionUnit;
  299. json.isDZ = circleCheck[(volumeData?.carrierShape?.indexOf("电子教材")>-1)?1:0];
  300. json.isSZ = circleCheck[(volumeData?.carrierShape?.indexOf("数字教材")>-1 || volumeData?.carrierShape?.indexOf("电子教材")>-1)?1:0];
  301. json.isQT = circleCheck[(volumeData?.carrierShape?.indexOf("其他")>-1)?1:0];
  302. json.isFD = circleCheck[(volumeData?.carrierShape?.indexOf("附带")>-1)?1:0];
  303. json.isZZ = circleCheck[(volumeData?.carrierShape?.indexOf("纸质教材")>-1 && volumeData?.carrierShape?.indexOf("附带")==-1)?1:0];
  304. json.latestY = latestYear;
  305. json.latestM = latestMonth;
  306. json.currentY = currentYear;
  307. json.currentM = currentMonth;
  308. console.log(importantProject)
  309. json.isGJS = circleCheck[(importantProject?.indexOf("建设")>-1)?1:0];
  310. json.isBGJ = circleCheck[(importantProject?.indexOf("本科国家")>-1)?1:0];
  311. json.isBSYX = circleCheck[(importantProject?.indexOf("省级优秀")>-1)?1:0];
  312. json.isBSGH = circleCheck[(importantProject?.indexOf("省级规划")>-1)?1:0];
  313. // json.isBSQT = circleCheck[isBSQT&&bsqtName?1:0];
  314. json.isBSQT = circleCheck[(importantProject?.indexOf("其他省部级")>-1)?1:0];
  315. json.isFirstNot = circleCheck[volumeData?.importantProject?.length > 0?0:1];
  316. // 作者列表 + 政治审查表
  317. totalJson.examineList = totalJson.examineList || []
  318. totalJson.zhengshenList = totalJson.zhengshenList || []
  319. // console.log(volumeData?.authorList)
  320. for (let index = 0; index < 6; index++) { // 补充空值
  321. if(!volumeData?.authorList?.[index]){
  322. volumeData.authorList.push({name:"",unit:"",birth:"",nationality:"",job:"",title:"",mobile:"",email:"",work:""})
  323. }
  324. }
  325. volumeData.authorList = volumeData?.authorList?.map((item,index)=>{ // 转换格式
  326. item.index = index + 1
  327. item.birth = toYearMonth(item?.birth)
  328. if(item?.examine){
  329. if(!(isChildren&&volumeIndex==0)){ // 子册第一册不重复导出
  330. // totalJson.examineList = pushDistinctItem(totalJson.examineList,item) // 名称去重
  331. // console.log(item)
  332. totalJson.zhengshenList.push(item?.examine);
  333. totalJson.examineList.push(item); // 全量导出
  334. }
  335. }
  336. return item
  337. })
  338. // console.log(totalJson.examineList)
  339. json.authorList = volumeData?.authorList;
  340. // 其他编者政治审查表
  341. totalJson.otherList = totalJson.otherList || []
  342. if(volumeData?.otherEditor){
  343. if(!(isChildren&&volumeIndex==0)){ // 子册第一册不重复导出
  344. // totalJson.otherList = pushDistinctItem(totalJson.otherList,volumeData?.otherEditor) // 名称去重
  345. totalJson.zhengshenList.push(volumeData?.otherEditor)
  346. totalJson.otherList.push(volumeData?.otherEditor); //全量导出
  347. }
  348. }
  349. // 成果列表
  350. // aclist[index] = [json?.achievementOptions?.[index]?.name||" ",json?.achievementOptions?.[index]?.unit||" ",toYearMonth(json?.achievementOptions?.[index]?.date)||" "]
  351. for (let index = 0; index < 5; index++) { // 补充空值
  352. if(!volumeData?.achievementOptions?.[index]){
  353. volumeData.achievementOptions.push({name:"",unit:"",date:""})
  354. }
  355. volumeData.achievementOptions = volumeData?.achievementOptions?.map((item,index)=>{ // 转换格式
  356. item.index = index + 1
  357. item.date = toYearMonth(item?.date)
  358. return item
  359. })
  360. }
  361. json.achievementOptions = volumeData?.achievementOptions;
  362. // 历程列表
  363. // clist[index] = [num,toYearMonth(json?.courses?.[index]?.date)||" ",json?.courses?.[index]?.wordage||" ",json?.courses?.[index]?.num||" ",json?.courses?.[index]?.sumNum||" ",json?.courses?.[index]?.accolade||" "]
  364. for (let index = 0; index < 5; index++) { // 补充空值
  365. if(!volumeData?.courses?.[index]){
  366. volumeData.courses.push({date:"",wordage:"",num:"",sumNum:"",accolade:""})
  367. }
  368. }
  369. volumeData.courses = volumeData?.courses?.map((item,index)=>{ // 转换格式
  370. item.index = index + 1
  371. item.date = toYearMonth(item?.date)
  372. return item
  373. })
  374. json.courses = volumeData?.courses;
  375. return json
  376. }
  377. function pushDistinctItem(list,item){
  378. let isDistinct = true
  379. if(list?.indexOf(item)>-1){
  380. isDistinct = false;
  381. }
  382. if(list?.find(old=>old?.name&&old?.name==item?.name)){
  383. isDistinct = false;
  384. }
  385. if(isDistinct){
  386. list.push(item);
  387. }
  388. return list
  389. }
  390. function renderReportDocsByTextbook(textbook){
  391. console.log("renderReportDocsByTextbook")
  392. return new Promise(async (resolve)=>{
  393. let json = textbook.toJSON();
  394. json.hasNoSign = false; // 未上传作者签名
  395. json.hasNoUnit = false; // 未上传单位资料
  396. json.hasNoNine = false; // 无需添加滞后九
  397. let bookid = json.code || json?.objectId;
  398. let exportPDF = textbook.get("exportPDF");
  399. if(exportPDF){
  400. // console.log(exportPDF)
  401. let exportPath = await downloadUrl(exportPDF,{tempDir:path.join(tempDir,textbook.id),keepFileName:true});
  402. // console.log(exportPath)
  403. resolve({
  404. code:bookid,
  405. objectId:textbook.id,
  406. title:json?.title,
  407. pdfPath:exportPath,
  408. urlPdf:exportPDF,
  409. })
  410. return
  411. }
  412. // 默认单册为第一分册
  413. let book1Data = json?.childrens?.[0]
  414. if(book1Data){
  415. Object.keys(book1Data).forEach(key=>{
  416. json[key] = book1Data[key] || json[key] || ""
  417. })
  418. }
  419. // 联系电话:默认为作者首个存在的电话;
  420. let mobile = json?.authorList?.find(item => item.mobile)?.mobile || ""
  421. // 填报时间:默认为创建时间
  422. let createdAt = new Date(textbook?.createdAt);
  423. let createdDate = `${createdAt?.getFullYear()}年${createdAt?.getMonth()+1}月${createdAt?.getDate()}日`;
  424. // 教材适用
  425. let characteristic = (json?.characteristic?.filter(item=>item?.checked).map(item=>item.label) || [])?.join(",")
  426. json = fixVolumeData(json,book1Data,0,json)
  427. let volumeList = []
  428. for (let index = 0; index < 12; index++) {
  429. if(json?.childrens?.[index]){
  430. let volumeData = json?.childrens?.[index]
  431. volumeData = fixVolumeData(volumeData,volumeData,index,json,true)
  432. volumeList.push(volumeData)
  433. }
  434. }
  435. // 作者列表 限6人
  436. let alist = []
  437. for (let index = 0; index < 9; index++) {
  438. alist[index] = [json?.authorList?.[index]?.name||" ",json?.authorList?.[index]?.unit||" ",toYearMonth(json?.authorList?.[index]?.birth)||" ",json?.authorList?.[index]?.nationality||" ",json?.authorList?.[index]?.job||" ",json?.authorList?.[index]?.title||" ",json?.authorList?.[index]?.mobile||" ",json?.authorList?.[index]?.email||" ",json?.authorList?.[index]?.work||" "]
  439. }
  440. // 相关成果 限5项
  441. let aclist = []
  442. for (let index = 0; index < 5; index++) {
  443. aclist[index] = [json?.achievementOptions?.[index]?.name||" ",json?.achievementOptions?.[index]?.unit||" ",toYearMonth(json?.achievementOptions?.[index]?.date)||" "]
  444. }
  445. // 申报历程 限4项
  446. let clist = []
  447. for (let index = 0; index < 4; index++) {
  448. let num = json?.courses?.[index]?(index+1):" ";
  449. clist[index] = [num,toYearMonth(json?.courses?.[index]?.date)||" ",json?.courses?.[index]?.wordage||" ",json?.courses?.[index]?.num||" ",json?.courses?.[index]?.sumNum||" ",json?.courses?.[index]?.accolade||" "]
  450. }
  451. // 附件信息
  452. let mergeFiles = []
  453. // 教材电子版
  454. // (教材出版单位配合按要求上传各地推荐的本单位出版的纸质教材最新印次的完整PDF电子版;数字教材上传全部教材内容电子版或填写能够查看全部教材内容的链接地址、账号;纸质教材附带数字资源的,上传纸质教材最新印次的完整PDF电子版,以及全部数字资源电子版或能够查看全部数字资源内容的链接地址、账号。)
  455. let isNotImpt = (json?.approval?.indexOf("101计划")==-1) && (json?.approval?.indexOf("中央有关部门")==-1) && (json?.approval?.indexOf("四新")==-1) && (json?.approval?.indexOf("首届全国")==-1);
  456. // 1.获批截图
  457. if(json?.approvedImgUrl && !isNotImpt){
  458. mergeFiles.push(json?.approvedImgUrl);
  459. }
  460. // 2.所有作者政治审查意见(必须提供)
  461. // (对应作者姓名上传“作者政治审查表”。作者单位党委对作者进行审查,对政治思想表现情况进行评价,确保作者的正确政治方向、价值取向,无违法违纪等记录。教材编写成员涉及多个不同单位时需要各单位分别出具意见,并由所在单位党委盖章,格式要求从申报平台下载。)
  462. // console.log("json.examineList");
  463. // console.log("json.examineList");
  464. // console.log("json.examineList");
  465. // console.log("json.examineList");
  466. // console.log(json.examineList);
  467. // json.examineList.forEach(author=>{
  468. // if(author?.examine) mergeFiles.push(author?.examine)
  469. // })
  470. // console.log(mergeFiles)
  471. // let otherMap = {}
  472. json?.zhengshenList?.forEach(item=>{ // 合并不重复其他编者政治审查表
  473. // if(otherMap[item]) return
  474. // otherMap[item] = true
  475. mergeFiles.push(item)
  476. })
  477. // json?.otherList?.forEach(item=>{ // 合并不重复其他编者政治审查表
  478. // if(otherMap[item]) return
  479. // otherMap[item] = true
  480. // mergeFiles.push(item)
  481. // })
  482. // 3.图书编校质量自查结果记录表(必须提供)
  483. // (教材出版单位对申报教材的编校质量自查后,按要求提供图书编校质量自查结果记录表,并加盖出版社公章。全册教材的不同分册以不同文件分别上传。格式要求从申报平台下载。)
  484. if(json?.selfResults?.url){mergeFiles.push(json?.selfResults?.url)}
  485. // 4.专家审查意见表(必须提供)
  486. // (由第一主编所在单位或出版机构邀请校内外相关学科专业领域专家,对教材进行思想性、学术性审查。专家不少于3名,其中半数以上为校外专家,专家分别实名评价并签字,并注明所在单位及专业身份。评价人不得是本教材的作者。)
  487. if(json?.expertOpinion?.url){mergeFiles.push(json?.expertOpinion?.url)}
  488. // 5.教材使用情况证明材料(必须提供)
  489. // (教材出版单位提供教材主要使用高校名单及使用情况证明材料,并加盖公章。)
  490. if(json?.evidence?.url){mergeFiles.push(json?.evidence?.url)}
  491. // 6.版权信息及CIP数据(必须提供)
  492. // (版权页截图,中国版本图书馆CIP查询截图,如CIP数据中无“教材”字样的,须再上传内容提要或前言或后记中可以证明本书为教材的相关内容截图。)
  493. //6.1 版权页截图
  494. if(json?.copyrightImgUrl){mergeFiles.push(json?.copyrightImgUrl)}
  495. //6.2 中国版本图书馆 CIP 查询截图
  496. if(json?.CIPImgUrl){mergeFiles.push(json?.CIPImgUrl)}
  497. //6.3 CIP 相关证明截图
  498. if(json?.cipProveFile?.length){
  499. json?.cipProveFile.forEach(item=>{
  500. item?.url && mergeFiles.push(item?.url)
  501. })
  502. }
  503. // 7.其他材料(可选提供)
  504. if(json?.moreMaterial?.length){
  505. json?.moreMaterial.forEach(doc=>{
  506. if(doc?.url){
  507. mergeFiles.push(doc?.url)
  508. }
  509. })
  510. }
  511. let bookTempDir = path.join(tempDir,json?.objectId)
  512. if(!fs.existsSync(bookTempDir)) fs.mkdirSync(bookTempDir)
  513. let codePngBuffer = await toBarCode(json?.code);
  514. let codePngPath = path.join(bookTempDir,bookid+"code.png")
  515. fs.writeFileSync(codePngPath,codePngBuffer)
  516. // let codeBarImg =
  517. // console.log(codeBarImg)
  518. // (其他佐证材料,限两份以内。)
  519. console.log(json?.approval)
  520. // let isNotImpt = (json?.approval?.indexOf("101计划")==-1) && (json?.approval?.indexOf("中央有关部门")==-1) && (json?.approval?.indexOf("四新")==-1) && (json?.approval?.indexOf("首届全国")==-1);
  521. let fixData = {
  522. volumeList:volumeList,
  523. // 图片信息
  524. codeBarImg:codePngPath,
  525. // 封面信息
  526. titlePad:padString(json?.title,21),
  527. ISBNPad:fromatFiled(json?.childrens, 'ISBN') || padString(json?.ISBN,21),
  528. ISBN:json?.ISBN,
  529. inviteUnit:json?.inviteUnit||json?.department?.name||"",
  530. one:squareCheck[(json?.type=="单本"||json?.type=="单册")?1:0], // 单本/单册 方框
  531. full:squareCheck[json?.type=="全册"?1:0], // 全册
  532. oneCircle:circleCheck[(json?.type=="单本"||json?.type=="单册")?1:0], // 单本/单册 圆圈
  533. fullCircle:circleCheck[json?.type=="全册"?1:0], // 全册
  534. tn:json?.typeNumber,
  535. authorPad:fromatFiled(json?.childrens, 'author') || padString(json?.author,21),
  536. mobile:padString(mobile,21),
  537. authorUnit:fromatFiled(json?.childrens, 'unit') || padString(json?.unit,21),
  538. publisherPad:fromatFiled(json?.childrens, 'editionUnit') || padString(json?.editionUnit,21),
  539. createdDate:padString(createdDate,21),
  540. // 基本信息
  541. title:json?.title,
  542. isJC: circleCheck[(json?.approval?.indexOf("基础")>-1)?1:0],
  543. isZL: circleCheck[(json?.approval?.indexOf("战略")>-1)?1:0],
  544. is101: circleCheck[(json?.approval?.indexOf("101计划")>-1)?1:0], // 2024新重点
  545. isZY: circleCheck[(json?.approval?.indexOf("中央有关部门")>-1)?1:0],
  546. isSX: circleCheck[(json?.approval?.indexOf("四新")>-1)?1:0],
  547. isJS: circleCheck[(json?.approval?.indexOf("首届全国")>-1)?1:0],
  548. isNotImpt: circleCheck[isNotImpt?1:0],
  549. // 教材适用情况
  550. lessons:json?.lessons||[],
  551. period:json?.period||"", // 学时
  552. isBX:squareCheck[(characteristic?.indexOf("必修")>-1)?1:0],
  553. isXX:squareCheck[(characteristic?.indexOf("选修")>-1)?1:0],
  554. isTS:circleCheck[(characteristic?.indexOf("通识")>-1)?1:0],
  555. isGG:circleCheck[(characteristic?.indexOf("公共")>-1)?1:0],
  556. isZYK:circleCheck[(characteristic?.indexOf("专业")>-1)?1:0],
  557. isSXZZ:squareCheck[(characteristic?.indexOf("思想")>-1)?1:0],
  558. isSY:squareCheck[(characteristic?.indexOf("实验")>-1)?1:0],
  559. // 作者列表
  560. a11:alist[0][0],a12:alist[0][1],a13:alist[0][2],a14:alist[0][3],a15:alist[0][4],a16:alist[0][5],a17:alist[0][6],a18:alist[0][7],a19:alist[0][8],
  561. a21:alist[1][0],a22:alist[1][1],a23:alist[1][2],a24:alist[1][3],a25:alist[1][4],a26:alist[1][5],a27:alist[1][6],a28:alist[1][7],a29:alist[1][8],
  562. a31:alist[2][0],a32:alist[2][1],a33:alist[2][2],a34:alist[2][3],a35:alist[2][4],a36:alist[2][5],a37:alist[2][6],a38:alist[2][7],a39:alist[2][8],
  563. a41:alist[3][0],a42:alist[3][1],a43:alist[3][2],a44:alist[3][3],a45:alist[3][4],a46:alist[3][5],a47:alist[3][6],a48:alist[3][7],a49:alist[3][8],
  564. a51:alist[4][0],a52:alist[4][1],a53:alist[4][2],a54:alist[4][3],a55:alist[4][4],a56:alist[4][5],a57:alist[4][6],a58:alist[4][7],a59:alist[4][8],
  565. a61:alist[5][0],a62:alist[5][1],a63:alist[5][2],a64:alist[5][3],a65:alist[5][4],a66:alist[5][5],a67:alist[5][6],a68:alist[5][7],a69:alist[5][8],
  566. // 成果列表
  567. ac11:aclist[0][0],ac12:aclist[0][1],ac13:aclist[0][2],
  568. ac21:aclist[1][0],ac22:aclist[1][1],ac23:aclist[1][2],
  569. ac31:aclist[2][0],ac32:aclist[2][1],ac33:aclist[2][2],
  570. ac41:aclist[3][0],ac42:aclist[3][1],ac43:aclist[3][2],
  571. ac51:aclist[4][0],ac52:aclist[4][1],ac53:aclist[4][2],
  572. // 历程列表
  573. c11:clist[0][0],c12:clist[0][1],c13:clist[0][2],c14:clist[0][3],c15:clist[0][4],c16:clist[0][5],
  574. c21:clist[1][0],c22:clist[1][1],c23:clist[1][2],c24:clist[1][3],c25:clist[1][4],c26:clist[1][5],
  575. c31:clist[2][0],c32:clist[2][1],c33:clist[2][2],c34:clist[2][3],c35:clist[2][4],c36:clist[2][5],
  576. c41:clist[3][0],c42:clist[3][1],c43:clist[3][2],c44:clist[3][3],c45:clist[3][4],c46:clist[3][5],
  577. }
  578. let bookData = json;
  579. Object.keys(fixData).forEach(key=>{
  580. bookData[key] = fixData[key] || bookData[key] || ""
  581. if(typeof bookData[key]=="string"){
  582. bookData[key] = bookData[key].replaceAll("\x02"," ")
  583. bookData[key] = bookData[key].replaceAll("\u0002"," ") // 字段填写字符中,存在无法转码的乱码字符
  584. if(key=="ac31"){
  585. console.log(bookData[key])
  586. }
  587. }
  588. })
  589. // console.log(bookData)
  590. // console.log(json)
  591. let title = bookData.title?.replaceAll("/","")
  592. let tempFileName = path.join(`${bookid}_${title}_申报书及附件.docx`)
  593. // mergeFiles 处理七八九是否签名或后置问题
  594. let lastPageList = []
  595. let docx7 = await getPageDocx(json?.objectId,bookid,"七",bookData);
  596. let docx8 = await getPageDocx(json?.objectId,bookid,"八",bookData);
  597. let docx9 = await getPageDocx(json?.objectId,bookid,"九",bookData);
  598. lastPageList.push(json?.authorSignPDF?.url||docx7);
  599. lastPageList.push(json?.unitMaterial?.url||docx8);
  600. lastPageList.push(docx9);
  601. let lastPageFileName = path.join(bookTempDir,`${bookid}_${title}_申报书及附件_789.pdf`)
  602. console.log(lastPageList)
  603. let lastPagePdf = await docxToPdf(null,lastPageFileName,{mergeFiles:lastPageList,tempDir:bookTempDir,mergeAll:true}) // 成功用pdf,失败继续用docx
  604. docx7&&fs.rmSync(docx7)
  605. docx8&&fs.rmSync(docx8)
  606. docx9&&fs.rmSync(docx9)
  607. // mergeFiles = [...lastPageList,...mergeFiles]
  608. mergeFiles = [lastPagePdf,...mergeFiles]
  609. // 开始文件合并导出
  610. let filePath,pdfPath,urlDocx,urlPdf
  611. let TemplateDocxPath
  612. if(json?.childrens?.length>1){
  613. TemplateDocxPath = path.join(TemplateDocxDir,"模板-本科教材申报书-全册.docx")
  614. }else{
  615. TemplateDocxPath = path.join(TemplateDocxDir,"模板-本科教材申报书-单册.docx")
  616. }
  617. try{
  618. // DOCX模板合成 速度2-3秒
  619. filePath = renderDocx(TemplateDocxPath,tempFileName,bookData,{tempDir:bookTempDir})
  620. urlDocx = (await uploadFileToOSS(filePath))?.url || null
  621. console.log("DOCX CREATED:",filePath)
  622. // PDF文档拼接 速度10-30s 需要API支持
  623. pdfPath = filePath.replaceAll(".docx",".pdf")
  624. let options = {
  625. mergeFiles:mergeFiles,
  626. tempDir:bookTempDir
  627. }
  628. pdfPath = await docxToPdf(filePath,pdfPath,options) || filePath // 成功用pdf,失败继续用docx
  629. console.log("PDF CREATED:",filePath)
  630. if(pdfPath){
  631. urlPdf = (await uploadFileToOSS(pdfPath,json?.objectId))?.url || null
  632. if(urlPdf){
  633. textbook.set("exportPDF",urlPdf);
  634. textbook.save();
  635. }
  636. }
  637. }catch(err){
  638. console.error(err)
  639. }
  640. resolve({
  641. code:bookid,
  642. objectId:json?.objectId,
  643. title:json?.title,
  644. filePath,
  645. pdfPath,
  646. urlDocx,
  647. urlPdf,
  648. })
  649. return
  650. })
  651. }
  652. async function getPageDocx(objectId,bookid,pageName,bookData){
  653. let tplPath = path.join(TemplateDocxDir,`模板-本科教材申报书-${pageName}.docx`);
  654. let title = bookData?.title?.replaceAll("/","")
  655. let tempFileName = path.join(objectId,`${bookid}_${title}_申报书及附件_${pageName}.docx`);
  656. let filePath = renderDocx(tplPath,tempFileName,bookData);
  657. return filePath;
  658. // 转pdf
  659. // let pdfPath = filePath.replaceAll(".docx",".pdf")
  660. // let options = {}
  661. // pdfPath = await docxToPdf(null,pdfPath,options) || filePath // 成功用pdf,失败继续用docx
  662. // return pdfPath
  663. }
  664. function toYearMonth(date){
  665. // console.log("toYearMonth",date)
  666. if(typeof date == "string" && (date?.indexOf("年")>-1 || date?.indexOf("-")>-1)) return date
  667. if(!date) return ""
  668. let datestr = date?.iso||date
  669. if(!datestr) return ""
  670. date = new Date(datestr);
  671. // return `${date.getFullYear()}年${date.getMonth()+1}月`
  672. return `${date.getFullYear()}-${get2bitint(date.getMonth()+1)}`
  673. }
  674. function get2bitint(value){
  675. if(value>=10) return value;
  676. if(value>=0&&value<10) return "0" + value;
  677. return value
  678. }
  679. function padString(str,width) {
  680. str = str || ""
  681. return str
  682. str = String(str)
  683. width = width || 21 // 目标宽度为21个单位
  684. let spaceChar = " " // 占位符 render可用空格,但document.xml用&#160;
  685. // 计算字符串的宽度
  686. const charWidth = {
  687. 'space': 1, // 空格占用1个单位
  688. 'zh': 3, // 汉字占用3个单位
  689. 'en': 1, // 英文字母占用1个单位
  690. 'other': 1 // 其他字符(如标点符号)占用1个单位
  691. };
  692. let strWidth = 0;
  693. // console.log(str)
  694. // 遍历文本中的每个字符
  695. for (let char of str) {
  696. if (/\s/.test(char)) {
  697. strWidth += charWidth.space; // 空格
  698. } else if (/[\u4e00-\u9fa5]/.test(char)) {
  699. strWidth += charWidth.zh; // 汉字
  700. } else if (/[a-zA-Z]/.test(char)) {
  701. strWidth += charWidth.en; // 英文字母
  702. } else {
  703. strWidth += charWidth.other; // 其他字符
  704. }
  705. }
  706. // for (let char of str) {
  707. // // 判断字符是否为中文
  708. // if (char.match(/[\u4e00-\u9fa5]/)) {
  709. // strWidth += 2; // 中文字符占4个单位
  710. // } else {
  711. // strWidth += 1; // 英文字符占1个单位
  712. // }
  713. // }
  714. const totalPadding = width - strWidth;
  715. // 如果已经达到或超过目标宽度,直接返回原字符串
  716. if (totalPadding <= 0) {
  717. return str;
  718. }
  719. // 计算左右两侧的空格数
  720. const leftPadding = Math.floor(totalPadding / 2) * 3;
  721. const rightPadding = Math.ceil(totalPadding / 2) * 3;
  722. // 生成填充空格的字符串
  723. const leftSpaces = spaceChar.repeat(leftPadding);
  724. const rightSpaces = spaceChar.repeat(rightPadding);
  725. // 返回补充后的字符串
  726. return leftSpaces + str + rightSpaces;
  727. }
  728. /* 格式化重复字段(首页多册情况展示:书号、第一主编、主编单位、出 版 社) */
  729. function fromatFiled(list, filed){
  730. let arr = [];
  731. list.forEach((item) => {
  732. arr.push(item[filed]);
  733. });
  734. let j = Array.from(new Set(arr)).join('、');
  735. return j || '-';
  736. }