pm_facade.js 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183
  1. /**
  2. * Created by zhang on 2018/4/17.
  3. */
  4. const projectType = {
  5. folder: 'Folder',
  6. tender: 'Tender',
  7. project: 'Project',
  8. engineering: 'Engineering',
  9. };
  10. //先导出后require可以解决循环引用问题
  11. module.exports={
  12. prepareShareList,
  13. getShareList,
  14. addShareList,
  15. updateShareList,
  16. deleteShareList,
  17. getShareInfoMap,
  18. getRecentShareList,
  19. getProjectShareList,
  20. getReceiveLibList,
  21. getLibShareList,
  22. getUnreadShareListByCompilation,
  23. getShareTip,
  24. getShareState,
  25. markShareItemsRead,
  26. getShareInfoAfterChangePermission,
  27. moveProject:moveProject,
  28. accessToCopyProject,
  29. copyProject:copyProject,
  30. copyExample: copyExample,
  31. setupSummaryFields: setupSummaryFields,
  32. getSummaryInfo: getSummaryInfo,
  33. getSummaryInfoByTender: getSummaryInfoByTender,
  34. getIndexReportData: getIndexReportData,
  35. getTendersFeeInfo: getTendersFeeInfo,
  36. getConstructionProject: getConstructionProject,
  37. getFullPath: getFullPath,
  38. projectType: projectType,
  39. getPosterityProjects: getPosterityProjects,
  40. isShare: isShare,
  41. isFirst: isFirst,
  42. getShareInfo: getShareInfo,
  43. prepareInitialData: prepareInitialData,
  44. changeFile:changeFile,
  45. getBasicInfo: getBasicInfo,
  46. getProjectFeature: getProjectFeature,
  47. getProgressiveInterval: getProgressiveInterval,
  48. getProjectByGranularity: getProjectByGranularity,
  49. importProject: importProject,
  50. getProjectPlaceholder: getProjectPlaceholder,
  51. exportProject:exportProject,
  52. importProjects:importProjects,//建筑这里重名了,这比养护加多了个s
  53. initOverHeightItems: initOverHeightItems,
  54. uploadToken:uploadToken,
  55. downLoadProjectFile:downLoadProjectFile,
  56. importChongqingProject:importChongqingProject,
  57. importExampleProject:importExampleProject,
  58. importProcessChecking:importProcessChecking,
  59. copyConstructionProject,
  60. importInterface,
  61. isTenderOverrun,
  62. getWelcomeInfo:getWelcomeInfo
  63. };
  64. let mongoose = require('mongoose');
  65. let _ = require("lodash");
  66. let feeRate_facade = require('../../fee_rates/facade/fee_rates_facade');
  67. let glj_facade = require('../../glj/facade/glj_facade');
  68. let project_facade = require('../../main/facade/project_facade');
  69. let logger = require("../../../logs/log_helper").logger;
  70. const uuidV1 = require('uuid/v1');
  71. let projectModel = mongoose.model('projects');
  72. let projectSettingModel = mongoose.model('proj_setting');
  73. let billsModel = mongoose.model('bills');
  74. let rationModel = mongoose.model('ration');
  75. let gljListModel = mongoose.model("glj_list");
  76. let calcProgramsModel = mongoose.model('calc_programs');
  77. let labourCoesModel = mongoose.model('labour_coes');
  78. let feeRateModel = mongoose.model('fee_rates');
  79. let feeRateFileModel = mongoose.model('fee_rate_file');
  80. let unitPriceFileModel = mongoose.model("unit_price_file");
  81. let mixRatioModel = mongoose.model("mix_ratio");
  82. let unitPriceModel = mongoose.model("unit_price");
  83. let installationFeeModel = mongoose.model("installation_fee");
  84. let rationGLJModel = mongoose.model('ration_glj');
  85. let rationCoeModel = mongoose.model('ration_coe');
  86. let rationInstallationModel = mongoose.model('ration_installation');
  87. let quantityDetailModel = mongoose.model('quantity_detail');
  88. let rationTemplateModel = mongoose.model('ration_template');
  89. let userModel = mongoose.model('user');
  90. let compleGljSectionModel = mongoose.model('complementary_glj_section');
  91. let compleGljSectionTModel = mongoose.model('complementary_glj_section_templates');
  92. let compilationModel = mongoose.model('compilation');
  93. let engineeringModel = mongoose.model('engineering_lib');
  94. let basicInfoModel = mongoose.model('std_basic_info_lib');
  95. let projectFeatureModel = mongoose.model('std_project_feature_lib');
  96. let progressiveModel = mongoose.model('std_progressive_lib');
  97. let stdRationItemModel = mongoose.model('std_ration_lib_ration_items');
  98. let stdGljItemModel = mongoose.model('std_glj_lib_gljList');
  99. let evaluateListModel = mongoose.model("evaluate_list");
  100. let bidListModel = mongoose.model("bid_evaluation_list");
  101. let contractorListModel = mongoose.model("contractor_list");
  102. let featureLibModel = mongoose.model("std_project_feature_lib");
  103. let importLogsModel = mongoose.model("import_logs");
  104. const overHeightLibModel = mongoose.model('std_over_height_lib');
  105. const shareListModel = mongoose.model('share_list');
  106. const shareLibModel = mongoose.model('share_libs');
  107. let welcomeModel = mongoose.model("welcome_setting");
  108. let equipmentPurchaseModel = mongoose.model('equipment_purchase');
  109. const gaterFeeModel = mongoose.model('gather_calc_programs');
  110. let scMathUtil = require('../../../public/scMathUtil').getUtil();
  111. let counter = require('../../../public/counter/counter');
  112. const SectionTreeDao = require('../../complementary_ration_lib/models/sectionTreeModel');
  113. let sectionTreeDao = new SectionTreeDao();
  114. const CounterModel = require("../../glj/models/counter_model");
  115. const moment = require('moment-timezone');
  116. const { fixedFlag, SharePermissionChangeType } = require('../../../public/common_constants');
  117. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  118. const {
  119. defaultDecimal,
  120. billsQuantityDecimal,
  121. displaySetting,
  122. calcOptions,
  123. tenderSetting
  124. } = require('../models/project_property_template');
  125. let labourCoeFacade = require('../../main/facade/labour_coe_facade');
  126. let calcProgramFacade = require('../../main/facade/calc_program_facade');
  127. let mainColLibModel = mongoose.model('std_main_col_lib');
  128. const EngineeringLibModel = require("../../users/models/engineering_lib_model");
  129. let installationFacade = require('../../main/facade/installation_facade');
  130. let cipher = require('../../../public/cipher');
  131. let index = require("../../system_setting/model/index");
  132. let qiniu = require("qiniu");
  133. let fs = require("fs");
  134. let path = require("path");
  135. let request = require("request");
  136. const systemSettingModel = mongoose.model('system_setting');
  137. const billFacade = require('../../main/facade/bill_facade');
  138. let qiniu_config = {
  139. "AccessKey": "_gR1ed4vi1vT2G2YITGSf4_H0fJu_nRS9Tzk3T4z",
  140. "SecretKey": "ty4zd0FHqgEDaiVzSLC8DfHlai99aS7bspLkw6s6",
  141. "Bucket": "yun-update",
  142. "Domain": "http://serverupdate.smartcost.com.cn"
  143. };
  144. let mac = new qiniu.auth.digest.Mac(qiniu_config.AccessKey, qiniu_config.SecretKey);
  145. // 重构了分享的数据结构,原本存在projects表的shareInfo数组中
  146. // 为了更好地适应新功能及以后拓展功能,现将分享信息存放在单独的share_list表中
  147. // 为了适应旧数据,需要在share_list没有数据的时候,将原本的分享信息复制到share_list中,同时生成联系人
  148. // TODO: 上线后这个方法执行过后,应该删除此方法
  149. async function prepareShareList() {
  150. const shareListCount = await shareListModel.count({});
  151. console.log(shareListCount);
  152. if (shareListCount) {
  153. return;
  154. }
  155. logger.info('================================enterPrepareShareList================================================');
  156. // 将项目的shareInfo数据复制到share_list表中
  157. const projects = await projectModel.find({'shareInfo.0': {$exists: true}}, '-_id ID userID shareInfo').lean();
  158. if (!projects.length) {
  159. return;
  160. }
  161. const shareList = [];
  162. const userMap = {}; // 给生成联系人做准备
  163. projects.forEach(project => {
  164. const ownerContacts = userMap[project.userID] || (userMap[project.userID] = []);
  165. project.shareInfo.forEach(shareItem => {
  166. if (!shareItem.shareDate) {
  167. return;
  168. }
  169. const receiverContacts = userMap[shareItem.userID] || (userMap[shareItem.userID] = []);
  170. receiverContacts.push(project.userID);
  171. const newItem = {
  172. ID: uuidV1(),
  173. projectID: project.ID,
  174. owner: project.userID,
  175. receiver: shareItem.userID,
  176. allowCopy: shareItem.allowCopy,
  177. allowCooperate: shareItem.allowCooperate,
  178. shareDate: shareItem.shareDate,
  179. updateDate: shareItem.shareDate
  180. };
  181. ownerContacts.push(shareItem.userID);
  182. shareList.push(newItem);
  183. });
  184. });
  185. // 插入分享信息
  186. const shareListPromise = shareListModel.insertMany(shareList);
  187. const tasks = [shareListPromise];
  188. // 更新用户信息
  189. const userTasks = [];
  190. Object.entries(userMap).forEach(([userID, contacts]) => {
  191. contacts = [...new Set(contacts)]
  192. .map(user => ({ userID: user }));
  193. const task = {
  194. updateOne: {
  195. filter: {
  196. _id: mongoose.Types.ObjectId(userID)
  197. },
  198. update: {
  199. contacts
  200. }
  201. }
  202. };
  203. userTasks.push(task);
  204. });
  205. if (userTasks.length) {
  206. tasks.push(userModel.bulkWrite(userTasks));
  207. }
  208. await Promise.all(tasks);
  209. }
  210. // 获取分享列表
  211. async function getShareList(query, isShareLib = false) {
  212. const model = isShareLib ? shareLibModel : shareListModel;
  213. return await model.find(query, '-_id').lean();
  214. }
  215. async function addShareList(docs, isShareLib = false) {
  216. const model = isShareLib ? shareLibModel : shareListModel;
  217. await model.insertMany(docs);
  218. }
  219. async function deleteShareList(query, isShareLib = false) {
  220. const model = isShareLib ? shareLibModel : shareListModel;
  221. await model.deleteMany(query);
  222. }
  223. async function updateShareList(updateData, isShareLib = false) {
  224. const model = isShareLib ? shareLibModel : shareListModel;
  225. const bulks = updateData.map(item => (
  226. {
  227. updateOne: {
  228. filter: item.query,
  229. update: item.update
  230. }
  231. }
  232. ));
  233. if (bulks.length) {
  234. await model.bulkWrite(bulks);
  235. }
  236. }
  237. // 根据项目ID获取项目shareInfo字段的数据映射(前端旧逻辑依赖项目本身的shareInfo字段)
  238. async function getShareInfoMap(projectIDs, shareList = null) {
  239. if (!shareList) {
  240. shareList = await getShareList({projectID: {$in: projectIDs}});
  241. }
  242. // 将相同项目的分享信息进行映射
  243. const map = {};
  244. shareList.forEach(item => {
  245. const shareInfo = map[item.projectID] || (map[item.projectID] = []);
  246. shareInfo.push({
  247. userID: item.receiver,
  248. shareDate: item.shareDate,
  249. updateDate: item.updateDate,
  250. allowCopy: item.allowCopy,
  251. allowCooperate: item.allowCooperate
  252. });
  253. });
  254. return map;
  255. }
  256. // 获取最近分享(只算分享出去的记录)
  257. async function getRecentShareList(userID, count) {
  258. // 合并分享的项目和库
  259. const shareProjectList = await getShareList({owner: userID});
  260. const shareLibList = await getShareList({owner: userID}, true);
  261. const shareList = [...shareProjectList, ...shareLibList];
  262. shareList.sort((a, b) => Date.parse(b.shareDate) - Date.parse(a.shareDate));
  263. const set = new Set();
  264. for(const item of shareList) {
  265. if (set.size === count) {
  266. break;
  267. }
  268. set.add(item.receiver);
  269. }
  270. const sortedIDList = [...set];
  271. const userIDList = sortedIDList.map(userID => mongoose.Types.ObjectId(userID));
  272. const users = await userModel.find({_id: {$in: userIDList}}, 'real_name mobile company').lean();
  273. users.sort((a, b) => sortedIDList.indexOf(a._id.toString()) - sortedIDList.indexOf(b._id.toString()));
  274. return users;
  275. }
  276. // 获取某项目的分享记录
  277. async function getProjectShareList(projectID, limit = null) {
  278. const sharedList = limit
  279. ? await shareListModel.find({ projectID }).lean().sort({ shareDate: -1 }).limit(limit)
  280. : await shareListModel.find({ projectID }).lean().sort({ shareDate: -1 });
  281. const userIDs = [];
  282. const userMap = {};
  283. sharedList.forEach((item, index) => {
  284. userIDs.push(item.receiver);
  285. userMap[item.receiver] = item;
  286. userMap[item.receiver].index = index;
  287. });
  288. const userObjectIDs = userIDs.map(userID => mongoose.Types.ObjectId(userID));
  289. const users = await userModel.find({_id: {$in: userObjectIDs}}, 'real_name mobile company').lean();
  290. users.forEach(user => {
  291. const matched = userMap[user._id];
  292. if (matched) {
  293. user.index = matched.index;
  294. user.allowCopy = matched.allowCopy;
  295. user.allowCooperate = matched.allowCooperate;
  296. }
  297. });
  298. users.sort((a, b) => a.index - b.index);
  299. return users;
  300. }
  301. async function getReceiveLibList(receiver, compilationID, libType) {
  302. const sharedList = await shareLibModel.find({ receiver, compilationID, libType }).lean().sort({ shareDate: -1 });
  303. const userIDs = [];
  304. const userMap = {};
  305. sharedList.forEach((item, index) => {
  306. userIDs.push(item.owner);
  307. userMap[item.owner] = item;
  308. userMap[item.owner].index = index;
  309. });
  310. const userObjectIDs = userIDs.map(userID => mongoose.Types.ObjectId(userID));
  311. const users = await userModel.find({ _id: { $in: userObjectIDs } }, 'real_name').lean();
  312. users.forEach(user => {
  313. const matched = userMap[user._id];
  314. if (matched) {
  315. user.index = matched.index;
  316. }
  317. });
  318. users.sort((a, b) => a.index - b.index);
  319. return users;
  320. }
  321. // 获取某库的分享记录
  322. async function getLibShareList(owner, compilationID, libType, limit = null) {
  323. const sharedList = limit
  324. ? await shareLibModel.find({ owner, compilationID, libType }).lean().sort({ shareDate: -1 }).limit(limit)
  325. : await shareLibModel.find({ owner, compilationID, libType }).lean().sort({ shareDate: -1 });
  326. const userIDs = [];
  327. const userMap = {};
  328. sharedList.forEach((item, index) => {
  329. userIDs.push(item.receiver);
  330. userMap[item.receiver] = item;
  331. userMap[item.receiver].index = index;
  332. });
  333. const userObjectIDs = userIDs.map(userID => mongoose.Types.ObjectId(userID));
  334. const users = await userModel.find({_id: {$in: userObjectIDs}}, 'real_name mobile company').lean();
  335. users.forEach(user => {
  336. const matched = userMap[user._id];
  337. if (matched) {
  338. user.index = matched.index;
  339. }
  340. });
  341. users.sort((a, b) => a.index - b.index);
  342. return users;
  343. }
  344. // 获取某用户某费用定额的未读的被分享记录
  345. async function getUnreadShareListByCompilation(userID, compilationID, isGetCount) {
  346. const fields = isGetCount ? '-_id projectID ' : '-_id';
  347. const list = await shareListModel.find({ receiver: userID, isRead: false }, fields);
  348. const idList = list.reduce((acc, cur) => {
  349. acc.push(cur.projectID);
  350. return acc;
  351. }, []);
  352. const notDeleted = [{ deleteInfo: null }, { 'deleteInfo.deleted': false }];
  353. const query = { ID: { $in: idList }, compilation: compilationID, $or: notDeleted };
  354. if (isGetCount) {
  355. return await projectModel.count(query)
  356. }
  357. const items = await projectModel.find(query, '-_id ID').lean();
  358. return items.map(item => item.ID);
  359. }
  360. // 获取分享的提示(造价书分享按钮tooltip使用)
  361. async function getShareTip(projectID, limit) {
  362. const task = [
  363. getProjectShareList(projectID, limit),
  364. shareListModel.count({ projectID })
  365. ];
  366. const [users, count] = await Promise.all(task);
  367. return users.reduce((acc, user, index) => {
  368. if (index === 0) {
  369. acc += '已分享给';
  370. acc += user.real_name;
  371. } else {
  372. acc += ` ${user.real_name}`;
  373. }
  374. if (index === users.length - 1 && count > limit) {
  375. acc += `等${count}人`;
  376. }
  377. return acc;
  378. }, '');
  379. }
  380. // 获取项目的分享状态
  381. // 分享项目的拷贝和编辑性,需要参考父项
  382. // 以项目链上最新更新的分享数据为准
  383. async function getShareState(projectID, receiver) {
  384. const projectIDs = await getUpChainIDs(projectID);
  385. const shareList = await shareListModel.find({ projectID: { $in: projectIDs }, receiver }).lean();
  386. shareList.sort((a, b) => Date.parse(b.updateDate) - Date.parse(a.updateDate));
  387. return {
  388. allowCopy: shareList[0] && shareList[0].allowCopy || false,
  389. allowCooperate: shareList[0] && shareList[0].allowCooperate || false
  390. };
  391. }
  392. // 自身及父链上的分享数据(链距离最近的一个)
  393. async function getUpChainShareData(projectID, receiver) {
  394. while (projectID != -1) {
  395. const shareData = await shareListModel.findOne({ projectID, receiver }).lean();
  396. if (shareData) {
  397. return shareData;
  398. }
  399. const project = await projectModel.findOne({ ID: projectID }, '-_id ParentID').lean();
  400. projectID = project ? project.ParentID : -1;
  401. }
  402. return null;
  403. }
  404. // 标记已读分享条目
  405. // 打开任意的单位工程,都会将其父分享条目标记和自身为已读
  406. // eg:被分享了一个建设项目,和其下一个单位工程,打开该一个单位工程,建设项目标记为已读、该单位工程也标记为已读
  407. async function markShareItemsRead(projectID, userID) {
  408. const upChainIDs = await getUpChainIDs(projectID);
  409. const unreadList = await shareListModel.find({ projectID: { $in: upChainIDs }, receiver: userID, isRead: false }, '-_id ID projectID').lean();
  410. const markReadProjectIDs = [];
  411. const bulks = [];
  412. unreadList.forEach(item => {
  413. markReadProjectIDs.push(item.projectID);
  414. bulks.push({
  415. updateOne: {
  416. filter: { ID: item.ID },
  417. update: { isRead: true }
  418. }
  419. });
  420. });
  421. if (bulks.length) {
  422. await shareListModel.bulkWrite(bulks);
  423. }
  424. return markReadProjectIDs;
  425. }
  426. /**
  427. * 分享权限变更后,根据变更操作,获取相关项目的分享权限信息
  428. * 不能简单根据某个项目的分享信息获得其权限,因为目前的分享可以重复分享(分享单位工程A、分享包含单位工程A的父项)
  429. * 最新的分享权限是由项目链上(所有子项、自身、父项...)最新的分享信息决定的
  430. * @param {Number} permissionType - 分享权限变更类型
  431. * @param {String} receiver - 用户ID
  432. * @param {Number} projectID - 项目ID
  433. */
  434. async function getShareInfoAfterChangePermission(permissionType, receiver, projectID) {
  435. const project = await projectModel.findOne({ ID: projectID }, '-_id ID projType').lean();
  436. if (!project) {
  437. return [];
  438. }
  439. // UPDATE_COPY不触发推送给主页面的消息
  440. const propChange = [SharePermissionChangeType.UPDATE_COOPERATE].includes(permissionType);
  441. const cancelShare = permissionType === SharePermissionChangeType.CANCEL;
  442. // 需要处理的单位工程
  443. if (propChange && project.projType === projectType.tender) {
  444. const shareData = await shareListModel.findOne({ projectID, receiver }, '-_id allowCooperate allowCopy updateDate').lean();
  445. const tender = { ID: projectID };
  446. if (shareData) {
  447. Object.assign(tender, shareData);
  448. }
  449. return [tender];
  450. }
  451. if (propChange && project.projType !== projectType.tender) {
  452. const projects = await getPosterityProjects([projectID], false, '-_id ID projType');
  453. const tenders = projects.filter(p => p.projType === projectType.tender);
  454. const shareData = await shareListModel.findOne({ projectID, receiver }, '-_id allowCooperate allowCopy updateDate').lean();
  455. if (shareData) {
  456. tenders.forEach(tender => Object.assign(tender, shareData));
  457. }
  458. return tenders
  459. }
  460. if (cancelShare && project.projType === projectType.tender) {
  461. const shareData = await getUpChainShareData(projectID, receiver);
  462. return shareData ? [] : [{ ID: projectID }];
  463. }
  464. if (cancelShare && project.projType !== projectType.tender) {
  465. const projects = await getPosterityProjects([projectID], false, '-_id ID projType');
  466. const tenders = [];
  467. for (const p of projects) {
  468. if (p.projType === projectType.tender) {
  469. const shareData = await getUpChainShareData(p.ID, receiver);
  470. if (!shareData) {
  471. tenders.push({ ID: p.ID });
  472. }
  473. }
  474. }
  475. return tenders;
  476. }
  477. return [];
  478. }
  479. //拷贝例题项目
  480. //@param {String}userID {Array}projIDs拷贝的例题项目ID(建设项目、文件夹)@return {Boolean}
  481. async function copyExample(userID, compilation, projIDs,nameMap){
  482. let allProjs = [],
  483. IDMapping = {},
  484. projMapping = {};
  485. //例题项目不可为单项工程、单位工程、只能是建设项目、文件夹,否则不自动新建例题项目(这里不报错,让用户没有感觉)
  486. let parentExample = await projectModel.find({ID: {$in: projIDs}, $or: notDeleted}).lean();
  487. if (parentExample.length === 0) {
  488. return false;
  489. }
  490. allProjs = allProjs.concat(parentExample);
  491. for (let i = 0; i < parentExample.length; i++) {
  492. let data = parentExample[i];
  493. if (data.projType === projectType.tender || data.projType === projectType.engineering) {
  494. return false;
  495. }
  496. //设置成顶节点,最后一个节点设置成末节
  497. data.ParentID = -1;
  498. if (i === parentExample.length - 1) {
  499. data.NextSiblingID = -1;
  500. }
  501. if(nameMap && nameMap[data.ID]) data.name = nameMap[data.ID];
  502. }
  503. //获取所有的子项目
  504. let posterityProjs = await getPosterityProjects(projIDs);
  505. allProjs = allProjs.concat(posterityProjs);
  506. let projCounter = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, allProjs.length);
  507. //旧ID与新ID映射
  508. for (let i = 0; i < allProjs.length; i++) {
  509. let data = allProjs[i];
  510. let newID = projCounter.sequence_value - (allProjs.length - 1) + i;
  511. IDMapping[data.ID] = newID;
  512. projMapping[newID] = data;
  513. }
  514. //return;
  515. //设置新的树结构数据
  516. let newDate = new Date(),
  517. parentBulks = [];
  518. const projectMaps = [];
  519. // 传入项目ID的新ID
  520. const newProjIDs = [];
  521. for (let data of allProjs) {
  522. let orgID = data.ID;
  523. data.ID = IDMapping[data.ID];
  524. if (projIDs.indexOf(orgID) >= 0) {
  525. newProjIDs.push(data.ID);
  526. }
  527. data.ParentID = IDMapping[data.ParentID] ? IDMapping[data.ParentID] : -1;
  528. data.NextSiblingID = IDMapping[data.NextSiblingID] ? IDMapping[data.NextSiblingID] : -1;
  529. data.createDateTime = newDate;
  530. data.userID = userID;
  531. data.compilation = compilation;
  532. data.shareInfo = [];
  533. if (data.projType !== projectType.tender) {
  534. let newData = _.cloneDeep(data);
  535. delete newData._id;
  536. // await projectModel.create(newData);
  537. parentBulks.push({insertOne: {document: newData}});
  538. } else {
  539. //拷贝单位工程
  540. let rootProjectID = projMapping[data.ParentID].ParentID;
  541. let projectMap = {
  542. copy: {
  543. document: {userID: userID, ID: orgID, NextSiblingID: data.NextSiblingID, ParentID: data.ParentID, name: data.name, shareInfo: [],
  544. compilation: compilation, fileVer: data.fileVer, projType: data.projType, property: {rootProjectID: rootProjectID}}
  545. }
  546. };
  547. await copyProject(userID, compilation, {projectMap}, data.ID, true);
  548. projectMaps.push(projectMap);
  549. }
  550. }
  551. //最末顶层项目(兼容测试时已存在有项目,正常用户第一次进费用定额,该费用定额不存在项目)
  552. let lastProj = await projectModel.findOne({userID: userID, compilation: compilation, ParentID: -1, NextSiblingID: -1, $or: notDeleted});
  553. if (lastProj) {
  554. parentBulks.push({updateOne: {filter: {ID: lastProj.ID}, update: {$set: {NextSiblingID: parentExample[0].ID}}}});
  555. }
  556. // 处理项目数据
  557. const projectTasks = [projectModel.bulkWrite(parentBulks), createProject(projectMaps)];
  558. await Promise.all(projectTasks);
  559. return newProjIDs;
  560. }
  561. async function accessToCopyProject(userID, compilationID, data, newProjectID) {
  562. const logData = {
  563. key: uuidV1(),
  564. content: '正在拷贝项目,请稍候……',
  565. userID,
  566. compilationID,
  567. status: 'start',
  568. create_time: +new Date()
  569. };
  570. await importLogsModel.create(logData);
  571. handleCopyProject(logData.key, userID, compilationID,data,newProjectID);
  572. return 'copying project';
  573. }
  574. async function handleCopyProject(key, userID, compilationID, data, newProjectID) {
  575. const doc = { status: 'finish' };
  576. try {
  577. const projectMap = await copyProject(userID, compilationID, data, newProjectID);
  578. doc.projectID = [projectMap.copy.document.ID];
  579. } catch (err) {
  580. doc.status = 'error';
  581. doc.errorMsg = String(err);
  582. } finally {
  583. await importLogsModel.update({ key }, doc);
  584. }
  585. }
  586. async function copyProject(userID, compilationID,data,newProjectID = null, delayProjectTask = false) {
  587. let projectMap = data.projectMap;
  588. let originalID = projectMap['copy'].document.ID;
  589. if (!newProjectID) {
  590. newProjectID = await getCounterID("projects");
  591. }
  592. let newFeeName = null,newUnitName = null;
  593. let calcProgramFileID = uuidV1();//新的计算程序文件ID
  594. let labourCoeFileID = uuidV1();//新的人工调整系数文件ID
  595. let feeRateFileID = uuidV1();//新的费率文件ID
  596. let unitPriceFileID = await getCounterID("unit_price_file");//新的单价文件ID
  597. let originalProject = await projectModel.findOne({'ID':originalID});//查找最新的那项目信息,前端缓存的数据有可能不是最新的
  598. if(!originalProject){
  599. throw new Error('没有找到对应的项目,复制失败!');
  600. }
  601. let property = originalProject.property;
  602. if(projectMap['copy'].document.property){//更新项目属性信息
  603. setProperty(property,projectMap['copy'].document.property);
  604. }
  605. let originalProperty = _.cloneDeep(property);
  606. projectMap['copy'].document.property = property;
  607. logger.info("复制项目: 旧项目ID: "+originalID+ " ------- 新项目ID: "+newProjectID);
  608. //费率文件、单价文件重名检查
  609. let feeRate = await feeRateFileModel.findOne({rootProjectID:originalProperty.rootProjectID,name:originalProperty.feeFile.name,deleteInfo:null});
  610. if(feeRate){//存在重名的文件
  611. newFeeName = originalProperty.feeFile.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '复制)';
  612. projectMap['copy'].document.property.feeFile.name = newFeeName;
  613. }
  614. let unitPriceFile = await unitPriceFileModel.findOne({root_project_id: originalProperty.rootProjectID,name:originalProperty.unitPriceFile.name,deleteInfo: null});
  615. if(unitPriceFile){//存在重名的文件
  616. newUnitName = originalProperty.unitPriceFile.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '复制)';
  617. projectMap['copy'].document.property.unitPriceFile.name = newUnitName;
  618. }
  619. //更新项目的属性;
  620. projectMap['copy'].document.ID = newProjectID;
  621. if(projectMap['copy'].document.property.calcProgramFile){
  622. projectMap['copy'].document.property.calcProgramFile.ID = calcProgramFileID;
  623. }
  624. if(projectMap['copy'].document.property.labourCoeFile){
  625. projectMap['copy'].document.property.labourCoeFile.ID = labourCoeFileID;
  626. }
  627. if(projectMap['copy'].document.property.feeFile){
  628. projectMap['copy'].document.property.feeFile.id = feeRateFileID;
  629. }
  630. if(projectMap['copy'].document.property.unitPriceFile){
  631. projectMap['copy'].document.property.unitPriceFile.id = unitPriceFileID;
  632. }
  633. projectMap['copy'].document.userID = userID;
  634. projectMap['copy'].document.compilation = compilationID;
  635. projectMap['copy'].document.createDateTime = new Date();
  636. //清单、定额ID生成任务
  637. let IDtasks = [
  638. createIDsAndReturn(originalID,billsModel),
  639. createIDsAndReturn(originalID,rationModel),
  640. getProjectGLJIDAndReturn(originalID,newProjectID)
  641. ];
  642. let [billMap,rationMap,projectGLJMap] = await Promise.all(IDtasks);
  643. //所有复制任务异步处理,提升效率 复制清单,定额,4个文件,项目工料机, 定额工料机,人工系数,工程量明细,定额安装增加费,安装增加费
  644. let copyTasks = [
  645. copyProjectSetting(originalID,newProjectID),
  646. copyBills(newProjectID,billMap),
  647. copyRations(newProjectID,billMap.uuidMaping,rationMap,projectGLJMap.IDMap),
  648. copyProjectGLJ(projectGLJMap.datas),
  649. copyInstallFee(originalID,newProjectID),
  650. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationGLJModel),
  651. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationCoeModel),
  652. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,quantityDetailModel),
  653. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationInstallationModel),
  654. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationTemplateModel),
  655. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,evaluateListModel),
  656. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,bidListModel),
  657. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,contractorListModel),
  658. ];
  659. if(originalProperty.calcProgramFile){
  660. copyTasks.push(commonCopy(newProjectID,originalProperty.calcProgramFile.ID,calcProgramFileID,calcProgramsModel));
  661. }
  662. if(originalProperty.labourCoeFile){
  663. copyTasks.push(commonCopy(newProjectID,originalProperty.labourCoeFile.ID,labourCoeFileID,labourCoesModel));
  664. }
  665. if(originalProperty.feeFile){
  666. copyTasks.push(copyFeeRate(originalProperty.rootProjectID,userID,originalProperty.feeFile.id,feeRateFileID,newFeeName));
  667. }
  668. if(originalProperty.unitPriceFile){
  669. copyTasks.push(copyUnitPriceFile(newProjectID,originalProperty.rootProjectID,userID,originalProperty.unitPriceFile.id,unitPriceFileID,newUnitName));
  670. }
  671. //复制设备购置
  672. copyTasks.push(copyEquipment(newProjectID,originalID));
  673. // 复制费用汇总
  674. copyTasks.push(copyGatherFee(newProjectID, originalID));
  675. await Promise.all(copyTasks);
  676. // 最后再处理项目数据
  677. // 可能会有最后再在外层方法插入项目数据的需求,如拷贝例题,暂时先不在这里插入项目数据
  678. if (delayProjectTask) {
  679. return [projectMap];
  680. } else {
  681. const projectMaps = await createProject([projectMap]);
  682. return projectMaps[0];
  683. }
  684. }
  685. async function createIDsAndReturn(originalID,model) {
  686. let uuidMaping = {};//做ID映射
  687. let datas = [];
  688. let result = await model.find({"projectID": originalID}, '-_id').lean();
  689. uuidMaping['-1'] = -1;
  690. //建立uuid-ID映射
  691. for(let d of result){
  692. uuidMaping[d.ID] = uuidV1();
  693. datas.push(d);
  694. }
  695. return{uuidMaping:uuidMaping,datas:datas};
  696. }
  697. async function getProjectGLJIDAndReturn(originalID,newProjectID) {
  698. let IDMap = {};
  699. let datas = [];
  700. let result = await gljListModel.find({project_id:originalID}, '-_id').lean();
  701. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, result.length);
  702. for(let i = 0; i < result.length; i++){
  703. let d = result[i];
  704. let newID = gljCount.sequence_value - (result.length - 1) + i;
  705. //let newID = await getCounterID("glj_list");
  706. IDMap[d.id] = newID;
  707. d.project_id = newProjectID;
  708. d.id = newID;
  709. datas.push(d);
  710. }
  711. return{IDMap:IDMap,datas:datas};
  712. }
  713. async function createProject(projectMaps) {//复制项目
  714. let tasks = [];
  715. for (const projectMap of projectMaps) {
  716. if(projectMap['update']){//如果复制后存在前一个节点,则更新其NextSiblingID
  717. tasks.push({updateOne:{filter : projectMap['update'].query, update : {NextSiblingID:projectMap['copy'].document.ID}}});
  718. }
  719. tasks.push({insertOne: {document: projectMap['copy'].document}});//复制任务
  720. }
  721. await projectModel.bulkWrite(tasks);
  722. return projectMaps;
  723. }
  724. async function copyProjectSetting(originalID,newProjectID) {
  725. let result = null;
  726. let setting = await projectSettingModel.findOne({"projectID": originalID}, '-_id');
  727. if(setting){
  728. setting._doc.projectID =newProjectID;
  729. result = await projectSettingModel.create(setting._doc);
  730. }
  731. return result;
  732. }
  733. async function copyBills(newProjectID,billMap) {
  734. let uuidMaping = billMap.uuidMaping;//做ID映射
  735. for(let doc of billMap.datas){
  736. doc = getCopyBillDatas(doc,newProjectID,uuidMaping);
  737. }
  738. await insertMany(billMap.datas,billsModel);
  739. return billMap.datas;
  740. }
  741. function getCopyBillDatas(doc,newProjectID,uuidMaping) {
  742. doc.projectID = newProjectID;
  743. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  744. doc.ParentID = uuidMaping[doc.ParentID] ? uuidMaping[doc.ParentID] : -1;
  745. doc.NextSiblingID = uuidMaping[doc.NextSiblingID] ? uuidMaping[doc.NextSiblingID] : -1;
  746. //对于有基数计算的节点,需要替换计算基数中引用的ID为新的ID
  747. if(doc.calcBase && doc.calcBase != ""){
  748. let idArr = scMathUtil.getFIDArr(doc.calcBase);
  749. for(let re of idArr){
  750. let oID = re.substr(1);//去掉开头的@字符
  751. if(!uuidMaping[oID]) continue;
  752. doc.calcBase = doc.calcBase.replace(new RegExp(oID, "g"),uuidMaping[oID]);
  753. }
  754. }
  755. return doc;
  756. }
  757. async function copyRations(newProjectID,billsIDMap,rationMap,projectGLJIDMap) {
  758. let uuidMaping = rationMap.uuidMaping;
  759. for(let doc of rationMap.datas){
  760. doc = getCopyRationData(doc,newProjectID,billsIDMap,uuidMaping,projectGLJIDMap);
  761. }
  762. if(rationMap.datas.length > 0){
  763. await insertMany(rationMap.datas,rationModel);
  764. }
  765. return rationMap.datas;
  766. }
  767. function getCopyRationData(doc,newProjectID,billsIDMap,uuidMaping,projectGLJIDMap){
  768. doc.projectID = newProjectID;
  769. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  770. if(doc.billsItemID){
  771. doc.billsItemID = billsIDMap[doc.billsItemID]?billsIDMap[doc.billsItemID]:-1;
  772. }
  773. if(doc.referenceRationID) doc.referenceRationID = uuidMaping[doc.referenceRationID]?uuidMaping[doc.referenceRationID]:undefined;
  774. //绑定定类型的工料机 项目工料机ID
  775. doc.type==3&&doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  776. return doc;
  777. }
  778. async function copyProjectGLJ(gljList) {
  779. await insertMany(gljList,gljListModel);
  780. }
  781. async function copyEquipment(newProjectID,oldProjectID){//复制设备购置费
  782. let result = null;
  783. const equipments = await equipmentPurchaseModel.findOne({projectID:oldProjectID}, '-_id').lean();
  784. if(equipments){
  785. equipments.projectID = newProjectID;
  786. result = await equipmentPurchaseModel.create(equipments);
  787. }
  788. return result;
  789. }
  790. // 复制费用汇总
  791. async function copyGatherFee(newProjectID, oldProjectID) {
  792. let result = null;
  793. const gatherItem = await gaterFeeModel.findOne({ projectID: oldProjectID }, '-_id').lean();
  794. if (gatherItem) {
  795. gatherItem.projectID = newProjectID;
  796. result = await gaterFeeModel.create(gatherItem);
  797. }
  798. return result;
  799. }
  800. async function commonCopy(newProjectID,oldID,newID,model) { //对于只需更新ID和projectID的文件的复制
  801. let result = null;
  802. let file = await model.findOne({"ID": oldID}, '-_id');
  803. if(file){
  804. file._doc.ID = newID;
  805. file._doc.projectID =newProjectID;
  806. result = await model.create(file._doc);
  807. }
  808. return result;
  809. }
  810. async function copyFeeRate(rootProjectID,userID,originalFeeRateFileID,feeRateFileID,newName) {//复制费率和费率文件
  811. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(originalFeeRateFileID);
  812. let newFeeRateID = uuidV1();
  813. if(feeRate){
  814. feeRate._doc.ID = newFeeRateID;
  815. await feeRateModel.create(feeRate._doc);
  816. }
  817. if(feeRateFile){
  818. feeRateFile._doc.ID = feeRateFileID;
  819. newName?feeRateFile._doc.name = newName:'';
  820. feeRateFile._doc.userID = userID;
  821. feeRateFile._doc.rootProjectID = rootProjectID;
  822. feeRateFile._doc.feeRateID = newFeeRateID;
  823. await feeRateFileModel.create(feeRateFile._doc);
  824. }
  825. }
  826. async function copyUnitPriceFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName) {//复制单价文件、组成物
  827. let taskList = [
  828. copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName),
  829. copySubList(originaluUnitPriceFileID,unitPriceFileID,mixRatioModel),
  830. copySubList(originaluUnitPriceFileID,unitPriceFileID,unitPriceModel)
  831. ];
  832. return await Promise.all(taskList);
  833. async function copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName){
  834. let unitPriceFile = await unitPriceFileModel.findOne({id:originaluUnitPriceFileID}, '-_id');
  835. if(unitPriceFile){
  836. unitPriceFile._doc.id = unitPriceFileID;
  837. newName?unitPriceFile._doc.name = newName:'';
  838. unitPriceFile._doc.project_id = newProjectID;
  839. unitPriceFile._doc.user_id = userID;
  840. unitPriceFile._doc.root_project_id = rootProjectID
  841. }
  842. await unitPriceFileModel.create(unitPriceFile._doc);
  843. }
  844. async function copySubList(srcFID,newFID,model) {
  845. let mList = await model.find({unit_price_file_id: srcFID}, '-_id').lean();
  846. let rList = [];
  847. let IDcounter = await counter.counterDAO.getIDAfterCountSync(model.modelName, mList.length);
  848. let firstID = IDcounter.sequence_value - (mList.length - 1);
  849. for(let m of mList){
  850. m.unit_price_file_id = newFID;
  851. m.id = firstID;
  852. firstID+=1
  853. rList.push(m);
  854. }
  855. await insertMany(rList,model)
  856. }
  857. }
  858. async function copyInstallFee(originalPID,newProjectID) {
  859. let result = null;
  860. let installationFee = await installationFeeModel.find({projectID:originalPID}, '-_id');
  861. let newList = [];
  862. for(let i of installationFee ){
  863. i._doc.ID = uuidV1();
  864. i._doc.projectID = newProjectID;
  865. newList.push(i._doc);
  866. }
  867. if(newList.length >0){
  868. result = await installationFeeModel.insertMany(newList);
  869. }
  870. return result;
  871. }
  872. async function copyRationSubList(originalPID,newProjectID,billIDMap,rationIDMap,projectGLJIDMap,model) {// 定额工料机,附注条件,工程量明细,定额安装增加费,模板子目
  873. let first = +new Date();
  874. let subList = await model.find({projectID:originalPID}, '-_id').lean();
  875. let newList =[];
  876. for(let s of subList){
  877. s = getCopyRationSubData(s,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  878. newList.push(s);
  879. }
  880. if(newList.length > 0) await insertMany(newList,model);
  881. let last = +new Date();
  882. console.log(model.modelName+"-------"+newList.length+"--copyRationSubList - insert时间为-------------------------------"+(last-first));
  883. }
  884. async function copyMaterialList(originalPID,newProjectID,projectGLJIDMap,model) {//暂估材料等信息
  885. let materialList = await model.find({projectID:originalPID}, '-_id').lean();
  886. let newList = [];
  887. for(let m of materialList){
  888. newList.push(getNewMaterial(m,newProjectID,projectGLJIDMap))
  889. }
  890. await insertMany(newList,model);
  891. }
  892. function getNewMaterial(m,newProjectID,projectGLJIDMap) {
  893. m.ID = uuidV1();
  894. m.projectID = newProjectID;
  895. if(projectGLJIDMap[m.projectGLJID]) m.projectGLJID = projectGLJIDMap[m.projectGLJID];
  896. return m;
  897. }
  898. function getCopyRationSubData(doc,newProjectID,billIDMap,rationIDMap,projectGLJIDMap){
  899. doc.ID = uuidV1();
  900. doc.projectID = newProjectID;
  901. doc.rationID&&rationIDMap[doc.rationID]?doc.rationID = rationIDMap[doc.rationID]:'';
  902. doc.billID&&billIDMap[doc.billID]?doc.billID = billIDMap[doc.billID]:'';
  903. doc.billsItemID&&billIDMap[doc.billsItemID]?doc.billsItemID = billIDMap[doc.billsItemID]:'';
  904. doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  905. if(doc.templateList && doc.templateList.length > 0 ){
  906. for(let t of doc.templateList){
  907. if(t.billID && billIDMap[t.billID]) t.billID = billIDMap[t.billID];
  908. if(t.fxID && billIDMap[t.fxID]) t.fxID = billIDMap[t.fxID];
  909. }
  910. }
  911. return doc;
  912. }
  913. async function moveProject(data) {
  914. data = JSON.parse(data);
  915. let projectMap = data.projectMap,feeRateMap = data.feeRateMap,unitPriceMap = data.unitPriceMap;
  916. let projectTasks = [],feeRateTask=[],feeRateFileTask=[],unitPriceTask=[],unitPriceFileTask=[],mixRatioTask=[];
  917. let feeUniqMap=[],priceUniqMap={};//费率、单价文件唯一映射表当移动多个项目时,任务有可能出现重复的情况
  918. if(!_.isEmpty(feeRateMap)&&data.rootProjectID){//如果费率有修改
  919. let feeRates =await feeRate_facade.getFeeRatesByProject(data.rootProjectID);//取目标建设项目的所有费率文件,重名检查
  920. for(let projectID in feeRateMap){
  921. let rename = feeRateMap[projectID].name;
  922. let feeRateID = feeRateMap[projectID].query.ID;
  923. let checkFee = _.find(feeRates,{'name':rename});
  924. let newID = feeRateID;
  925. if(checkFee){//说明费率名字已存在,需要重命名
  926. rename = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  927. projectMap[projectID]['update']['property.feeFile.name'] = rename;
  928. if(feeRateMap[projectID].action == 'move'){
  929. feeRateMap[projectID].update.name = rename;
  930. }
  931. }
  932. if(feeRateMap[projectID].action == 'copy'){
  933. newID = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].ID:uuidV1();
  934. feeRateMap[projectID].name = rename;
  935. feeRateMap[projectID].ID = newID;
  936. projectMap[projectID]['update']['property.feeFile.id'] = newID;
  937. }
  938. if(!feeUniqMap[feeRateID]){
  939. await generateFeeRateTask(feeRateMap[projectID],feeRateTask,feeRateFileTask);
  940. feeUniqMap[feeRateID] = {name:rename,ID:newID};
  941. }
  942. }
  943. }
  944. if(!_.isEmpty(unitPriceMap)&&data.rootProjectID) {//如果单价文件有修改
  945. let unitPriceFiles = await unitPriceFileModel.find({root_project_id: data.rootProjectID, deleteInfo: null});
  946. for(let projectID in unitPriceMap){
  947. let checkUn = _.find(unitPriceFiles,{'name':unitPriceMap[projectID].name});
  948. let rename = unitPriceMap[projectID].name;
  949. let unitPriceID = unitPriceMap[projectID].query.id;
  950. let newID = unitPriceID;
  951. if(checkUn){//重名检查
  952. rename = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  953. projectMap[projectID]['update']['property.unitPriceFile.name'] = rename;
  954. if(unitPriceMap[projectID].action =='move'){
  955. unitPriceMap[projectID].update.name = rename;
  956. }
  957. }
  958. if(unitPriceMap[projectID].action =='copy'){
  959. newID = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].id: await getCounterID("unit_price_file");
  960. unitPriceMap[projectID].name = rename;
  961. unitPriceMap[projectID].id = newID;
  962. projectMap[projectID]['update']['property.unitPriceFile.id'] = newID;
  963. }
  964. if(!priceUniqMap[unitPriceID]){
  965. await generateUnitPriceTask(unitPriceMap[projectID],projectID,data.user_id,unitPriceTask,unitPriceFileTask,mixRatioTask);
  966. priceUniqMap[unitPriceID] = {name:rename,id:newID};
  967. }
  968. }
  969. }
  970. if(!_.isEmpty(projectMap)){
  971. for(let projectID in projectMap){
  972. projectTasks.push({updateOne:{filter : projectMap[projectID].query, update : projectMap[projectID].update}});
  973. }
  974. }
  975. projectTasks.length>0?await projectModel.bulkWrite(projectTasks):'';
  976. feeRateTask.length>0?await feeRateModel.bulkWrite(feeRateTask):'';
  977. feeRateFileTask.length>0?await feeRateFileModel.bulkWrite(feeRateFileTask):'';
  978. unitPriceFileTask.length>0?await unitPriceFileModel.bulkWrite(unitPriceFileTask):'';
  979. unitPriceTask.length>0?await insertMany(unitPriceTask,unitPriceModel):'';
  980. mixRatioTask.length>0?await insertMany(mixRatioTask,mixRatioModel):'';
  981. return projectMap;
  982. }
  983. async function generateFeeRateTask(data,feeRateTask,feeRateFileTask) {
  984. if(data.action == 'move'){
  985. let task = {
  986. updateOne:{
  987. filter : data.query,
  988. update : data.update
  989. }
  990. };
  991. feeRateFileTask.push(task);
  992. }
  993. if(data.action == 'copy'){//copy 费率的时候用insertOne方法
  994. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(data.query.ID);
  995. let newFeeRateID = uuidV1();
  996. let newFeeRate = {
  997. ID:newFeeRateID,
  998. rates:feeRate.rates
  999. };
  1000. let newFeeRateFile = {
  1001. ID:data.ID,
  1002. rootProjectID:data.rootProjectID,
  1003. userID:feeRateFile.userID,
  1004. name:data.name,
  1005. libID:feeRateFile.libID,
  1006. libName:feeRateFile.libName,
  1007. feeRateID:newFeeRateID
  1008. };
  1009. feeRateTask.push({insertOne :{document:newFeeRate}});
  1010. feeRateFileTask.push({insertOne :{document:newFeeRateFile}});
  1011. }
  1012. }
  1013. async function generateUnitPriceTask(data,projectID,user_id,unitPriceTask,unitPriceFileTask,mixRatioTask){
  1014. if(data.action == 'move'){
  1015. let task = {
  1016. updateOne:{
  1017. filter : data.query,
  1018. update : data.update
  1019. }
  1020. };
  1021. unitPriceFileTask.push(task);
  1022. }
  1023. if(data.action == 'copy'){
  1024. let newUnitFile = {
  1025. id:data.id,
  1026. name: data.name,
  1027. project_id:projectID,
  1028. user_id:user_id,
  1029. root_project_id: data.rootProjectID
  1030. };
  1031. unitPriceFileTask.push({insertOne :{document:newUnitFile}});
  1032. let mixRatios = await mixRatioModel.find({unit_price_file_id: data.query.id});
  1033. mixRatios = JSON.stringify(mixRatios);
  1034. mixRatios = JSON.parse(mixRatios);
  1035. for(let m of mixRatios){
  1036. delete m._id; // 删除原有id信息
  1037. delete m.id;
  1038. m.unit_price_file_id = data.id;
  1039. m.id = await getCounterID('mix_ratio');
  1040. mixRatioTask.push(m);
  1041. }
  1042. let unitPrices = await unitPriceModel.find({unit_price_file_id: data.query.id});//unit_price_file_id
  1043. unitPrices = JSON.stringify(unitPrices);
  1044. unitPrices = JSON.parse(unitPrices);
  1045. for(let u of unitPrices){
  1046. delete u._id; // 删除原有id信息
  1047. delete u.id;
  1048. u.unit_price_file_id = data.id;
  1049. u.id = await getCounterID('unit_price');
  1050. unitPriceTask.push(u);
  1051. }
  1052. }
  1053. }
  1054. async function getCounterID(collectionName){
  1055. let counterModel = new CounterModel();
  1056. return await counterModel.getId(collectionName);
  1057. }
  1058. async function insertMany(datas,model) {
  1059. /* while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入 2020-05-28 测试后发现没有限制,暂时先保留代码
  1060. let newList = datas.splice(0,1000);//一次插入1000条
  1061. await model.insertMany(newList);
  1062. } */
  1063. await model.insertMany(datas);
  1064. }
  1065. function setProperty(Obj,updateData) {
  1066. for(let ukey in updateData){
  1067. if(_.isObject(updateData[ukey]) && _.isObject(Obj[ukey])){
  1068. setProperty(Obj[ukey],updateData[ukey]);
  1069. }else {
  1070. Obj[ukey] = updateData[ukey];
  1071. }
  1072. }
  1073. }
  1074. function isDef(v){
  1075. return typeof v !== 'undefined' && v !== null;
  1076. }
  1077. function getTotalFee(bills, feeName) {
  1078. if(!isDef(bills)){
  1079. return 0;
  1080. }
  1081. if(!isDef(bills.fees) || bills.fees.length <= 0){
  1082. return 0;
  1083. }
  1084. for(let fee of bills.fees){
  1085. if(isDef(fee.fieldName) && fee.fieldName === feeName){
  1086. return isDef(fee.tenderTotalFee)
  1087. ? fee.tenderTotalFee
  1088. : isDef(fee.totalFee)
  1089. ? fee.totalFee
  1090. : 0;
  1091. }
  1092. }
  1093. return 0;
  1094. }
  1095. function summarizeToParent(parent, child, fields = null) {
  1096. const decimal = -2;
  1097. if (!fields) {
  1098. fields = ['engineeringCost', 'subEngineering', 'measure', 'safetyConstruction', 'other', 'charge', 'tax', 'estimate'];
  1099. }
  1100. for (let field of fields) {
  1101. parent[field] = scMathUtil.roundTo(parseFloat(parent[field]) + parseFloat(child[field]), decimal);
  1102. }
  1103. }
  1104. function getBuildingArea(projFeature){
  1105. if(!projFeature || projFeature.length === 0){
  1106. return null;
  1107. }
  1108. for(let f of projFeature){
  1109. if(f.key === 'buildingArea'){
  1110. return f.value;
  1111. }
  1112. }
  1113. return null;
  1114. }
  1115. //根据单位工程ID获取经济指标信息
  1116. //@param {Number}prj_id @return {Object}
  1117. async function getIndexReportData(prj_id, filters) {
  1118. return await project_facade.getIndexReportData(prj_id, filters);
  1119. }
  1120. // 根据树结构数据排序
  1121. function getSortedDataByTree(data) {
  1122. // NextSiblingID-数据映射
  1123. const mapping = {};
  1124. data.forEach(item => {
  1125. // 错误数据兼容处理
  1126. // 由于之前的导入建设项目,会导致最后的一个项目的NextSiblingID为空,为非正确的-1
  1127. // 因此把项目中NextSibling为空的数据设置为NextSiblingID为-1
  1128. if (!item.NextSiblingID) {
  1129. item.NextSiblingID = -1;
  1130. }
  1131. mapping[item.NextSiblingID] = item;
  1132. });
  1133. let lastItem = data.find(item => +item.NextSiblingID === -1);
  1134. if (!lastItem) {
  1135. return data;
  1136. }
  1137. const rst = [lastItem];
  1138. let preItem = mapping[lastItem.ID];
  1139. while (preItem) {
  1140. rst.unshift(preItem);
  1141. preItem = mapping[preItem.ID];
  1142. }
  1143. // 根据树结构排序形成的新数组与旧数组项数不同,说明树结构数据有问题(断链),则返回原本数据。
  1144. return rst.length === data.length ? rst : data;
  1145. }
  1146. //根据单位工程ID获取汇总信息
  1147. //@param {Number}tenderID {String}summaryType @return {Object}
  1148. async function getSummaryInfoByTender(tenderID, summaryType) {
  1149. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  1150. let tender = await projectModel.findOne({ID: tenderID, $or: notDeleted});
  1151. let parent,
  1152. parentName,
  1153. compilationIllustration;
  1154. let summaryList = [];
  1155. if(!tender){
  1156. return null;
  1157. }
  1158. let engineering = await projectModel.findOne({ID: tender.ParentID, $or: notDeleted});
  1159. if(!engineering){
  1160. return null;
  1161. }
  1162. let project = await projectModel.findOne({ID: engineering.ParentID, $or: notDeleted});
  1163. if(!project){
  1164. return null;
  1165. }
  1166. let summaryInfo = await getSummaryInfo([project.ID]);
  1167. if(summaryType === projectType.engineering){ // 汇总到单项工程级别
  1168. parent = engineering;
  1169. let tenders = await projectModel.find({ParentID: engineering.ID, $or: notDeleted}).lean();
  1170. tenders = getSortedDataByTree(tenders);
  1171. for(let t of tenders){
  1172. if(summaryInfo[t.ID]){
  1173. summaryInfo[t.ID]['name'] = t.name ? t.name : '';
  1174. summaryList.push(summaryInfo[t.ID]);
  1175. }
  1176. }
  1177. } else { // 汇总到建设项目级别
  1178. parent = project;
  1179. let engs = await projectModel.find({ParentID: project.ID, $or: notDeleted}).lean();
  1180. engs = getSortedDataByTree(engs);
  1181. for(let e of engs){
  1182. if(summaryInfo[e.ID]){
  1183. summaryInfo[e.ID]['name'] = e.name ? e.name : '';
  1184. summaryList.push(summaryInfo[e.ID]);
  1185. }
  1186. }
  1187. }
  1188. // 项目名称
  1189. parentName = parent && parent.name
  1190. ? parent.name
  1191. : '';
  1192. // 编制说明
  1193. compilationIllustration = parent && parent.property && parent.property.compilationIllustration
  1194. ? parent.property.compilationIllustration
  1195. : '';
  1196. return {
  1197. parent: {
  1198. name: parentName,
  1199. compilationIllustration: compilationIllustration},
  1200. subList: summaryList
  1201. };
  1202. }
  1203. //获取单位工程的各标段费用信息(不进行汇总)
  1204. async function getTendersFeeInfo(tenders) {
  1205. const unitIDs = tenders.map(tender => tender.ID);
  1206. const unitsBudgetMap = await billFacade.getUnitsBudgetMap(unitIDs);
  1207. const unitsEquipmentMap = await billFacade.getUnitsEquipmentMap(unitIDs);
  1208. const IDMapping = {};
  1209. tenders.forEach(tender => {
  1210. const unitID = tender.ID;
  1211. const decimal = tender && tender.property && tender.property.decimal && tender.property.decimal.bills && tender.property.decimal.bills.totalPrice || 2;
  1212. const unitFee = +unitsBudgetMap[unitID]; // 费用汇总算出来的值
  1213. const unitEquipmentFee = +unitsEquipmentMap[unitID]; // 设备购置窗口的值
  1214. const unitTotalFee = scMathUtil.roundForObj(unitFee + unitEquipmentFee, decimal); // 费用汇总算出来的值 + 设备购置值
  1215. IDMapping[unitID] = {
  1216. engineeringCost: unitTotalFee,
  1217. buildingArea: '',
  1218. rate: '',
  1219. perCost: '',
  1220. }
  1221. })
  1222. /* let IDMapping = {};
  1223. //固定清单类别与汇总金额字段映射
  1224. let flagFieldMapping = {};
  1225. flagFieldMapping[fixedFlag.ENGINEERINGCOST] = 'engineeringCost';
  1226. flagFieldMapping[fixedFlag.SUB_ENGINERRING] = 'subEngineering';
  1227. flagFieldMapping[fixedFlag.MEASURE] = 'measure';
  1228. flagFieldMapping[fixedFlag.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  1229. flagFieldMapping[fixedFlag.OTHER] = 'other';
  1230. flagFieldMapping[fixedFlag.CHARGE] = 'charge';
  1231. flagFieldMapping[fixedFlag.TAX] = 'tax';
  1232. let tenderIDs = [];
  1233. if(tenders.length > 0){
  1234. for(let tender of tenders){
  1235. tenderIDs.push(tender.ID);
  1236. IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  1237. IDMapping[tender.ID]['buildingArea'] = '';
  1238. }
  1239. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
  1240. let needFlags = [fixedFlag.ENGINEERINGCOST, fixedFlag.SUB_ENGINERRING, fixedFlag.MEASURE,
  1241. fixedFlag.SAFETY_CONSTRUCTION, fixedFlag.CHARGE, fixedFlag.OTHER, fixedFlag.TAX];
  1242. //获取单位工程汇总金额需要用到的所有清单
  1243. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: notDeleted},
  1244. '-_id projectID fees flags');
  1245. //进行单位工程级别的汇总
  1246. for(let bills of allBills){
  1247. let billsFlag = bills.flags[0]['flag'];
  1248. let costField = flagFieldMapping[billsFlag];
  1249. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  1250. //暂估合价(工程造价暂估合价)
  1251. if (billsFlag === fixedFlag.ENGINEERINGCOST){
  1252. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  1253. }
  1254. }
  1255. //占造价比例、单方造价
  1256. for(let tender of tenders){
  1257. let tenderInfo = IDMapping[tender.ID];
  1258. tenderInfo.rate = '';
  1259. //单方造价
  1260. tenderInfo.perCost = '';
  1261. }
  1262. } */
  1263. return IDMapping;
  1264. }
  1265. const defaultSummaryField = {
  1266. [fixedFlag.ENGINEERINGCOST]: {
  1267. items: [
  1268. { name: 'engineeringCost', feeName: 'common' },
  1269. { name: 'estimate', feeName: 'estimate' }
  1270. ]
  1271. },
  1272. /* [fixedFlag.SUB_ENGINERRING]: {
  1273. items: [{ name: 'subEngineering', feeName: 'common' }]
  1274. },
  1275. [fixedFlag.MEASURE]: {
  1276. items: [{ name: 'measure', feeName: 'common' }]
  1277. },
  1278. [fixedFlag.SAFETY_CONSTRUCTION]: {
  1279. items: [{ name: 'safetyConstruction', feeName: 'common' }]
  1280. },
  1281. [fixedFlag.OTHER]: {
  1282. items: [{ name: 'other', feeName: 'common' }]
  1283. },
  1284. [fixedFlag.CHARGE]: {
  1285. items: [{ name: 'charge', feeName: 'common' }]
  1286. },
  1287. [fixedFlag.TAX]: {
  1288. items: [{ name: 'tax', feeName: 'common' }]
  1289. } */
  1290. };
  1291. // 项目管理界面需要显示的汇总字段
  1292. function setupSummaryFields(summaryInfo, projects, fields = null) {
  1293. if (!fields) {
  1294. fields = [
  1295. 'engineeringCost',
  1296. /* 'subEngineering',
  1297. 'measure',
  1298. 'safetyConstruction',
  1299. 'other',
  1300. 'charge',
  1301. 'tax', */
  1302. 'rate',
  1303. 'buildingArea',
  1304. 'perCost'
  1305. ];
  1306. }
  1307. for(const proj of projects){
  1308. const summaryProj = summaryInfo[proj.ID];
  1309. if(summaryProj){
  1310. for (const field of fields) {
  1311. proj[field] = summaryProj[field];
  1312. }
  1313. }
  1314. }
  1315. }
  1316. async function getSummaryInfo(projectIDs, summaryField = defaultSummaryField){
  1317. function initFees(target, summaryField) {
  1318. for (const flag in summaryField) {
  1319. const summaryItem = summaryField[flag];
  1320. summaryItem.items.forEach(item => {
  1321. target[item.name] = 0;
  1322. });
  1323. }
  1324. }
  1325. const summaryMap = await billFacade.getBudgetSummaryInfo(projectIDs);
  1326. //ID与汇总信息映射
  1327. let IDMapping = {};
  1328. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1329. //设置建设项目的总建筑面积
  1330. for(let project of projects){
  1331. let grossArea = '';
  1332. if(project.property && project.property.basicInformation){
  1333. for(let basicInfo of project.property.basicInformation){
  1334. if(basicInfo.key === 'basicInfo'){
  1335. for(let k of basicInfo.items){
  1336. if(k.key === 'grossArea'){
  1337. grossArea = k.value;
  1338. }
  1339. }
  1340. }
  1341. }
  1342. }
  1343. IDMapping[project.ID] = { engineeringCost: summaryMap[project.ID].totalFee || 0, rate: summaryMap[project.ID].rate || 0, buildingArea: grossArea, perCost: ''};
  1344. }
  1345. //单项工程
  1346. let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1347. let tenders = [];
  1348. let engIDs = [];
  1349. for(let eng of engineerings){
  1350. engIDs.push(eng.ID);
  1351. IDMapping[eng.ID] = {engineeringCost: summaryMap[eng.ID].totalFee || 0, rate: summaryMap[eng.ID].rate || 0, buildingArea: '', perCost: ''};
  1352. }
  1353. //单位工程
  1354. if(engIDs.length > 0){
  1355. tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1356. }
  1357. let tenderIDs = [];
  1358. if(tenders.length > 0){
  1359. for(let tender of tenders){
  1360. tenderIDs.push(tender.ID);
  1361. IDMapping[tender.ID] = {engineeringCost: summaryMap[tender.ID].totalFee || 0, rate: summaryMap[tender.ID].rate || 0,buildingArea: '', perCost: '', changeMark:tender.changeMark,property:tender.property};
  1362. let buildingArea = getBuildingArea(tender.property.projectFeature);
  1363. if(buildingArea){
  1364. IDMapping[tender.ID]['buildingArea'] = buildingArea;
  1365. }
  1366. }
  1367. //占造价比例、单方造价
  1368. const rateDecimal = -2;
  1369. const perCostDecimal = -2;
  1370. for(let tender of tenders){
  1371. let tenderInfo = IDMapping[tender.ID];
  1372. //单方造价
  1373. tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0
  1374. ? tenderInfo.buildingArea.toString().trim()
  1375. : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
  1376. }
  1377. //建设项目占造价比例及单方造价
  1378. for(let project of projects){
  1379. let projectInfo = IDMapping[project.ID];
  1380. projectInfo.rate = 100;
  1381. projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0
  1382. ? projectInfo.buildingArea.toString().trim()
  1383. : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
  1384. }
  1385. }
  1386. return IDMapping;
  1387. }
  1388. /* async function getSummaryInfo(projectIDs, feeFields = null, engineeringCostFields = null){
  1389. function initFees(obj, feeFields, engineeringCostFields) {
  1390. for (let data of feeFields) {
  1391. obj[data.v] = 0;
  1392. }
  1393. for (let data of engineeringCostFields) {
  1394. obj[data.k] = 0;
  1395. }
  1396. }
  1397. if (!feeFields) {
  1398. feeFields = [
  1399. {k: fixedFlag.ENGINEERINGCOST, v: 'engineeringCost'},
  1400. {k: fixedFlag.SUB_ENGINERRING, v: 'subEngineering'},
  1401. {k: fixedFlag.MEASURE, v: 'measure'},
  1402. {k: fixedFlag.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  1403. {k: fixedFlag.OTHER, v: 'other'},
  1404. {k: fixedFlag.CHARGE, v: 'charge'},
  1405. {k: fixedFlag.TAX, v: 'tax'}
  1406. ];
  1407. }
  1408. // 项目总造价的各个费用,k为汇总的字段,v为工程造价的费用字段
  1409. if (!engineeringCostFields) {
  1410. engineeringCostFields = [{ k: 'estimate', v: 'estimate' }];
  1411. }
  1412. //ID与汇总信息映射
  1413. let IDMapping = {};
  1414. //固定清单类别与汇总金额字段映射
  1415. let flagFieldMapping = {};
  1416. for (let data of feeFields) {
  1417. flagFieldMapping[data.k] = data.v;
  1418. }
  1419. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1420. //设置建设项目的总建筑面积
  1421. for(let project of projects){
  1422. let grossArea = '';
  1423. if(project.property && project.property.basicInformation){
  1424. for(let basicInfo of project.property.basicInformation){
  1425. if(basicInfo.key === 'basicInfo'){
  1426. for(let k of basicInfo.items){
  1427. if(k.key === 'grossArea'){
  1428. grossArea = k.value;
  1429. }
  1430. }
  1431. }
  1432. }
  1433. }
  1434. IDMapping[project.ID] = {rate: 0, buildingArea: grossArea, perCost: ''};
  1435. initFees(IDMapping[project.ID], feeFields, engineeringCostFields);
  1436. console.log(IDMapping[project.ID]);
  1437. }
  1438. //单项工程
  1439. let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1440. let tenders = [];
  1441. let engIDs = [];
  1442. for(let eng of engineerings){
  1443. engIDs.push(eng.ID);
  1444. IDMapping[eng.ID] = {rate: 0, buildingArea: '', perCost: ''};
  1445. initFees(IDMapping[eng.ID], feeFields, engineeringCostFields);
  1446. }
  1447. //单位工程
  1448. if(engIDs.length > 0){
  1449. tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1450. }
  1451. let tenderIDs = [];
  1452. if(tenders.length > 0){
  1453. for(let tender of tenders){
  1454. tenderIDs.push(tender.ID);
  1455. IDMapping[tender.ID] = {rate: 0, buildingArea: '', perCost: '', changeMark:tender.changeMark,property:tender.property};
  1456. initFees(IDMapping[tender.ID], feeFields, engineeringCostFields);
  1457. let buildingArea = getBuildingArea(tender.property.projectFeature);
  1458. if(buildingArea){
  1459. IDMapping[tender.ID]['buildingArea'] = buildingArea;
  1460. }
  1461. }
  1462. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金...
  1463. let needFlags = feeFields.map(data => data.k);
  1464. //获取单位工程汇总金额需要用到的所有清单
  1465. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
  1466. '-_id projectID fees flags');
  1467. //进行单位工程级别的汇总
  1468. for(let bills of allBills){
  1469. let billsFlag = bills.flags[0]['flag'];
  1470. let costField = flagFieldMapping[billsFlag];
  1471. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  1472. // 工程造价各费用
  1473. if (billsFlag === fixedFlag.ENGINEERINGCOST){
  1474. engineeringCostFields.forEach(({k, v}) => {
  1475. IDMapping[bills.projectID][k] = getTotalFee(bills, v);
  1476. });
  1477. }
  1478. }
  1479. let summaryFields = [...feeFields, ...engineeringCostFields].map(data => data.v);
  1480. //进行单项工程级别的汇总
  1481. for(let tender of tenders){
  1482. summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID], summaryFields);
  1483. }
  1484. //进行建设项目级别的汇总
  1485. for(let eng of engineerings){
  1486. summarizeToParent(IDMapping[eng.ParentID], IDMapping[eng.ID], summaryFields);
  1487. }
  1488. //占造价比例、单方造价
  1489. const rateDecimal = -2;
  1490. const perCostDecimal = -2;
  1491. for(let tender of tenders){
  1492. let tenderInfo = IDMapping[tender.ID];
  1493. let engInfo = IDMapping[tender.ParentID];
  1494. tenderInfo.rate = engInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(tenderInfo.engineeringCost * 100 / engInfo.engineeringCost, rateDecimal);
  1495. //单方造价
  1496. tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0
  1497. ? tenderInfo.buildingArea.toString().trim()
  1498. : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
  1499. }
  1500. for(let eng of engineerings){
  1501. let engInfo = IDMapping[eng.ID];
  1502. let projInfo = IDMapping[eng.ParentID];
  1503. engInfo.rate = !isDef(projInfo) || projInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(engInfo.engineeringCost * 100 / projInfo.engineeringCost, rateDecimal);
  1504. }
  1505. //建设项目占造价比例及单方造价
  1506. for(let project of projects){
  1507. let projectInfo = IDMapping[project.ID];
  1508. projectInfo.rate = 100;
  1509. projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0
  1510. ? projectInfo.buildingArea.toString().trim()
  1511. : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
  1512. }
  1513. }
  1514. return IDMapping;
  1515. } */
  1516. //根据项目ID获取所属建设项目
  1517. //@param {Number}projectID @return {Object}
  1518. async function getConstructionProject(projectID){
  1519. function returnProject(project){
  1520. if(!project || project.projType === projectType.folder){
  1521. return null;
  1522. }
  1523. if(project.projType === projectType.project){
  1524. return project;
  1525. }
  1526. }
  1527. let project = await projectModel.findOne({ID: projectID, $or: notDeleted});
  1528. let returnV = returnProject(project);
  1529. if(returnV !== undefined){
  1530. return returnV;
  1531. }
  1532. let parent = await projectModel.findOne({ID: project.ParentID, $or: notDeleted});
  1533. returnV = returnProject(parent);
  1534. if(returnV !== undefined){
  1535. return returnV;
  1536. }
  1537. let grandParent = await projectModel.findOne({ID: parent.ParentID, $or: notDeleted});
  1538. returnV = returnProject(grandParent);
  1539. return returnV !== undefined ? returnV : null;
  1540. }
  1541. //获取单位工程完整目录结构
  1542. //@param {Number}projectID @return {Arry}
  1543. async function getFullPath(projectID) {
  1544. let fullPath = [];
  1545. let project = await projectModel.findOne({ID: projectID, $or: notDeleted}, '-_id ParentID name');
  1546. if(project){
  1547. fullPath.push(project.name);
  1548. await getParent(project.ParentID);
  1549. }
  1550. fullPath = fullPath.reverse();
  1551. return fullPath;
  1552. async function getParent(ParentID) {
  1553. if(ParentID != -1){
  1554. let parent = await projectModel.findOne({ID: ParentID, $or: notDeleted}, '-_id ParentID name');
  1555. if(parent){
  1556. fullPath.push(parent.name);
  1557. await getParent(parent.ParentID);
  1558. }
  1559. }
  1560. }
  1561. }
  1562. //获取累进区间数据
  1563. async function getProgressiveInterval(libID) {
  1564. let lib = await progressiveModel.findOne({ID: libID});
  1565. return lib ? lib.data : [];
  1566. }
  1567. // 获取项目链上,自身、父项、爷爷项...的ID
  1568. async function getUpChainIDs(projectID) {
  1569. const rst = [];
  1570. while (projectID != -1) {
  1571. rst.push(projectID);
  1572. const project = await projectModel.findOne({ ID: projectID }, '-_id ParentID').lean();
  1573. projectID = project ? project.ParentID : -1;
  1574. }
  1575. return rst;
  1576. }
  1577. //获取projectIDs文件下所有子项目(默认不包括projectIDs本身)
  1578. async function getPosterityProjects(projectIDs, includeSelf = false, fields = '-_id') {
  1579. let rst = [];
  1580. if (includeSelf) {
  1581. const projects = await projectModel.find({ID: {$in: projectIDs}, $or: notDeleted}, fields).lean();
  1582. if (projects) {
  1583. rst.push(...projects);
  1584. }
  1585. }
  1586. async function getProjects(parentIDs) {
  1587. if (parentIDs.length > 0) {
  1588. let newIDs = [];
  1589. let projs = await projectModel.find({ParentID: {$in: parentIDs}, $or: notDeleted}, fields).lean();
  1590. for (let proj of projs) {
  1591. // 兼容旧的错误数据,可能ParentID和ID相同
  1592. if (parentIDs.includes(proj.ID)) {
  1593. continue;
  1594. }
  1595. rst.push(proj);
  1596. newIDs.push(proj.ID);
  1597. }
  1598. await getProjects(newIDs);
  1599. }
  1600. }
  1601. await getProjects(projectIDs);
  1602. return rst;
  1603. }
  1604. //根据项目获得分享信息(分享层级不一定在项目级)(以最新为准)
  1605. async function getShareInfo(userID, projectID) {
  1606. // 接受到的分享项目
  1607. const upChainIDs = await getUpChainIDs(projectID);
  1608. const shareList = await getShareList({receiver: userID, projectID: {$in: upChainIDs}});
  1609. // 返回最新的分享
  1610. //return shareList.sort((a, b) => Date.parse(b.shareDate) - Date.parse(a.shareDate))[0];
  1611. return shareList.sort((a, b) => Date.parse(b.updateDate) - Date.parse(a.updateDate))[0];
  1612. }
  1613. //打开的单位工程是否是被分享的.
  1614. async function isShare(userId, project){
  1615. //判断是否是打开分享的项目,属于分享文件的子项也算
  1616. while (project) {
  1617. for(let shareData of project.shareInfo){
  1618. if(shareData.userID === userId){
  1619. return true;
  1620. }
  1621. }
  1622. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  1623. }
  1624. return false;
  1625. }
  1626. //用户是否第一次进入费用定额
  1627. async function isFirst(userId, compilationId) {
  1628. let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(userId)}, '-_id used_list');
  1629. let first = false;
  1630. if (userData) {
  1631. first = !_.find(userData.used_list, function (o) {
  1632. return o.compilationId === compilationId;
  1633. });;
  1634. }
  1635. return first;
  1636. }
  1637. async function copyConstructionProject(data){
  1638. let log_data = {
  1639. key:data.key,
  1640. content: '正在复制建设项目,请稍候……',
  1641. userID:data.user_id,
  1642. compilationID: data.session.sessionCompilation._id,
  1643. status:"start",
  1644. create_time:+new Date()
  1645. };
  1646. await importLogsModel.create(log_data);
  1647. doCopy(data.user_id,data.session.sessionCompilation._id,data.projectID,data.newName,data.key);
  1648. return "start copy";
  1649. async function doCopy(user_id,compilationId,projectID,newName,key) {
  1650. let doc = {status:"finish"};
  1651. try {
  1652. let nameMap={};
  1653. nameMap[projectID] = newName
  1654. let r = await copyExample(user_id,compilationId,[projectID],nameMap);
  1655. if(r == false){
  1656. doc.errorMsg = "复制失败,请检查项目是否存在!";
  1657. doc.status = "error";
  1658. }
  1659. }catch (error){
  1660. console.log(error);
  1661. doc.errorMsg = "复制失败,请检查项目是否存在!";
  1662. doc.status = "error";
  1663. }finally {
  1664. await importLogsModel.update({key:key},doc);
  1665. }
  1666. }
  1667. }
  1668. async function importChongqingProject(data) {
  1669. let log_data = {
  1670. key:data.key,
  1671. content: '正在导入例题,请稍候……',
  1672. userID:data.user_id,
  1673. compilationID: data.session.sessionCompilation._id,
  1674. status:"start",
  1675. create_time:+new Date()
  1676. };
  1677. await importLogsModel.create(log_data);
  1678. doImport(data.user_id,data.session.sessionCompilation._id,data.session.sessionCompilation.adProjects,data.key);
  1679. return "start importing";
  1680. }
  1681. //加载例题
  1682. async function importExampleProject(data) {
  1683. let log_data = {
  1684. key:data.key,
  1685. content: '正在导入例题,请稍候……',
  1686. userID:data.user_id,
  1687. compilationID: data.session.sessionCompilation._id,
  1688. status:"start",
  1689. create_time:+new Date()
  1690. };
  1691. await importLogsModel.create(log_data);
  1692. doImport(data.user_id,data.session.sessionCompilation._id,data.session.sessionCompilation.example,data.key);
  1693. return "start importing";
  1694. }
  1695. async function doImport(user_id,compilationId,projectIDs,key) {
  1696. let doc = {status:"finish"};
  1697. try {
  1698. let r = await copyExample(user_id,compilationId,projectIDs);
  1699. if(r == false){
  1700. doc.errorMsg = "导入失败,请检查项目是否存在!";
  1701. doc.status = "error";
  1702. } else {
  1703. doc.projectID = r;
  1704. }
  1705. }catch (error){
  1706. console.log(error);
  1707. doc.errorMsg = "导入失败,请检查项目是否存在!";
  1708. doc.status = "error";
  1709. }finally {
  1710. await importLogsModel.update({key:key},doc);
  1711. }
  1712. }
  1713. //用户第一次进入费用定额的数据准备
  1714. async function prepareInitialData(userId, compilation, example) {
  1715. let first = await isFirst(userId, compilation);
  1716. if (first) {
  1717. await updateUsedList(userId, compilation);
  1718. const logData = {
  1719. key: uuidV1(),
  1720. content: '正在加载例题,请稍候……',
  1721. userID: userId,
  1722. compilationID: compilation,
  1723. status: 'start',
  1724. create_time: +new Date()
  1725. };
  1726. await importLogsModel.create(logData);
  1727. initData(logData.key, userId, compilation, example);
  1728. return 'start prepareInitialData';
  1729. }
  1730. async function initData(key, userId, compilation, example) {
  1731. const doc = { status: 'finish' };
  1732. try {
  1733. let prepareTask = [
  1734. copyCompleRationSection(userId, compilation),
  1735. copyCompleGljSection(userId, compilation)
  1736. ];
  1737. if (example && example.length > 0) {
  1738. prepareTask.push(copyExample(userId, compilation, example));
  1739. }
  1740. await Promise.all(prepareTask);
  1741. } catch (error) {
  1742. doc.errorMsg = '加载例题失败,请检查例题项目是否存在!';
  1743. doc.status = 'error';
  1744. } finally {
  1745. await importLogsModel.update({ key }, doc);
  1746. }
  1747. }
  1748. }
  1749. async function updateUsedList(userId, compilation) {
  1750. await userModel.update({_id: mongoose.Types.ObjectId(userId)}, {$push: {used_list: {compilationId: compilation}}});
  1751. }
  1752. //拷贝补充定额章节树
  1753. async function copyCompleRationSection(userId, compilationId) {
  1754. await sectionTreeDao.copyDataFromTemplate(userId, compilationId);
  1755. }
  1756. //拷贝补充人材机分类树
  1757. async function copyCompleGljSection(userId, compilationId) {
  1758. const srcCompilationID = '5b52b027fd3bb0000b257cf8';
  1759. // 如果已有数据则不再生成
  1760. const count = await compleGljSectionModel.count({userId, compilationId});
  1761. if (count) {
  1762. return;
  1763. }
  1764. let templateData = await compleGljSectionTModel.find({compilationId: srcCompilationID});
  1765. if (templateData.length > 0) {
  1766. let insertDatas = [],
  1767. uuidMapping = {};
  1768. //将ID替换成UUID
  1769. for (let temData of templateData) {
  1770. uuidMapping[temData.ID] = uuidV1();
  1771. }
  1772. for(let temData of templateData) {
  1773. let insertD = {
  1774. userId: userId,
  1775. compilationId: compilationId,
  1776. Name: temData.Name,
  1777. ID: uuidMapping[temData.ID],
  1778. ParentID: uuidMapping[temData.ParentID] || -1,
  1779. NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
  1780. };
  1781. insertDatas.push(insertD);
  1782. }
  1783. //插入数据
  1784. await compleGljSectionModel.insertMany(insertDatas);
  1785. }
  1786. }
  1787. async function changeFile(datas,userID,fileID,name,from,type){//from 费率或单价文件,type从单前建设项目还是从其它建设项目中复制
  1788. let projectIDs = [],newFile = {id:fileID,name:name};//计录从其它项目中复制的文件,选中多个的时候只需复制一次
  1789. let projectUpdateType = from == "feeRateFile"?"feeRate":"unitFile";
  1790. for(let d of datas){
  1791. let tem_file = from == "feeRateFile"? await feeRate_facade.changeFeeRateFile(d, newFile,type,userID):await glj_facade.changeUnitFile(d, newFile,type,userID);
  1792. if(type == 1 && tem_file){//从建设项目复制时,只有第一次需要复制,剩下的就相当于使用同个建设项目的情况了
  1793. let newID = from == "feeRateFile"?tem_file.ID:tem_file.id;
  1794. newFile = {id:newID,name:tem_file.name};
  1795. type = 0;
  1796. }
  1797. projectIDs.push({ID:d.projectID})
  1798. }
  1799. await project_facade.markProjectsToChange(projectIDs,projectUpdateType)//项目标记为待刷新状态
  1800. }
  1801. //获取费用定额绑定的基本信息库数据
  1802. async function getBasicInfo(compilationID, fileKind = null) {
  1803. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(compilationID)});
  1804. if (!compilation) {
  1805. return null;
  1806. }
  1807. let billValuation = compilation.bill_valuation.find(function (data) {
  1808. return data.enable;
  1809. });
  1810. if (!billValuation) {
  1811. return null;
  1812. }
  1813. let engineerings = await engineeringModel.find({valuationID: billValuation.id});
  1814. let engineering = engineerings.find(function (data) {
  1815. return data.info_lib && data.info_lib.length > 0;
  1816. });
  1817. if (!engineering || !engineering.info_lib || !engineering.info_lib[0]) {
  1818. return null;
  1819. }
  1820. let infoLib = await basicInfoModel.findOne({ID: engineering.info_lib[0].id});
  1821. //提取文件类型中需要的数据 (投标项目可能不需要招标的一些信息)
  1822. if (fileKind && infoLib && infoLib.info && infoLib.info.length) {
  1823. let strMap = {
  1824. 1: '投标', //投标
  1825. 2: '招标', //招标
  1826. 3: '控制价' //控制价
  1827. };
  1828. let needfulData = infoLib.info.filter(data => !data.fileKind || data.fileKind === strMap[fileKind]);
  1829. needfulData.forEach(nData => {
  1830. let needfulSub = nData.items.filter(sData => !sData.fileKind || sData.fileKind === strMap[fileKind]);
  1831. nData.items = needfulSub;
  1832. });
  1833. infoLib.info = needfulData;
  1834. }
  1835. return infoLib;
  1836. }
  1837. async function getProjectFeature(valuationID, engineeringName, feeName) {
  1838. let engineering = await engineeringModel.findOne({valuationID: valuationID, name: engineeringName, feeName: feeName});
  1839. if (!engineering || !engineering.feature_lib || !engineering.feature_lib[0]) {
  1840. return null;
  1841. }
  1842. let featureLib = await projectFeatureModel.findOne({ID: engineering.feature_lib[0].id});
  1843. return featureLib;
  1844. }
  1845. //根据单位工程,获取建设项目-单项工程-单位工程,不包含无单位工程的单项工程
  1846. //@param {Number}tenderID(单位工程ID) {Number}granularity(颗粒度 1:建设项目 2:单项工程 3:单位工程)
  1847. async function getProjectByGranularity(tenderID, granularity, summaryField, userID, versionName) {
  1848. const GRANULARITY = {
  1849. PROJECT: 1,
  1850. ENGINEERING: 2,
  1851. TENDER: 3
  1852. };
  1853. let theTender = await projectModel.findOne({userID: userID, ID: tenderID}).lean(); //加上session的userID,防止tenderID被篡改过
  1854. if (!theTender) {
  1855. return null;
  1856. }
  1857. let theEngineering = await projectModel.findOne({ID: theTender.ParentID}).lean();
  1858. if (!theEngineering) {
  1859. return null;
  1860. }
  1861. let constructionProject = await projectModel.findOne({ID: theEngineering.ParentID}).lean();
  1862. if (!constructionProject) {
  1863. return null;
  1864. }
  1865. let engineerings;
  1866. if (granularity === GRANULARITY.PROJECT) {
  1867. engineerings = await projectModel.find({ParentID: constructionProject.ID, $or: notDeleted}).lean();
  1868. for (let eng of engineerings) {
  1869. eng.children = await projectModel.find({ParentID: eng.ID, $or: notDeleted}).lean();
  1870. }
  1871. } else {
  1872. engineerings = [theEngineering];
  1873. if (granularity === GRANULARITY.ENGINEERING) {
  1874. theEngineering.children = await projectModel.find({ParentID: theEngineering.ID, $or: notDeleted}).lean();
  1875. } else {
  1876. theEngineering.children = [theTender];
  1877. }
  1878. }
  1879. constructionProject.children = engineerings;
  1880. //获取汇总信息
  1881. constructionProject.summaryInfo = await getSummaryInfo([constructionProject.ID], summaryField);
  1882. //获取编制软件信息: 软件公司;软件名;版本号;授权信息; base64
  1883. const systemSetting = await systemSettingModel.findOne({});
  1884. let company = systemSetting.company || '珠海纵横创新软件有限公司',
  1885. version = systemSetting.version || '';
  1886. constructionProject.softInfo = `${company};${versionName};${version};${userID}`;
  1887. return constructionProject;
  1888. }
  1889. //获取项目数据占位ID
  1890. async function getProjectPlaceholder(data) {
  1891. let rst = {};
  1892. //项目本身数据
  1893. if (data.projectCount) {
  1894. let projectCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, data.projectCount);
  1895. rst.project = projectCount.sequence_value - data.projectCount + 1;
  1896. }
  1897. //项目人材机数据
  1898. if (data.projectGLJCount) {
  1899. let projectGLJCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJCount);
  1900. rst.projectGLJ = projectGLJCount.sequence_value - data.projectGLJCount + 1;
  1901. }
  1902. //组成物数据
  1903. if (data.ratioCount) {
  1904. let ratioCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.mix_ratio, data.ratioCount);
  1905. rst.ratio = ratioCount.sequence_value - data.ratioCount + 1;
  1906. }
  1907. //单价文件数据
  1908. if (data.unitPriceFileCount) {
  1909. let unitPriceFileCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price_file, data.unitPriceFileCount);
  1910. rst.unitPriceFile = unitPriceFileCount.sequence_value - data.unitPriceFileCount + 1;
  1911. }
  1912. //单价数据
  1913. if (data.unitPriceCount) {
  1914. let unitPriceCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price, data.unitPriceCount);
  1915. rst.unitPrice = unitPriceCount.sequence_value - data.unitPriceCount + 1;
  1916. }
  1917. return rst;
  1918. }
  1919. /*
  1920. * 接口导入 项目详细数据都导入完成了,再生成项目数据(项目管理界面数据)
  1921. * */
  1922. async function importProject(importObj, userID, compilationID, overWriteUrl) {
  1923. let toInsertProjects = [importObj]; //待新增项目数据
  1924. let billsCalcMode = 0;
  1925. if (overWriteUrl) {
  1926. const overWrite = require('../../..' + overWriteUrl);
  1927. if(overWrite.getBillsCalcMode) { // 重写清单计费取费方式
  1928. billsCalcMode = overWrite.getBillsCalcMode();
  1929. }
  1930. }
  1931. await setupProject(importObj);
  1932. //设置项目ID及相关数据
  1933. for (let curEng of importObj.engs) {
  1934. await setupProject(curEng);
  1935. toInsertProjects.push(curEng);
  1936. for (let curTender of curEng.tenders) {
  1937. await setupProject(curTender.tender);
  1938. //插入单位工程的详细数据
  1939. await importTenderDetail(curTender);
  1940. toInsertProjects.push(curTender.tender);
  1941. }
  1942. delete curEng.tenders;
  1943. }
  1944. delete importObj.engs;
  1945. //项目内部数据设置、新增完毕后,插入项目本身的数据,更新前节点数据
  1946. let bulks = [];
  1947. //如果有前节点,更新前节点
  1948. if (importObj.preID !== -1) {
  1949. bulks.push({
  1950. updateOne: {filter: {ID: importObj.preID}, update: {$set: {NextSiblingID: importObj.ID}}}
  1951. });
  1952. }
  1953. for (let insertP of toInsertProjects) {
  1954. bulks.push({
  1955. insertOne: {document: insertP}
  1956. });
  1957. }
  1958. if (bulks.length > 0) {
  1959. await projectModel.bulkWrite(bulks);
  1960. }
  1961. return importObj.ID; // 返回建设项目ID
  1962. // TODO 删除
  1963. let summaryInfo = await getSummaryInfo([importObj.ID]);
  1964. //设置汇总字段
  1965. for(let proj of toInsertProjects){
  1966. let summaryProj = summaryInfo[proj.ID];
  1967. if(summaryProj){
  1968. proj.engineeringCost = summaryProj.engineeringCost;
  1969. proj.subEngineering = summaryProj.subEngineering;
  1970. proj.measure = summaryProj.measure;
  1971. proj.safetyConstruction = summaryProj.safetyConstruction;
  1972. proj.other = summaryProj.other;
  1973. proj.charge = summaryProj.charge;
  1974. proj.tax = summaryProj.tax;
  1975. proj.rate = summaryProj.rate;
  1976. proj.buildingArea = summaryProj.buildingArea;
  1977. proj.perCost = summaryProj.perCost;
  1978. }
  1979. }
  1980. return toInsertProjects;
  1981. //给项目数据设置一些需要的数据
  1982. async function setupProject(data) {
  1983. data.userID = userID;
  1984. data.compilation = compilationID;
  1985. data.fileVer = await index.getVersion();
  1986. data.createDateTime = new Date();
  1987. if (data.projType === 'Project') {
  1988. await setupConstruct(data);
  1989. } else if (data.projType === 'Tender') {
  1990. await setupTender(data);
  1991. }
  1992. }
  1993. //给建设项目设置一些数据
  1994. async function setupConstruct(data) {
  1995. //更新基本信息, 按照key匹配
  1996. let infoLib = await getBasicInfo(data.compilation, data.property.fileKind);
  1997. if (infoLib) {
  1998. //标准基本信息库的数据打平
  1999. let flatDatas = [];
  2000. infoLib.info.forEach(ifData => flatDatas.push(...ifData.items));
  2001. data.basicInformation.forEach(importI => {
  2002. flatDatas.forEach(item => {
  2003. if (item.key === 'engineeringName') {
  2004. item.value = data.name;
  2005. } else if (item.key === 'fileKind') {
  2006. item.value = {'1': '投标', '2': '招标'}[data.property.fileKind]
  2007. } else if (item.key === 'taxModel') {
  2008. item.value = {'1': '一般计税法', '2': '简易计税法'}[data.property.taxType]
  2009. }
  2010. if (item.key === importI.key) {
  2011. item.value = importI.value;
  2012. }
  2013. });
  2014. });
  2015. }
  2016. data.property.basicInformation = infoLib ? infoLib.info : [];
  2017. }
  2018. //给单位工程设置一些数据
  2019. async function setupTender(data) {
  2020. // 将项目标记为通过接口导入的项目
  2021. data.importedByInterface = true;
  2022. if (!data.property.decimal) {
  2023. //小数位数 需要修改,所以深拷贝
  2024. data.property.decimal = JSON.parse(JSON.stringify(defaultDecimal));
  2025. // 定额工程量、人材机消耗量精度设为最大6
  2026. data.property.decimal.ration.quantity = 6;
  2027. data.property.decimal.glj.quantity = 6;
  2028. }
  2029. //清单工程量精度 需要修改,所以深拷贝
  2030. data.property.billsQuantityDecimal = JSON.parse(JSON.stringify(billsQuantityDecimal));
  2031. // 清单工程量精度默认为4
  2032. const billsQuantityDecimalValue = data.property.billsQuantityDecimalValue || 4;
  2033. data.property.billsQuantityDecimal.forEach(data => data.decimal = billsQuantityDecimalValue);
  2034. //呈现选项
  2035. data.property.displaySetting = displaySetting;
  2036. data.property.billsCalcMode = billsCalcMode;
  2037. data.property.zanguCalcMode = 0;
  2038. //计算选项
  2039. data.property.calcOptions = calcOptions;
  2040. //安装增加费
  2041. if(data.property.isInstall === true || data.property.isInstall === 'true'){//判断是否安装工程
  2042. await installationFacade.copyInstallationFeeFromLib(data.ID, data.property.engineering_id);
  2043. }
  2044. //锁定清单
  2045. data.property.lockBills = true;
  2046. //工料机单价调整系数
  2047. data.property.tenderSetting = tenderSetting;
  2048. //工程特征相关更新 (配对更新+追加)
  2049. let featureLib = await getProjectFeature(data.property.valuation, data.property.engineeringName, data.property.feeStandardName);
  2050. if (featureLib) {
  2051. //把导入的数据设置到默认生成的数据中,按名称匹配 (导入项不确定,因此无法确定获取项的key)
  2052. // 只匹配第一层
  2053. const unmatched = [];
  2054. data.projectFeature.forEach(importF => {
  2055. let matchData = featureLib.feature.find(f => f.dispName === importF.dispName);
  2056. if (matchData) {
  2057. matchData.value = importF.value;
  2058. if (importF.items) {
  2059. matchData.items = importF.items;
  2060. }
  2061. } else {
  2062. unmatched.push(importF);
  2063. }
  2064. });
  2065. featureLib.feature.push(...unmatched);
  2066. featureLib.feature.forEach(f => {
  2067. //设置工程专业的值为费用标准的值..
  2068. if (f.key === 'engineering') {
  2069. f.value = data.property.feeStandardName;
  2070. } else if (f.key === 'projType' && !f.value) {
  2071. const options = f.options && f.options.split('@') || [];
  2072. f.value = options[0] || '';
  2073. }
  2074. });
  2075. }
  2076. data.property.projectFeature = featureLib ? featureLib.feature : [];
  2077. // 累进数据
  2078. if (data.property.progressiveLibID) {
  2079. data.property.progressiveInterval = await getProgressiveInterval(data.property.progressiveLibID);
  2080. }
  2081. // 指标信息相关设置
  2082. await project_facade.setSEILibData(data.property);
  2083. }
  2084. }
  2085. //插入单位工程内部详细数据
  2086. async function importTenderDetail(tenderData) {
  2087. //单价文件
  2088. let upFile = {
  2089. id: tenderData.tender.property.unitPriceFile.id,
  2090. name: tenderData.tender.name,
  2091. project_id: tenderData.tender.ID,
  2092. user_id: tenderData.tender.userID,
  2093. root_project_id: tenderData.tender.property.rootProjectID
  2094. };
  2095. await unitPriceFileModel.create(upFile);
  2096. //费率文件
  2097. let feeRateFileID = await feeRate_facade.newFeeRateFile(tenderData.tender.userID, tenderData.tender);
  2098. tenderData.tender.property.feeFile = feeRateFileID ? feeRateFileID : -1;
  2099. //人工系数文件
  2100. let lcFile = await labourCoeFacade.newProjectLabourCoe(tenderData.tender);
  2101. tenderData.tender.property.labourCoeFile = lcFile ? lcFile : null;
  2102. let cpFile = await calcProgramFacade.newProjectCalcProgramFile(tenderData.tender);
  2103. tenderData.tender.property.calcProgramFile = cpFile ? cpFile : null;
  2104. //列设置
  2105. let engineeringModel = new EngineeringLibModel();
  2106. let engineering = await engineeringModel.getEngineering(tenderData.tender.property.engineering_id);
  2107. let mainTreeCol = await mainColLibModel.findOne({ID: tenderData.tender.property.colLibID});
  2108. await projectSettingModel.create({projectID: tenderData.tender.ID, main_tree_col: mainTreeCol.main_tree_col, glj_col: engineering.glj_col});
  2109. //清单
  2110. if (tenderData.bills.length) {
  2111. await billsModel.insertMany(tenderData.bills);
  2112. }
  2113. // 工程量明细
  2114. if (tenderData.quantityDetails && tenderData.quantityDetails.length) {
  2115. await quantityDetailModel.insertMany(tenderData.quantityDetails);
  2116. }
  2117. if (enterDetail(tenderData)) {
  2118. //匹配标准数据,更新一些标准数据
  2119. await setupStdData(tenderData);
  2120. }
  2121. let task = [];
  2122. //定额
  2123. if (tenderData.ration.length) {
  2124. task.push(rationModel.insertMany(tenderData.ration))
  2125. }
  2126. //定额人材机
  2127. if (tenderData.rationGLJ.length) {
  2128. task.push(rationGLJModel.insertMany(tenderData.rationGLJ));
  2129. }
  2130. //定额调整系数
  2131. if (tenderData.rationCoe.length) {
  2132. task.push(rationCoeModel.insertMany(tenderData.rationCoe));
  2133. }
  2134. //项目人材机
  2135. if (tenderData.projectGLJ.length) {
  2136. task.push(gljListModel.insertMany(tenderData.projectGLJ));
  2137. }
  2138. // 承包人材料
  2139. if (tenderData.contractorList.length) {
  2140. task.push(contractorListModel.insertMany(tenderData.contractorList));
  2141. }
  2142. // 评标材料表
  2143. if (tenderData.bidEvaluationList.length) {
  2144. task.push(bidListModel.insertMany(tenderData.bidEvaluationList));
  2145. }
  2146. // 暂估价材料表
  2147. if (tenderData.evaluationList.length) {
  2148. task.push(evaluateListModel.insertMany(tenderData.evaluationList));
  2149. }
  2150. //组成物
  2151. if (tenderData.mixRatio.length) {
  2152. task.push(mixRatioModel.insertMany(tenderData.mixRatio));
  2153. }
  2154. //单价文件
  2155. if (tenderData.unitPrice.length) {
  2156. task.push(unitPriceModel.insertMany(tenderData.unitPrice));
  2157. }
  2158. if (task.length) {
  2159. await Promise.all(task);
  2160. }
  2161. //继续处理定额等数据
  2162. function enterDetail(tenderData) {
  2163. return tenderData.ration.length ||
  2164. tenderData.rationGLJ.length ||
  2165. tenderData.projectGLJ.length ||
  2166. tenderData.mixRatio.length ||
  2167. tenderData.unitPrice.length;
  2168. }
  2169. }
  2170. //匹配标准数据,需要匹配标准定额,更新导入的定额人材机的定额消耗量等数据
  2171. async function setupStdData(tenderData) {
  2172. //获取标准定额数据 (定额子目的编码查找)
  2173. let matchRationCodes = [...new Set(tenderData.ration.map(ration => ration.code))];
  2174. if (!matchRationCodes.length) {
  2175. return;
  2176. }
  2177. //限制在当前费用定额可用的定额库里查找
  2178. let stdRations = await stdRationItemModel.find({code: {$in: matchRationCodes}, rationRepId: {$in: tenderData.tender.rationLibIDs}},
  2179. '-_id -rationAssList -rationCoeList -rationInstList');
  2180. //标准定额code - 映射
  2181. let stdRationCodeMap = {};
  2182. stdRations.forEach(stdRation => stdRationCodeMap[stdRation.code] = stdRation);
  2183. //获取标准人材机数据 (人材机汇总的编码查找)
  2184. let matchGLJCodes = [...new Set(tenderData.projectGLJ.map(pGLJ => pGLJ.original_code))];
  2185. if (!matchGLJCodes.length) {
  2186. return;
  2187. }
  2188. //限制在当前费用定额可用的人材机库里查找
  2189. let stdGLJs = await stdGljItemModel.find({code: {$in: matchGLJCodes}, repositoryId: {$in: tenderData.tender.gljLibIDs}},
  2190. '-_id -component -priceProperty');
  2191. //标准人材机code - 映射
  2192. let stdGLJCodeMap = {};
  2193. stdGLJs.forEach(stdGLJ => stdGLJCodeMap[stdGLJ.code] = stdGLJ);
  2194. // 取费ID-计算程序子目映射
  2195. const programIDCalculationMap = {};
  2196. //更新定额数据
  2197. const toSetFakeProgramIDData = [];
  2198. tenderData.ration.forEach(r => {
  2199. if (r.setFakeProgramID) {
  2200. toSetFakeProgramIDData.push(r);
  2201. delete r.setFakeProgramID;
  2202. }
  2203. let stdRation = stdRationCodeMap[r.code];
  2204. if (stdRation) {
  2205. r.caption = stdRation.caption;
  2206. r.from = 'std';
  2207. r.libID = stdRation.rationRepId;
  2208. r.stdID = stdRation.ID;
  2209. r.prefix = stdRation.rationRepId == tenderData.tender.defaultRationLib ? '' : '借';
  2210. r.content = stdRation.jobContent;
  2211. r.manageFeeRate = stdRation.manageFeeRate;
  2212. if (stdRation.feeType) {
  2213. r.programID = stdRation.feeType;
  2214. } else {
  2215. // 是标准定额,但是该标准定额取费专业为空,取定额取费专业(后台配置项)
  2216. r.programID = tenderData.tender.property.engineering;
  2217. }
  2218. } else {
  2219. r.from = 'cpt';
  2220. r.prefix = '补';
  2221. }
  2222. if (r.calculationItems && r.calculationItems.length > 0 && !programIDCalculationMap[r.programID]) {
  2223. programIDCalculationMap[r.programID] = r.calculationItems;
  2224. }
  2225. delete r.calculationItems;
  2226. });
  2227. // 更新计算程序
  2228. const newTemplates = [];
  2229. const calcFileID = tenderData.tender.property.calcProgramFile.ID;
  2230. let calcProgramFile = null;
  2231. if (Object.keys(programIDCalculationMap).length > 0) {
  2232. calcProgramFile = await calcProgramsModel.findOne({ ID: calcFileID }).lean();
  2233. if (calcProgramFile) {
  2234. for (const template of calcProgramFile.templates) {
  2235. const matched = programIDCalculationMap[template.ID];
  2236. if (!matched) {
  2237. newTemplates.push(template);
  2238. continue;
  2239. }
  2240. for (const newCalcItem of matched) {
  2241. for (const oldCalcItem of template.calcItems) {
  2242. if (newCalcItem.fieldName === oldCalcItem.fieldName &&
  2243. !(newCalcItem.feeRate === 100 && !oldCalcItem.feeRateID && !oldCalcItem.feeRate)) {
  2244. oldCalcItem.feeRate = newCalcItem.feeRate;
  2245. oldCalcItem.feeRateID = null; // feeRateID优先级比较高,不赋为空的话为被覆盖
  2246. }
  2247. }
  2248. }
  2249. newTemplates.push(template);
  2250. }
  2251. }
  2252. }
  2253. // 增加假的计算程序
  2254. if (toSetFakeProgramIDData.length) {
  2255. if (!calcProgramFile) {
  2256. calcProgramFile = await calcProgramsModel.findOne({ ID: calcFileID }).lean();
  2257. }
  2258. if (calcProgramFile) {
  2259. const programIDTemplateMap = {};
  2260. const programIDNewTemplateMap = {};
  2261. calcProgramFile.templates.forEach(template => programIDTemplateMap[template.ID] = template);
  2262. let curID = calcProgramFile.templates.length + 1;
  2263. toSetFakeProgramIDData.forEach(r => {
  2264. const matchedNewTempate = programIDNewTemplateMap[r.programID];
  2265. if (matchedNewTempate) {
  2266. r.programID = matchedNewTempate.ID;
  2267. return;
  2268. }
  2269. const matched = programIDTemplateMap[r.programID];
  2270. if (matched) {
  2271. const newData = {
  2272. ID: curID++,
  2273. name: `${matched.name}_1`,
  2274. calcItems: []
  2275. };
  2276. newTemplates.push(newData);
  2277. programIDNewTemplateMap[r.programID] = newData;
  2278. r.programID = newData.ID;
  2279. }
  2280. });
  2281. }
  2282. }
  2283. if (newTemplates.length) {
  2284. await calcProgramsModel.update({ ID: calcFileID }, { $set: { templates: newTemplates } });
  2285. }
  2286. //更新定额人材机数据
  2287. tenderData.rationGLJ.forEach(rGLJ => {
  2288. rGLJ.from = 'cpt';
  2289. //匹配定额
  2290. let stdRation = stdRationCodeMap[rGLJ.rationCode];
  2291. if (stdRation) {
  2292. //根据导入数据的定额人材机编码匹配人材机
  2293. let stdGLJ = stdGLJCodeMap[rGLJ.original_code];
  2294. if (stdGLJ) {
  2295. rGLJ.from = 'std';
  2296. rGLJ.GLJID = stdGLJ.ID;
  2297. rGLJ.type = stdGLJ.gljType;
  2298. rGLJ.shortName = stdGLJ.shortName;
  2299. rGLJ.repositoryId = stdGLJ.repositoryId;
  2300. rGLJ.model = stdGLJ.model;
  2301. rGLJ.adjCoe = stdGLJ.adjCoe;
  2302. //找匹配到的标准定额中定额人材机的相应人材机,更新定额消耗
  2303. let stdRationGLJ = stdRation.rationGljList.find(data => data.gljId === stdGLJ.ID);
  2304. if (stdRationGLJ) {
  2305. rGLJ.rationItemQuantity = stdRationGLJ.consumeAmt;
  2306. }
  2307. }
  2308. }
  2309. });
  2310. //更新人材机汇总数据
  2311. tenderData.projectGLJ.forEach(pGLJ => {
  2312. if (!pGLJ.specs) {
  2313. pGLJ.specs = null;
  2314. }
  2315. let stdGLJ = stdGLJCodeMap[pGLJ.original_code];
  2316. if (stdGLJ) {
  2317. pGLJ.glj_id = stdGLJ.ID;
  2318. pGLJ.model = stdGLJ.model;
  2319. if (pGLJ.type !== stdGLJ.gljType) { //更新组成物connect_key
  2320. let keyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', pGLJ.type].join('|-|');
  2321. let ratios = tenderData.mixRatio.filter(ratio =>
  2322. ratio.connect_key === keyStr);
  2323. let newKeyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', stdGLJ.gljType || 'null'].join('|-|');
  2324. ratios.forEach(ratio => ratio.connect_key = newKeyStr);
  2325. }
  2326. pGLJ.type = stdGLJ.gljType; //更新类型,标准的数据类型更准确,导入的类型数据有细分识别不了
  2327. }
  2328. });
  2329. //更新单价文件数据
  2330. tenderData.unitPrice.forEach(up => {
  2331. let stdGLJ = stdGLJCodeMap[up.original_code];
  2332. if (stdGLJ) {
  2333. up.glj_id = stdGLJ.ID;
  2334. up.type = stdGLJ.gljType;
  2335. up.short_name = stdGLJ.shortName;
  2336. if (stdGLJ.taxRate) {
  2337. up.taxRate = stdGLJ.taxRate;
  2338. }
  2339. }
  2340. });
  2341. //更新组成物数据
  2342. tenderData.mixRatio.forEach(ratio => {
  2343. let stdGLJ = stdGLJCodeMap[ratio.code] || stdGLJCodeMap[ratio.original_code];
  2344. if (stdGLJ) {
  2345. ratio.glj_id = stdGLJ.ID;
  2346. ratio.type = stdGLJ.gljType;
  2347. }
  2348. });
  2349. }
  2350. async function exportProject(userID,data){//导出建设项目
  2351. if(data.type == 'main'){
  2352. return await exportMainData(userID,data.projectID);
  2353. }else {
  2354. return await exportTenderData(data);
  2355. }
  2356. }
  2357. async function exportMainData(userID,projectID) {
  2358. let result = {userID:userID,projects:[],type:'Project'};//type 备用属性,表示导出的类型,目前导出的都是整个建设项目
  2359. let tenderIDs = [];
  2360. let project = await projectModel.findOne({ID:projectID});
  2361. if(!project) throw new Error("没有找到该建设项目:"+projectID);
  2362. result['compilationID'] = project.compilation;
  2363. result['from'] = "construction";
  2364. result.projects.push(project);
  2365. tenderIDs.push(project.ID);
  2366. let subProjects = await projectModel.find({"$or": [{'ParentID':projectID}, {"property.rootProjectID": projectID}]});
  2367. for(let s of subProjects){
  2368. if(!s.deleteInfo || !s.deleteInfo.deleted){
  2369. result.projects.push(s);
  2370. if(s.projType =="Tender") tenderIDs.push(s.ID);
  2371. }
  2372. }
  2373. const constructions = result.projects.filter(item => item.projType === projectType.project);
  2374. resortImportProjectData(result.projects, constructions);
  2375. let files = {unitFiles:await exportUnitFiles(projectID),feeRateFiles:await exportFeeRateFiles(projectID)};
  2376. result.files = files;
  2377. result = cipher.aesEncrypt(JSON.stringify(result));
  2378. result +="|----|" +JSON.stringify(tenderIDs);
  2379. return result;
  2380. }
  2381. async function exportUnitFiles(rootProjectID){
  2382. let unitFiles = [];
  2383. let files = await unitPriceFileModel.find({root_project_id:rootProjectID});
  2384. for(let f of files){
  2385. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  2386. let tem = {unitFile:f};
  2387. tem.unitPrices = await unitPriceModel.find({unit_price_file_id:f.id});
  2388. tem.mixRatios = await mixRatioModel.find({unit_price_file_id:f.id});
  2389. unitFiles.push(tem);
  2390. }
  2391. return unitFiles;
  2392. }
  2393. async function exportFeeRateFiles(rootProjectID) {
  2394. let feeRateFiles = [];
  2395. let files = await feeRateFileModel.find({rootProjectID:rootProjectID});
  2396. for(let f of files){
  2397. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  2398. let tem = {feeRateFile:f};
  2399. tem.feeRate = await feeRateModel.findOne({ID:f.feeRateID});
  2400. feeRateFiles.push(tem);
  2401. }
  2402. return feeRateFiles;
  2403. }
  2404. async function exportTenderData(data){
  2405. let result = {};
  2406. let projectSetting = await projectSettingModel.findOne({"projectID": data.projectID}, '-_id');
  2407. if(projectSetting) result['projSetting'] = projectSetting;
  2408. result.projectID = data.projectID;
  2409. result.bills = await billsModel.find({"projectID": data.projectID});
  2410. result.rations = await rationModel.find({'$or': [{projectID: data.projectID, deleteInfo: null}, {projectID: data.projectID, 'deleteInfo.deleted': {$in: [null, false]}}]});
  2411. result.projectGLJs = await gljListModel.find({'project_id':data.projectID});
  2412. result.installationFees = await installationFeeModel.find({projectID:data.projectID});
  2413. result.rationGLJs = await rationGLJModel.find({projectID:data.projectID});
  2414. result.rationCoes = await rationCoeModel.find({projectID:data.projectID});
  2415. result.quantityDetails = await quantityDetailModel.find({projectID:data.projectID});
  2416. result.rationInstallations = await rationInstallationModel.find({projectID:data.projectID});
  2417. result.rationTemplates = await rationTemplateModel.find({projectID:data.projectID});
  2418. result.calcProgramsFile = await calcProgramsModel.findOne({projectID:data.projectID});
  2419. result.labourCoes = await labourCoesModel.findOne({projectID:data.projectID});
  2420. result.evaluateList = await evaluateListModel.find({projectID:data.projectID}, '-_id').lean();
  2421. result.bidList = await bidListModel.find({projectID:data.projectID}, '-_id').lean();
  2422. result.contractorList = await contractorListModel.find({projectID:data.projectID}, '-_id').lean();
  2423. result.equipments = await equipmentPurchaseModel.findOne({projectID:data.projectID},'-_id').lean();
  2424. result.gatherFees = await gaterFeeModel.findOne({projectID:data.projectID},'-_id').lean();
  2425. return cipher.aesEncrypt(JSON.stringify(result));
  2426. }
  2427. async function downLoadProjectFile(info) {
  2428. let result = {error:0};
  2429. let bucketManager2 = new qiniu.rs.BucketManager(mac, null);
  2430. let publicBucketDomain = qiniu_config.Domain;// "http://serverupdate.smartcost.com.cn";//这里不支持https
  2431. let deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
  2432. let privateDownloadUrl = bucketManager2.privateDownloadUrl(publicBucketDomain, info.key, deadline);
  2433. console.log(privateDownloadUrl);
  2434. let data = {
  2435. key:info.key,
  2436. content: '正在导入建设项目,请稍候……',
  2437. userID:info.session.sessionUser.id,
  2438. compilationID: info.session.sessionCompilation._id,
  2439. status:"start",
  2440. create_time:+new Date()
  2441. };
  2442. await importLogsModel.create(data);
  2443. doDownLoadAndImport(privateDownloadUrl,info);
  2444. return result;
  2445. }
  2446. async function doDownLoadAndImport(privateDownloadUrl, info) {
  2447. let stream = fs.createWriteStream(path.join(__dirname, "../../../tmp/" + info.key));//
  2448. request(privateDownloadUrl)
  2449. .on('error', async function(err) {
  2450. await importLogsModel.update({ key: info.key }, { status: 'error', errorMsg: err.toString() });
  2451. })
  2452. .pipe(stream)
  2453. .on("close", async function () {
  2454. console.log("文件[" + info.key + "]下载完毕");
  2455. let doc = { status: "finish" };
  2456. try {
  2457. let data = fs.readFileSync(stream.path, 'utf-8');
  2458. let result = await importProjects(data, { session: info.session }, info.updateData);
  2459. if (result.error == 1) {
  2460. doc.errorMsg = result.msg;
  2461. doc.status = "error";
  2462. } else {
  2463. doc.projectID = [result.constructionProjectID];
  2464. }
  2465. } catch (error) {
  2466. console.log(error.message);
  2467. doc.errorMsg = "导入失败,请检查文件!";
  2468. doc.status = "error";
  2469. } finally {
  2470. await importLogsModel.update({ key: info.key }, doc);
  2471. fs.unlinkSync(stream.path);
  2472. }
  2473. })
  2474. .on('error', async function () {
  2475. await importLogsModel.update({ key: info.key }, { status: 'error', errorMsg: `文件[${info.key}]下载失败,请稍后再试。` });
  2476. });
  2477. }
  2478. async function importProcessChecking(data){
  2479. let result = {error:0};
  2480. const query = data.key ? { key: data.key } : { userID: data.userID, compilationID: data.compilationID };
  2481. let log = await importLogsModel.findOne(query);
  2482. if(log){
  2483. if(log.status == "finish"){
  2484. result.status = "complete";
  2485. await importLogsModel.remove(query);
  2486. // 获取导入的项目数据
  2487. if (log.projectID && log.projectID.length > 0) {
  2488. const projects = await getPosterityProjects(log.projectID, true);
  2489. if (!(projects.length === 1 && projects[0].projType === projectType.tender)) { // 处理的是建设项目数据
  2490. const summaryInfo = await getSummaryInfo(log.projectID);
  2491. setupSummaryFields(summaryInfo, projects);
  2492. }
  2493. result.data = projects;
  2494. }
  2495. /* if (log.projectID && log.projectID.length > 0) {
  2496. const projects = await getPosterityProjects([log.projectID], true);
  2497. if (!(projects.length === 1 && projects[0].projType === projectType.tender)) { // 处理的是建设项目数据
  2498. const summaryInfo = await getSummaryInfo([log.projectID]);
  2499. setupSummaryFields(summaryInfo, projects);
  2500. }
  2501. result.data = projects;
  2502. } */
  2503. }else if(log.status == "start"){
  2504. result.status = "processing";
  2505. result.content = log.content;
  2506. }else if(log.status == "error"){
  2507. result.error = 1;
  2508. result.msg = log.errorMsg;
  2509. await importLogsModel.remove(query);
  2510. }
  2511. }else {
  2512. result.status = "complete";
  2513. }
  2514. return result;
  2515. }
  2516. // 从cdn服务器下载文件,key就是文件名
  2517. async function downloadFileSync(key) {
  2518. const filePath = path.join(__dirname, '../../../tmp/', key);
  2519. const bucketManager2 = new qiniu.rs.BucketManager(mac, null);
  2520. const publicBucketDomain = qiniu_config.Domain; // "http://serverupdate.smartcost.com.cn";//这里不支持https
  2521. const deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
  2522. const privateDownloadUrl = bucketManager2.privateDownloadUrl(publicBucketDomain, key, deadline);
  2523. const stream = fs.createWriteStream(filePath);
  2524. return new Promise((resolve, reject) => {
  2525. request(privateDownloadUrl)
  2526. .on('error', reject)
  2527. .pipe(stream)
  2528. .on('close', () => {
  2529. // 读取文件返回字符串
  2530. const srcData = fs.readFileSync(stream.path,'utf-8');
  2531. resolve({
  2532. path: stream.path,
  2533. srcData: srcData
  2534. });
  2535. })
  2536. .on('error', reject);
  2537. });
  2538. }
  2539. // 导入接口
  2540. async function importInterface(key, session) {
  2541. const logData = {
  2542. key: key,
  2543. content: '正在导入接口文件,请稍候……',
  2544. userID: session.sessionUser.id,
  2545. compilationID: session.sessionCompilation._id,
  2546. status: 'start',
  2547. create_time: +new Date()
  2548. };
  2549. await importLogsModel.create(logData);
  2550. handleImportInterface(key, session);
  2551. return 'importing interface';
  2552. }
  2553. async function handleImportInterface(key, session) {
  2554. const doc = { status: 'finish' };
  2555. // 源文件内容文本
  2556. let downloadFilePath = '';
  2557. try {
  2558. const { path, srcData } = await downloadFileSync(key);
  2559. downloadFilePath = path;
  2560. if (!srcData) {
  2561. throw '无有效数据';
  2562. }
  2563. const userID = session.sessionUser.id;
  2564. const compilationID = session.sessionCompilation._id;
  2565. const importData = JSON.parse(srcData);
  2566. let tenderCount = 0;
  2567. importData.engs.forEach(eng => {
  2568. eng.tenders.forEach(() => {
  2569. tenderCount += 1;
  2570. });
  2571. });
  2572. if (await isTenderOverrun(tenderCount, session)) {
  2573. throw '您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。';
  2574. }
  2575. const overWriteUrl = session.sessionCompilation.overWriteUrl;
  2576. const projectID = await importProject(importData, userID, compilationID, overWriteUrl);
  2577. doc.projectID = [projectID];
  2578. } catch (err) {
  2579. doc.errorMsg = typeof err === 'string' ? err : err.toString();
  2580. doc.status = 'error';
  2581. } finally {
  2582. await importLogsModel.update({ key }, doc);
  2583. fs.unlinkSync(downloadFilePath);
  2584. }
  2585. }
  2586. /* async function importInterface(key, session) {
  2587. // 源文件内容文本
  2588. let downloadFilePath = '';
  2589. try {
  2590. const { path, srcData } = await downloadFileSync(key);
  2591. downloadFilePath = path;
  2592. if (!srcData) {
  2593. throw '无有效数据';
  2594. }
  2595. const userID = session.sessionUser.id;
  2596. const compilationID = session.sessionCompilation._id;
  2597. const importData = JSON.parse(srcData);
  2598. let tenderCount = 0;
  2599. importData.engs.forEach(eng => {
  2600. eng.tenders.forEach(tender => {
  2601. tenderCount += 1;
  2602. });
  2603. });
  2604. if (await isTenderOverrun(tenderCount, session)) {
  2605. throw '您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。';
  2606. }
  2607. const projectData = await importProject(importData, userID, compilationID);
  2608. return projectData;
  2609. } catch (err) {
  2610. throw err;
  2611. } finally {
  2612. fs.unlinkSync(downloadFilePath);
  2613. }
  2614. } */
  2615. // 为防止导入的ybp源文件的树结构是错误的,进行重排
  2616. function resortImportProjectData(allData, curDepthData) {
  2617. curDepthData = project_facade.sortChildren(curDepthData);
  2618. curDepthData.forEach((cur, index) => {
  2619. cur.NextSiblingID = curDepthData[index + 1] && curDepthData[index + 1].ID || -1;
  2620. const nextDepthData = allData.filter(item => item.ParentID === cur.ID);
  2621. if (nextDepthData.length) {
  2622. resortImportProjectData(allData, nextDepthData);
  2623. }
  2624. });
  2625. }
  2626. async function importProjects(data,req,updateData) {
  2627. let result = {error:0};
  2628. let stringArr = data.split("|----|");
  2629. let datas = [];
  2630. let first = +new Date();
  2631. for(let s of stringArr){
  2632. datas.push(JSON.parse(cipher.aesDecrypt(s)));
  2633. }
  2634. let mainData = datas.length > 0 ?datas[0]:null;
  2635. if(mainData){
  2636. if(mainData.from && mainData.from != "construction"){
  2637. result.error = 1;
  2638. result.msg = "导入失败:您要导入的文件是由“纵横公路养护云版”导出,当前软件是“大司空云计价”,请选择正确的软件再进行操作!";
  2639. }else if(mainData.compilationID != req.session.sessionCompilation._id){
  2640. const fileCompilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(mainData.compilationID)}, 'name');
  2641. const fileCompilationName = fileCompilation ? fileCompilation.name : '未知的费用定额';
  2642. const curCompilationName = req.session.sessionCompilation.name;
  2643. result.error = 1;
  2644. result.msg = `导入失败:您要导入的文件是由“${fileCompilationName}”导出,当前软件是“${curCompilationName}”,请选择正确的费用定额再进行操作!`;
  2645. }else {
  2646. const tenders = mainData.projects.filter(item => item.projType === projectType.tender);
  2647. const tenderOverrun = await isTenderOverrun(tenders.length, req.session);
  2648. if (tenderOverrun) {
  2649. result.error = 1;
  2650. result.msg = `您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。`;
  2651. return result;
  2652. }
  2653. const constructions = mainData.projects.filter(item => item.projType === projectType.project);
  2654. resortImportProjectData(mainData.projects, constructions);
  2655. let [constructionProjectID,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap] = await handleMainProjectDatas(mainData,updateData,req.session.sessionUser.id);
  2656. result.constructionProjectID = constructionProjectID;
  2657. if(datas.length > 1 ){
  2658. let newProjectSettings=[],bills=[],rations=[],installationFees=[],projectGLJs=[],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[],evaluateList=[],bidList=[],contractorList=[],newCalcProgramsFiles=[],newLabourCoes=[],newEquipments = [],newGatherFees = [];
  2659. for(let i = 1;i<datas.length;i++){
  2660. let [tnewProjectSetting,tbills,trations,tinstallationFees,tprojectGLJs,trationGLJs,trationCoes,tquantityDetails,trationInstallations,trationTemplates,tevaluateList,tbidList,tcontractorList,tnewCalcProgramsFile,tnewLabourCoe,tnewEquipments, tnewGatherFees] = await handleEachProject(datas[i],projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap)
  2661. if(tnewProjectSetting) newProjectSettings.push(tnewProjectSetting);
  2662. if(tbills.length > 0) bills = bills.concat(tbills);
  2663. if(trations.length > 0) rations = rations.concat(trations);
  2664. if(tinstallationFees.length > 0) installationFees = installationFees.concat(tinstallationFees);
  2665. if(tprojectGLJs.length > 0) projectGLJs = projectGLJs.concat(tprojectGLJs);
  2666. if(trationGLJs.length > 0) rationGLJs = rationGLJs.concat(trationGLJs);
  2667. if(trationCoes.length > 0) rationCoes = rationCoes.concat(trationCoes);
  2668. if(tquantityDetails.length > 0) quantityDetails = quantityDetails.concat(tquantityDetails);
  2669. if(trationInstallations.length > 0) rationInstallations = rationInstallations.concat(trationInstallations);
  2670. if(trationTemplates.length > 0) rationTemplates = rationTemplates.concat(trationTemplates);
  2671. if(tevaluateList.length > 0) evaluateList = evaluateList.concat(tevaluateList);
  2672. if(tbidList.length > 0) bidList = bidList.concat(tbidList);
  2673. if(tcontractorList.length > 0) contractorList = contractorList.concat(tcontractorList);
  2674. if(tnewCalcProgramsFile) newCalcProgramsFiles.push(tnewCalcProgramsFile);
  2675. if(tnewLabourCoe) newLabourCoes.push(tnewLabourCoe);
  2676. if(tnewEquipments) newEquipments.push(tnewEquipments);
  2677. if(tnewGatherFees) newGatherFees.push(tnewGatherFees);
  2678. }
  2679. if(newProjectSettings.length > 0) await insertMany(newProjectSettings,projectSettingModel)
  2680. if(bills.length > 0) await insertMany(bills,billsModel);
  2681. if(rations.length > 0) await insertMany(rations,rationModel);
  2682. if(installationFees.length > 0) await insertMany(installationFees,installationFeeModel);
  2683. if(projectGLJs.length > 0) await insertMany(projectGLJs,gljListModel);
  2684. if(rationGLJs.length > 0) await insertMany(rationGLJs,rationGLJModel);
  2685. if(rationCoes.length > 0) await insertMany(rationCoes,rationCoeModel);
  2686. if(quantityDetails.length > 0) await insertMany(quantityDetails,quantityDetailModel);
  2687. if(rationInstallations.length > 0) await insertMany(rationInstallations,rationInstallationModel);
  2688. if(rationTemplates.length > 0) await insertMany(rationTemplates,rationTemplateModel);
  2689. if(evaluateList.length > 0) await insertMany(evaluateList,evaluateListModel);
  2690. if(bidList.length > 0) await insertMany(bidList,bidListModel);
  2691. if(contractorList.length > 0) await insertMany(contractorList,contractorListModel);
  2692. if(newCalcProgramsFiles.length > 0) await insertMany(newCalcProgramsFiles,calcProgramsModel);
  2693. if(newLabourCoes.length > 0) await insertMany(newLabourCoes,labourCoesModel);
  2694. if(newEquipments.length > 0) await insertMany(newEquipments,equipmentPurchaseModel);
  2695. if(newGatherFees.length > 0) await insertMany(newGatherFees,gaterFeeModel);
  2696. }
  2697. }
  2698. }
  2699. let finish = +new Date();
  2700. console.log("导入操作总时间为-------------------------------"+(finish-first));
  2701. return result;
  2702. }
  2703. async function handleEachProject(data,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap){
  2704. let bills = [],rations = [],projectGLJs = [],installationFees=[],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[],evaluateList=[],bidList=[],contractorList=[];
  2705. let newProjectSetting =null,newCalcProgramsFile = null,newLabourCoe = null,newEquipments = null, newGatherFees = null;
  2706. let billsIDMap = {},projectGLJIDMap={},rationIDMap = {};
  2707. let newProjectID = projectIDMap[data.projectID];
  2708. //生成安装增加费设置
  2709. if(data.installationFees && data.installationFees.length > 0){
  2710. for(let ins of data.installationFees){
  2711. delete ins._id;
  2712. ins.ID = uuidV1();
  2713. ins.projectID = newProjectID;
  2714. installationFees.push(ins);
  2715. }
  2716. }
  2717. //生成新的清单;
  2718. if(data.bills && data.bills.length > 0){
  2719. for(let b of data.bills){
  2720. billsIDMap[b.ID] = uuidV1();
  2721. }
  2722. for(let b of data.bills){
  2723. delete b._id;
  2724. b = getCopyBillDatas(b,newProjectID,billsIDMap);
  2725. bills.push(b);
  2726. }
  2727. }
  2728. //生成项目工料机数据
  2729. if(data.projectGLJs && data.projectGLJs.length > 0){
  2730. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJs.length);
  2731. for(let i = 0; i < data.projectGLJs.length; i++){
  2732. let d = data.projectGLJs[i];
  2733. delete d._id;
  2734. let newID = gljCount.sequence_value - (data.projectGLJs.length - 1) + i;
  2735. projectGLJIDMap[d.id] = newID;
  2736. d.project_id = newProjectID;
  2737. d.id = newID;
  2738. projectGLJs.push(d);
  2739. }
  2740. }
  2741. //生成新的定额
  2742. if(data.rations && data.rations.length > 0){
  2743. for(let r of data.rations){
  2744. rationIDMap[r.ID] = uuidV1();
  2745. }
  2746. for(let r of data.rations){
  2747. delete r._id;
  2748. r = getCopyRationData(r,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2749. rations.push(r);
  2750. }
  2751. }
  2752. //生成定额下挂的定额工料机等等数据
  2753. if(data.rationGLJs && data.rationGLJs.length > 0) rationGLJs = setRationSubList(data.rationGLJs,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2754. if(data.rationCoes && data.rationCoes.length > 0) rationCoes = setRationSubList(data.rationCoes,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2755. if(data.quantityDetails && data.quantityDetails.length > 0) quantityDetails = setRationSubList(data.quantityDetails,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2756. if(data.rationInstallations && data.rationInstallations.length > 0) rationInstallations = setRationSubList(data.rationInstallations,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2757. if(data.rationTemplates && data.rationTemplates.length > 0) rationTemplates = setRationSubList(data.rationTemplates,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2758. if(data.evaluateList && data.evaluateList.length > 0) evaluateList = setMaterialList(data.evaluateList,newProjectID,projectGLJIDMap);
  2759. if(data.bidList && data.bidList.length > 0) bidList = setMaterialList(data.bidList,newProjectID,projectGLJIDMap);
  2760. if(data.contractorList && data.contractorList.length > 0) contractorList = setMaterialList(data.contractorList,newProjectID,projectGLJIDMap);
  2761. //生成projectSetting 文件
  2762. if(data.projSetting){
  2763. data.projSetting.projectID =newProjectID;
  2764. newProjectSetting = data.projSetting;
  2765. delete newProjectSetting._id;
  2766. }
  2767. //生成计算程序文件,系数文件
  2768. if(data.calcProgramsFile && calcProgramFileIDMap[data.calcProgramsFile.ID]){
  2769. data.calcProgramsFile.ID = calcProgramFileIDMap[data.calcProgramsFile.ID];
  2770. data.calcProgramsFile.projectID = newProjectID;
  2771. newCalcProgramsFile = data.calcProgramsFile;
  2772. delete newCalcProgramsFile._id;
  2773. }
  2774. if(data.labourCoes && labourCoeFileIDMap[data.labourCoes.ID]){
  2775. data.labourCoes.ID = labourCoeFileIDMap[data.labourCoes.ID];
  2776. data.labourCoes.projectID = newProjectID;
  2777. newLabourCoe = data.labourCoes;
  2778. delete newLabourCoe._id;
  2779. }
  2780. if(data.equipments){
  2781. data.equipments.projectID = newProjectID;
  2782. newEquipments = data.equipments;
  2783. delete newEquipments._id;
  2784. }
  2785. if (data.gatherFees) {
  2786. data.gatherFees.projectID = newProjectID;
  2787. newGatherFees = data.gatherFees;
  2788. delete newGatherFees._id;
  2789. }
  2790. return [newProjectSetting,bills,rations,installationFees,projectGLJs,rationGLJs,rationCoes,quantityDetails,rationInstallations,rationTemplates,evaluateList,bidList,contractorList,newCalcProgramsFile,newLabourCoe,newEquipments,newGatherFees]
  2791. }
  2792. function setMaterialList(datas,newProjectID,projectGLJIDMap){
  2793. let arrs = [];
  2794. for(let d of datas){
  2795. arrs.push(getNewMaterial(d,newProjectID,projectGLJIDMap))
  2796. }
  2797. return arrs
  2798. }
  2799. function setRationSubList(datas,newProjectID,billIDMap,rationIDMap,projectGLJIDMap) {
  2800. let arrs = [];
  2801. for(let d of datas){
  2802. delete d._id;
  2803. d = getCopyRationSubData(d,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  2804. arrs.push(d);
  2805. }
  2806. return arrs;
  2807. }
  2808. async function handleMainProjectDatas(mainData,updateData,userID) {
  2809. let mainProjectID = -1;
  2810. let projectIDMap = {},feeRateFileIDMap={},unitPriceFileIDMap={},labourCoeFileIDMap={},calcProgramFileIDMap={};
  2811. let tasks = [];
  2812. projectIDMap[-1] = -1;//最后一个项目的nextID为-1的情况
  2813. let constructionProjectID;
  2814. //生成新的projectID
  2815. for(let p of mainData.projects){
  2816. let newProjectID = await getCounterID("projects");
  2817. projectIDMap[p.ID] = newProjectID;
  2818. if(p.projType == "Project") {
  2819. mainProjectID = newProjectID;
  2820. constructionProjectID = newProjectID;
  2821. }
  2822. if(p.projType == "Tender"){
  2823. if(p.property.calcProgramFile) calcProgramFileIDMap[p.property.calcProgramFile.ID] = uuidV1();//新的计算程序文件ID
  2824. if(p.property.labourCoeFile) labourCoeFileIDMap[p.property.labourCoeFile.ID] = uuidV1();//新的人工调整系数文件ID
  2825. if(p.property.feeFile) feeRateFileIDMap[p.property.feeFile.id] = uuidV1();//新的费率文件ID
  2826. if(p.property.unitPriceFile) unitPriceFileIDMap[p.property.unitPriceFile.id] = await getCounterID("unit_price_file");//新的单价文件ID
  2827. }
  2828. }
  2829. if(mainProjectID == -1) throw new Error("文件里面没包含建设项目信息!");
  2830. //处理项目信息 ----- 费率文件,单价文件ID信息要重新生成----to do
  2831. for(let p of mainData.projects){
  2832. delete p._id;
  2833. delete p.__v;
  2834. p.ID = projectIDMap[p.ID];
  2835. if(p.ID == mainProjectID){//对于建设项目,要父和下一节点ID要使用前端传入的位置ID
  2836. p.ParentID = updateData.self.ParentID;
  2837. p.NextSiblingID = updateData.self.NextSiblingID;
  2838. if(updateData.update){//树节构中的上一节点的下一节点设置为本建设项目ID;
  2839. tasks.push({updateOne:{filter : updateData.update.query, update : {NextSiblingID:mainProjectID}}});
  2840. }
  2841. //查看是否重名;
  2842. let temp = await projectModel.findOne({userID:userID,ParentID:p.ParentID,name:p.name});
  2843. if(temp) p.name = p.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '导入)';
  2844. }else {
  2845. p.ParentID = projectIDMap[p.ParentID];
  2846. p.NextSiblingID = projectIDMap[p.NextSiblingID];
  2847. }
  2848. p.userID =userID;
  2849. p.shareInfo=[];
  2850. if(p.projType == "Tender"){
  2851. if(p.property.calcProgramFile) p.property.calcProgramFile.ID = calcProgramFileIDMap[p.property.calcProgramFile.ID];
  2852. if(p.property.labourCoeFile) p.property.labourCoeFile.ID = labourCoeFileIDMap[p.property.labourCoeFile.ID];
  2853. if(p.property.feeFile) p.property.feeFile.id = feeRateFileIDMap[p.property.feeFile.id];
  2854. if(p.property.unitPriceFile) p.property.unitPriceFile.id = unitPriceFileIDMap[p.property.unitPriceFile.id];
  2855. p.property.rootProjectID = mainProjectID
  2856. }
  2857. tasks.push({insertOne: {document: p}})
  2858. }
  2859. //项目树节构数据生成:
  2860. await projectModel.bulkWrite(tasks);
  2861. //生成所有的费率文件
  2862. await importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID);
  2863. //生成所有的单价文件
  2864. await importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID);
  2865. return [constructionProjectID,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap]
  2866. }
  2867. async function importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID) {
  2868. if(!mainData.files.unitFiles) return;
  2869. let unitFiles = [],unitPrices =[],mixRatios=[],freights=[],originals=[];
  2870. for(let f of mainData.files.unitFiles){
  2871. let file = f.unitFile,prices = f.unitPrices,mixs = f.mixRatios,fres = f.freights,ors = f.originals;
  2872. //生成单价文件
  2873. delete file._id;
  2874. file.id = unitPriceFileIDMap[file.id]?unitPriceFileIDMap[file.id]:await getCounterID("unit_price_file");
  2875. file.project_id = projectIDMap[file.project_id];
  2876. file.root_project_id = projectIDMap[file.root_project_id];
  2877. file.user_id = userID;
  2878. unitFiles.push(file);
  2879. //生成子数据
  2880. if(prices) await setSubList(prices,unitPrices,file.id,unitPriceModel);
  2881. if(mixs) await setSubList(mixs,mixRatios,file.id,mixRatioModel);
  2882. }
  2883. if(unitFiles.length > 0) await insertMany(unitFiles,unitPriceFileModel);
  2884. if(unitPrices.length > 0) await insertMany(unitPrices,unitPriceModel);
  2885. if(mixRatios.length > 0) await insertMany(mixRatios,mixRatioModel);
  2886. async function setSubList(oList,nList,fileID,model) {
  2887. let IDcounter = await counter.counterDAO.getIDAfterCountSync(model.modelName, oList.length);
  2888. let firstID = IDcounter.sequence_value - (oList.length - 1);
  2889. for(let o of oList){
  2890. delete o._id;
  2891. o.unit_price_file_id = fileID;
  2892. o.id = firstID;
  2893. firstID+=1
  2894. nList.push(o)
  2895. }
  2896. }
  2897. }
  2898. async function importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID) {
  2899. let feeRateFiles = [], feeRates = [];
  2900. if(!mainData.files.feeRateFiles) return;
  2901. for(let f of mainData.files.feeRateFiles){
  2902. //生成费率记录
  2903. let rate = f.feeRate;
  2904. delete rate._id;
  2905. rate.ID = uuidV1();
  2906. feeRates.push(rate);
  2907. //生成费率文件记录
  2908. let file = f.feeRateFile;
  2909. delete file._id;
  2910. file.ID = feeRateFileIDMap[file.ID]?feeRateFileIDMap[file.ID]:uuidV1();
  2911. file.userID = userID;
  2912. file.rootProjectID = projectIDMap[file.rootProjectID];
  2913. file.feeRateID = rate.ID;
  2914. feeRateFiles.push(file);
  2915. }
  2916. if(feeRateFiles.length > 0) await insertMany(feeRateFiles,feeRateFileModel);
  2917. if(feeRates.length > 0) await insertMany(feeRates,feeRateModel);
  2918. }
  2919. // 初始化
  2920. async function initOverHeightItems(engineeringID) {
  2921. const defaultData = [];
  2922. const engineering = await engineeringModel.findById(engineeringID);
  2923. const overHeightLibs = engineering.over_height_lib;
  2924. if (!overHeightLibs || !overHeightLibs.length) {
  2925. return defaultData;
  2926. }
  2927. const overHeightLibID = overHeightLibs[0].id;
  2928. const overHeightLib = await overHeightLibModel.findOne({ID: overHeightLibID});
  2929. return overHeightLib ? overHeightLib.list : defaultData;
  2930. }
  2931. function uploadToken() {
  2932. let options = {
  2933. scope: qiniu_config.Bucket,
  2934. deleteAfterDays: 1,
  2935. returnBody:
  2936. '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
  2937. };
  2938. let putPolicy = new qiniu.rs.PutPolicy(options);
  2939. let token = putPolicy.uploadToken(mac);
  2940. let result = {
  2941. uptoken: token,
  2942. domain: qiniu_config.Domain
  2943. }
  2944. return result
  2945. }
  2946. // 获取系统设置,这个系统设置正常情况下有存在session中
  2947. async function getSystemSetting() {
  2948. return await systemSettingModel.findOne({}).lean();
  2949. }
  2950. // 有些方法无法通过中间件就检查单位工程数量是否超限
  2951. // 需要到具体的业务代码中进行判断
  2952. // 这个方法就是具体业务代码中,需要检查单位工程数量是否超限用
  2953. async function isTenderOverrun(tenderCount, session) {
  2954. const userID = session.sessionUser.id;
  2955. const compilation = session.sessionCompilation._id;
  2956. const compilationVersion = session.compilationVersion || '免费';
  2957. let systemSetting = session.systemSetting || (session.systemSetting = await getSystemSetting());
  2958. // 这种情况只有在刚上线此功能时会出现,不考虑时间差
  2959. if (!systemSetting) {
  2960. return false;
  2961. }
  2962. const type = compilationVersion.includes('免费') ? 'normal' : 'professional';
  2963. const limit = systemSetting[type].project;
  2964. const curTenderCount = await projectModel.count({userID, compilation, projType: 'Tender', '$or':[{deleteInfo: null}, {'deleteInfo.completeDeleted': false}]});
  2965. return tenderCount + curTenderCount > limit;
  2966. }
  2967. async function getWelcomeInfo(compilationId,sessionUser,isFree=true) {
  2968. let welcom_setting = await welcomeModel.findOne({compilationId:compilationId});
  2969. let isShow = false;
  2970. let context = "";
  2971. let setting = null
  2972. if(welcom_setting){
  2973. setting = isFree? welcom_setting.normal:welcom_setting.professional;//区分专业版和免费版
  2974. }
  2975. if(setting){
  2976. if(setting.showType == 0) return [false,""];//关闭
  2977. context = setting.context;
  2978. if(setting.showType == 1){//每天一次
  2979. let dataString =moment(Date.now()).tz("Asia/Shanghai").format('YYYY-MM-DD');//今天的日期字符串
  2980. let userInfo =await userModel.findOne({_id: mongoose.Types.ObjectId(sessionUser.id)});
  2981. if (dataString != userInfo.welcomeShowTime){//今天没登录过
  2982. isShow = true;
  2983. await userModel.update({_id: mongoose.Types.ObjectId(sessionUser.id)},{welcomeShowTime:dataString})
  2984. }
  2985. }else if(setting.showType == 2){//每次登录显示
  2986. isShow = sessionUser.newLogin?true:false;
  2987. sessionUser.newLogin = false
  2988. }
  2989. }
  2990. return [isShow,context]
  2991. }