func-tbook-export.js 35 KB

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