func-tbook-export.js 33 KB

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