ledger.js 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  1. 'use strict';
  2. /**
  3. * 标段--台账 数据模型
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/12/1
  7. * @version
  8. */
  9. const needField = {
  10. id: 'ledger_id',
  11. pid: 'ledger_pid',
  12. order: 'order',
  13. level: 'level',
  14. fullPath: 'full_path',
  15. isLeaf: 'is_leaf',
  16. };
  17. const keyFields = {
  18. table: ['id'],
  19. index: ['tender_id', 'ledger_id'],
  20. };
  21. // 以下字段仅可通过树结构操作改变,不可直接通过update方式从接口提交,发现时过滤
  22. const readOnlyFields = ['id', 'tender_id', 'ledger_id', 'ledger_pid', 'order', 'level', 'full_path', 'is_leaf'];
  23. const calcFields = ['quantity', 'unit_price', 'total_price', 'deal_qty', 'deal_tp', 'dgn_qty1', 'dgn_qty2'];
  24. const upFields = ['unit_price'];
  25. const qtyFields = ['quantity', 'deal_qty', 'dgn_qty1', 'dgn_qty2'];
  26. const tpFields = ['total_price', 'deal_tp'];
  27. const zeroRange = 0.0000000001;
  28. const rootId = -1;
  29. const keyPre = 'tender_node_maxId:';
  30. module.exports = app => {
  31. class Ledger extends app.BaseService {
  32. /**
  33. * 构造函数
  34. *
  35. * @param {Object} ctx - egg全局变量
  36. * @return {void}
  37. */
  38. constructor(ctx) {
  39. super(ctx);
  40. this.tableName = 'ledger';
  41. }
  42. /**
  43. * 新增数据(供内部或其他service类调用, controller不可直接使用)
  44. * @param {Array|Object} data - 新增数据
  45. * @param {Number} tenderId - 标段id
  46. * @param {Object} transaction - 新增事务
  47. * @return {Promise<boolean>} - {Promise<是否正确新增成功>}
  48. */
  49. async innerAdd(data, tenderId, transaction) {
  50. const datas = data instanceof Array ? data : [data];
  51. if (tenderId <= 0) {
  52. throw '标段id错误';
  53. }
  54. if (datas.length <= 0) {
  55. throw '插入数据为空';
  56. }
  57. if (!transaction) {
  58. throw '内部错误';
  59. }
  60. // 整理数据
  61. const insertData = [];
  62. for (const tmp of datas) {
  63. tmp.ledger_id = tmp.id;
  64. tmp.ledger_pid = tmp.pid;
  65. tmp.tender_id = tenderId;
  66. delete tmp.id;
  67. delete tmp.pid;
  68. insertData.push(tmp);
  69. }
  70. const operate = await transaction.insert(this.tableName, insertData);
  71. return operate.affectedRows === datas.length;
  72. }
  73. /**
  74. * 新增数据
  75. *
  76. * @param {Object} data - 新增的数据(可批量)
  77. * @param {Number} tenderId - 标段id
  78. * @return {Boolean} - 返回新增的结果
  79. */
  80. async add(data, tenderId) {
  81. this.transaction = await this.db.beginTransaction();
  82. let result = false;
  83. try {
  84. result = await this.innerAdd(data, tenderId, this.transaction);
  85. if (!result) {
  86. throw '新增数据错误';
  87. }
  88. await this.transaction.commit();
  89. } catch (error) {
  90. await this.transaction.rollback();
  91. result = false;
  92. }
  93. return result;
  94. }
  95. /**
  96. * 根据层级获取数据
  97. *
  98. * @param {Number} tenderId - 标段id
  99. * @param {Number} showLevel - 显示层数
  100. * @return {Array} - 返回数据
  101. */
  102. async getDataByTenderId(tenderId, showLevel = 4) {
  103. if (tenderId <= 0) {
  104. return [];
  105. }
  106. this.initSqlBuilder();
  107. this.sqlBuilder.setAndWhere('tender_id', {
  108. value: tenderId,
  109. operate: '=',
  110. });
  111. if (showLevel > 0) {
  112. this.sqlBuilder.setAndWhere('level', {
  113. value: showLevel,
  114. operate: '<=',
  115. });
  116. }
  117. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  118. const data = await this.db.query(sql, sqlParam);
  119. return data;
  120. }
  121. /**
  122. * 根据节点Id获取数据
  123. *
  124. * @param {Number} tenderId - 标段id
  125. * @param {Number} nodeId - 项目节/工程量清单节点id
  126. * @return {Object} - 返回查询到的节点数据
  127. */
  128. async getDataByNodeId(tenderId, nodeId) {
  129. if ((nodeId <= 0) || (tenderId <= 0)) {
  130. return undefined;
  131. }
  132. this.initSqlBuilder();
  133. this.sqlBuilder.setAndWhere('tender_id', {
  134. value: tenderId,
  135. operate: '=',
  136. });
  137. this.sqlBuilder.setAndWhere('ledger_id', {
  138. value: nodeId,
  139. operate: '=',
  140. });
  141. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  142. const data = await this.db.queryOne(sql, sqlParam);
  143. return data;
  144. }
  145. /**
  146. * 根据节点Id获取数据
  147. * @param {Number} tenderId - 标段Id
  148. * @param {Array} nodesIds - 节点Id
  149. * @return {Array}
  150. */
  151. async getDataByNodeIds(tenderId, nodesIds) {
  152. if (tenderId <= 0) {
  153. return [];
  154. }
  155. this.initSqlBuilder();
  156. this.sqlBuilder.setAndWhere('tender_id', {
  157. value: tenderId,
  158. operate: '=',
  159. });
  160. this.sqlBuilder.setAndWhere('ledger_id', {
  161. value: nodesIds,
  162. operate: 'in',
  163. });
  164. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  165. const data = await this.db.query(sql, sqlParam);
  166. return data;
  167. }
  168. /**
  169. * 根据主键id获取数据
  170. * @param {Array|Number} id - 主键id
  171. * @return {Promise<*>}
  172. */
  173. async getDataByIds(id) {
  174. if (!id) {
  175. return;
  176. }
  177. const ids = id instanceof Array ? id : [id];
  178. if (ids.length === 0) {
  179. return;
  180. }
  181. this.initSqlBuilder();
  182. this.sqlBuilder.setAndWhere('id', {
  183. value: ids,
  184. operate: 'in',
  185. });
  186. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  187. const data = await this.db.query(sql, sqlParam);
  188. return data;
  189. }
  190. /**
  191. * 根据标准清单源检索
  192. * @param tenderId
  193. * @param source
  194. * @return {Promise<*>}
  195. */
  196. async getDataBySource(tenderId, source) {
  197. this.initSqlBuilder();
  198. this.sqlBuilder.setAndWhere('tender_id', {
  199. value: tenderId,
  200. operate: '=',
  201. });
  202. this.sqlBuilder.setAndWhere('source', {
  203. value: source,
  204. operate: '=',
  205. });
  206. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  207. const data = await this.db.query(sql, sqlParam);
  208. return data;
  209. }
  210. /**
  211. * 获取最末的子节点
  212. * @param {Number} tenderId - 标段id
  213. * @param {Number} pid - 父节点id
  214. * @return {Object}
  215. */
  216. async getLastChildData(tenderId, pid) {
  217. this.initSqlBuilder();
  218. this.sqlBuilder.setAndWhere('tender_id', {
  219. value: tenderId,
  220. operate: '=',
  221. });
  222. this.sqlBuilder.setAndWhere('ledger_pid', {
  223. value: pid,
  224. operate: '=',
  225. });
  226. this.sqlBuilder.orderBy = [['order', 'DESC']];
  227. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  228. const resultData = await this.db.queryOne(sql, sqlParam);
  229. return resultData;
  230. }
  231. /**
  232. * 根据 父节点id 和 节点排序order 获取数据
  233. *
  234. * @param {Number} tenderId - 标段id
  235. * @param {Number} pid - 父节点id
  236. * @param {Number|Array} order - 排序
  237. * @return {Object|Array} - 查询结果
  238. */
  239. async getDataByParentAndOrder(tenderId, pid, order) {
  240. if ((tenderId <= 0) || (pid <= 0) || (order <= 0)) {
  241. return undefined;
  242. }
  243. this.initSqlBuilder();
  244. this.sqlBuilder.setAndWhere('tender_id', {
  245. value: tenderId,
  246. operate: '=',
  247. });
  248. this.sqlBuilder.setAndWhere('ledger_pid', {
  249. value: pid,
  250. operate: '=',
  251. });
  252. if (order instanceof Array) {
  253. this.sqlBuilder.setAndWhere('order', {
  254. value: order,
  255. operate: 'in',
  256. });
  257. } else {
  258. this.sqlBuilder.setAndWhere('order', {
  259. value: order,
  260. operate: '=',
  261. });
  262. }
  263. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  264. let data;
  265. if (order instanceof Array) {
  266. data = await this.db.query(sql, sqlParam);
  267. } else {
  268. data = await this.db.queryOne(sql, sqlParam);
  269. }
  270. return data;
  271. }
  272. /**
  273. * 根据 父节点id 获取子节点
  274. * @param tenderId
  275. * @param nodeId
  276. * @return {Promise<*>}
  277. */
  278. async getChildrenByParentId(tenderId, nodeId) {
  279. if (tenderId <= 0 || !nodeId) {
  280. return undefined;
  281. }
  282. const nodeIds = nodeId instanceof Array ? nodeId : [nodeId];
  283. if (nodeIds.length === 0) {
  284. return [];
  285. }
  286. this.initSqlBuilder();
  287. this.sqlBuilder.setAndWhere('tender_id', {
  288. value: tenderId,
  289. operate: '=',
  290. });
  291. this.sqlBuilder.setAndWhere('ledger_pid', {
  292. value: nodeIds,
  293. operate: 'in',
  294. });
  295. this.sqlBuilder.orderBy = [['order', 'ASC']];
  296. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  297. const data = await this.db.query(sql, sqlParam);
  298. return data;
  299. }
  300. /**
  301. * 根据 父节点id 获取孙子节点
  302. * @param tenderId
  303. * @param nodeId
  304. * @return {Promise<void>}
  305. */
  306. async getPosterityByParentId(tenderId, nodeId) {
  307. if (tenderId <= 0 || !nodeId) {
  308. return undefined;
  309. }
  310. const node = await this.getDataByNodeId(tenderId, nodeId);
  311. this.initSqlBuilder();
  312. this.sqlBuilder.setAndWhere('tender_id', {
  313. value: tenderId,
  314. operate: '=',
  315. });
  316. this.sqlBuilder.setAndWhere('full_path', {
  317. value: this.db.escape(node.full_path + '.%'),
  318. operate: 'like',
  319. });
  320. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  321. const data = await this.db.query(sql, sqlParam);
  322. return data;
  323. }
  324. /**
  325. * 根据 父节点ID 和 节点排序order 获取全部后节点数据
  326. * @param {Number} tenderId - 标段id
  327. * @param {Number} pid - 父节点id
  328. * @param {Number} order - 排序
  329. * @return {Array}
  330. */
  331. async getNextsData(tenderId, pid, order) {
  332. if ((tenderId <= 0) || (order < 0)) {
  333. return undefined;
  334. }
  335. this.initSqlBuilder();
  336. this.sqlBuilder.setAndWhere('tender_id', {
  337. value: tenderId,
  338. operate: '=',
  339. });
  340. this.sqlBuilder.setAndWhere('ledger_pid', {
  341. value: pid,
  342. operate: '=',
  343. });
  344. this.sqlBuilder.setAndWhere('order', {
  345. value: order,
  346. operate: '>',
  347. });
  348. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  349. const data = await this.db.query(sql, sqlParam);
  350. return data;
  351. }
  352. /**
  353. * 根据full_path获取数据 full_path Like ‘1.2.3%’(传参full_path = '1.2.3%')
  354. * @param {Number} tenderId - 标段id
  355. * @param {String} full_path - 路径
  356. * @return {Promise<void>}
  357. */
  358. async getDataByFullPath(tenderId, full_path) {
  359. this.initSqlBuilder();
  360. this.sqlBuilder.setAndWhere('tender_id', {
  361. value: tenderId,
  362. operate: '=',
  363. });
  364. this.sqlBuilder.setAndWhere('full_path', {
  365. value: this.db.escape(full_path),
  366. operate: 'Like',
  367. });
  368. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  369. const resultData = await this.db.query(sql, sqlParam);
  370. return resultData;
  371. }
  372. /**
  373. * 根据full_path检索自己及所有父项
  374. * @param {Number} tenderId - 标段id
  375. * @param {Array|String} fullPath - 节点完整路径
  376. * @return {Promise<*>}
  377. * @private
  378. */
  379. async getFullLevelDataByFullPath(tenderId, fullPath) {
  380. const explodePath = this.ctx.helper.explodePath(fullPath);
  381. this.initSqlBuilder();
  382. this.sqlBuilder.setAndWhere('tender_id', {
  383. value: tenderId,
  384. operate: '=',
  385. });
  386. this.sqlBuilder.setAndWhere('full_path', {
  387. value: explodePath,
  388. operate: 'in',
  389. });
  390. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  391. const data = await this.db.query(sql, sqlParam);
  392. return data;
  393. }
  394. /**
  395. * 获取项目工程量
  396. * @param tenderId
  397. * @returns {Promise<*>}
  398. */
  399. async getGatherGclBills(tenderId) {
  400. const sql = 'SELECT `b_code`, `name`, `unit`, `unit_price`, ' +
  401. ' Sum(`quantity`) As `quantity`, Sum(`total_price`) As `total_price`, ' +
  402. ' Sum(`deal_qty`) As `deal_qty`, Sum(`deal_tp`) As `deal_tp` ' +
  403. ' From ?? ' +
  404. ' WHERE `tender_id` = ? And `b_code` And `is_leaf` ' +
  405. ' GROUP BY `b_code`, `name`, `unit`, `unit_price`';
  406. const sqlParam = [this.tableName, tenderId];
  407. return await this.db.query(sql, sqlParam);
  408. }
  409. /**
  410. * 获取sql条件语句片段,仅供search、searchRange方法使用
  411. * @param {Object} where - 条件参数
  412. * @return {*[]}
  413. * e.g.
  414. * where = {type: 'And', value: 'A', operate: '=', fields: ['code', 'name']}
  415. * return [sql: 'And (?? = \'A\' Or ?? = \'A\')', sqlParam: ['code', name]]
  416. * @private
  417. */
  418. _getWhereString(where) {
  419. const sqlParam = [],
  420. sqlPart = [];
  421. const values = where.value instanceof Array ? where.value : [where.value];
  422. const fields = where.fields instanceof Array ? where.fields : [where.fields];
  423. for (const field of fields) {
  424. for (const v of values) {
  425. sqlPart.push('?? ' + where.operate + ' ' + v);
  426. sqlParam.push(field);
  427. }
  428. }
  429. const sql = ' ' + (where.type ? where.type : 'And') + ' (' + sqlPart.join(' OR ') + ')';
  430. return [sql, sqlParam];
  431. }
  432. /**
  433. * 搜索台账
  434. *
  435. * @param {Number} tenderId - 标段id
  436. * @param {Object} key - 查询信息
  437. * @return {Promise<void>}
  438. */
  439. async search(tenderId, key) {
  440. let sql = 'Select * From ?? Where';
  441. let sqlParam = [this.tableName];
  442. sql = sql + ' ?? = ' + tenderId;
  443. sqlParam.push('tender_id');
  444. const [sql1, sqlParam1] = this._getWhereString(key);
  445. sql = sql + sql1;
  446. sqlParam = sqlParam.concat(sqlParam1);
  447. return this.db.query(sql, sqlParam);
  448. }
  449. /**
  450. * 范围内搜索台账
  451. *
  452. * @param {Number} tenderId - 标段id
  453. * @param {Object} key - 查询信息
  454. * @param {Array} range - 查询范围
  455. * @return {Promise<void>}
  456. */
  457. async searchRange(tenderId, key, range) {
  458. let sql = 'Select * From ?? Where';
  459. let sqlParam = [this.tableName];
  460. sql = sql + ' ?? = ' + tenderId;
  461. sqlParam.push('tender_id');
  462. let [sql1, sqlParam1] = this._getWhereString(key);
  463. sql = sql + sql1;
  464. sqlParam = sqlParam.concat(sqlParam1);
  465. for (const r of range) {
  466. [sql1, sqlParam1] = this._getWhereString(r);
  467. sql = sql + sql1;
  468. sqlParam = sqlParam.concat(sqlParam1);
  469. }
  470. return this.db.query(sql, sqlParam);
  471. }
  472. /**
  473. * 统计子节点total_price
  474. * @param {Number} tenderId - 标段id
  475. * @param {Number} pid - 父节点id
  476. * @param {Number} order - order取值
  477. * @param {String} orderOperate - order比较操作符
  478. * @return {Promise<void>}
  479. */
  480. async addUpChildren(tenderId, pid, order, orderOperate) {
  481. this.initSqlBuilder();
  482. const sql = ['SELECT SUM(??) As value FROM ?? ', ' WHERE '];
  483. const sqlParam = ['total_price', this.tableName];
  484. sql.push(' ?? = ' + tenderId);
  485. sqlParam.push('tender_id');
  486. sql.push(' And ?? = ' + pid);
  487. sqlParam.push('ledger_pid');
  488. sql.push(' And ?? ' + orderOperate + ' ' + order);
  489. sqlParam.push('order');
  490. const result = await this.db.queryOne(sql.join(''), sqlParam);
  491. return result.value;
  492. }
  493. /**
  494. * 更新order
  495. * @param {Number} tenderId - 标段id
  496. * @param {Number} parentId - 父节点id
  497. * @param {Number} order - 自增起始order(含)
  498. * @param {Number} incre - 自增量
  499. * @return {Promise<*>}
  500. * @private
  501. */
  502. async _updateChildrenOrderAfter(tenderId, parentId, order, incre = 1) {
  503. this.initSqlBuilder();
  504. this.sqlBuilder.setAndWhere('tender_id', {
  505. value: tenderId,
  506. operate: '=',
  507. });
  508. this.sqlBuilder.setAndWhere('order', {
  509. value: order,
  510. operate: '>=',
  511. });
  512. this.sqlBuilder.setAndWhere('ledger_pid', {
  513. value: parentId,
  514. operate: '=',
  515. });
  516. this.sqlBuilder.setUpdateData('order', {
  517. value: Math.abs(incre),
  518. selfOperate: incre > 0 ? '+' : '-',
  519. });
  520. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  521. const data = await this.transaction.query(sql, sqlParam);
  522. return data;
  523. }
  524. /**
  525. * select的全部后兄弟节点,Order自增
  526. *
  527. * @param {Object} select - 选中的节点
  528. * @param {Number} incre - 自增值
  529. * @return {Array} - 自增后的数据
  530. * @private
  531. */
  532. async _updateSelectNextsOrder(select, incre = 1) {
  533. return await this._updateChildrenOrderAfter(select.tender_id, select.ledger_pid, select.order + 1, incre);
  534. }
  535. /**
  536. * 从数据库获取标段的最大节点id
  537. *
  538. * @param {Number} tenderId - 标段id
  539. * @return {Number}
  540. * @private
  541. */
  542. async _getMaxNodeId(tenderId) {
  543. const sql = 'SELECT Max(??) As max_id FROM ?? Where tender_id = ' + tenderId;
  544. const sqlParam = ['ledger_id', this.tableName];
  545. const queryResult = await this.db.queryOne(sql, sqlParam);
  546. return queryResult.max_id;
  547. }
  548. /**
  549. * 根据selectData, data 新增数据(新增为selectData的后项,该方法不可单独使用)
  550. *
  551. * @param {Number} tenderId - 标段id
  552. * @param {Object} selectData - 选中节点的数据
  553. * @param {Object} data - 新增节点的初始数据
  554. * @return {Object} - 新增结果
  555. * @private
  556. */
  557. async _addNodeData(tenderId, selectData, data) {
  558. if (tenderId <= 0) {
  559. return undefined;
  560. }
  561. if (!data) {
  562. data = {};
  563. }
  564. const cacheKey = keyPre + tenderId;
  565. let maxId = parseInt(await this.cache.get(cacheKey));
  566. if (!maxId) {
  567. maxId = await this._getMaxNodeId(tenderId);
  568. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  569. }
  570. data.tender_id = tenderId;
  571. data.ledger_id = maxId + 1;
  572. data.ledger_pid = selectData.ledger_pid;
  573. data.level = selectData.level;
  574. data.order = selectData.order + 1;
  575. data.full_path = selectData.full_path.replace('.' + selectData.ledger_id, '.' + data.ledger_id);
  576. data.is_leaf = true;
  577. const result = await this.transaction.insert(this.tableName, data);
  578. this.cache.set(cacheKey, maxId + 1, 'EX', this.ctx.app.config.cacheTime);
  579. return result;
  580. }
  581. /**
  582. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  583. * @param {Number} tenderId - 标段id
  584. * @param {Object} parentData - 父项数据
  585. * @param {Object} data - 新增节点,初始数据
  586. * @return {Promise<*>} - 新增结果
  587. * @private
  588. */
  589. async _addChildNodeData(tenderId, parentData, data) {
  590. if (tenderId <= 0) {
  591. return undefined;
  592. }
  593. if (!data) {
  594. data = {};
  595. }
  596. const pid = parentData ? parentData.ledger_id : rootId;
  597. const cacheKey = keyPre + tenderId;
  598. let maxId = parseInt(await this.cache.get(cacheKey));
  599. if (!maxId) {
  600. maxId = await this._getMaxNodeId(tenderId);
  601. }
  602. this.cache.set(cacheKey, maxId + 1, 'EX', this.ctx.app.config.cacheTime);
  603. data.tender_id = tenderId;
  604. data.ledger_id = maxId + 1;
  605. data.ledger_pid = pid;
  606. if (data.order === undefined) {
  607. data.order = 1;
  608. }
  609. data.level = parentData ? parentData.level + 1 : 1;
  610. data.full_path = parentData ? parentData.full_path + '.' + data.ledger_id : '' + data.ledger_id;
  611. if (data.is_leaf === undefined) {
  612. data.is_leaf = true;
  613. }
  614. const result = await this.transaction.insert(this.tableName, data);
  615. return [result, data];
  616. }
  617. /**
  618. * 根据parentData, data新增数据(自动排序)
  619. * @param tenderId
  620. * @param parentData
  621. * @param data
  622. * @return {Promise<void>}
  623. * @private
  624. */
  625. async _addChildAutoOrder(tenderId, parentData, data) {
  626. const self = this;
  627. const findPreData = function(list, a) {
  628. if (!list || list.length === 0) { return null; }
  629. for (let i = 0, iLen = list.length; i < iLen; i++) {
  630. if (self.ctx.helper.compareCode(list[i].code, a.code) > 0) {
  631. return i > 0 ? list[i - 1] : null;
  632. }
  633. }
  634. return list[list.length - 1];
  635. };
  636. const pid = parentData ? parentData.ledger_id : rootId;
  637. const children = await this.getChildrenByParentId(tenderId, pid);
  638. const preData = findPreData(children, data);
  639. const parent = null;
  640. if (!preData || children.indexOf(preData) < children.length - 1) {
  641. await this._updateChildrenOrderAfter(tenderId, pid, preData ? preData.order + 1 : 1);
  642. }
  643. data.order = preData ? preData.order + 1 : 1;
  644. const [addResult, node] = await this._addChildNodeData(tenderId, parentData, data);
  645. return [addResult, node];
  646. }
  647. /**
  648. * tenderId标段中, 在selectId后新增一个节点
  649. *
  650. * @param {Number} tenderId - 标段id
  651. * @param {Number} selectId - 选中节点id
  652. * @param {Object} data - 新增节点初始化数据
  653. * @return {Array} 新增后的数据,其他被修改的数据
  654. */
  655. async addNode(tenderId, selectId, data) {
  656. if ((tenderId <= 0) || (selectId <= 0)) {
  657. return [];
  658. }
  659. const selectData = await this.getDataByNodeId(tenderId, selectId);
  660. if (!selectData) {
  661. throw '新增节点数据错误';
  662. }
  663. if (!this.transaction) {
  664. this.transaction = await this.db.beginTransaction();
  665. }
  666. try {
  667. // 选中节点的所有后兄弟节点,order+1
  668. await this._updateSelectNextsOrder(selectData);
  669. // 数据库创建新增节点数据
  670. const newNode = await this._addNodeData(tenderId, selectData, data);
  671. if (!newNode) { throw '新增节点数据错误'; }
  672. await this.transaction.commit();
  673. } catch (err) {
  674. await this.transaction.rollback();
  675. this.transaction = null;
  676. throw err;
  677. }
  678. this.transaction = null;
  679. // 查询应返回的结果
  680. const createData = await this.getDataByParentAndOrder(selectData.tender_id, selectData.ledger_pid, [selectData.order + 1]);
  681. const updateData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + 1);
  682. return { create: createData, update: updateData };
  683. }
  684. /**
  685. * 从标准数据中提取有效数据
  686. * @param {Object} stdData - 从标准库中查询所得
  687. * @returns {name, unit, source, code, b_code}
  688. * @private
  689. */
  690. _filterStdData(stdData) {
  691. const result = {
  692. name: stdData.name,
  693. unit: stdData.unit,
  694. source: stdData.source,
  695. };
  696. result.code = stdData.code ? stdData.code : '';
  697. result.b_code = stdData.b_code ? stdData.b_code : '';
  698. return result;
  699. }
  700. /**
  701. * 添加节点(来自标准清单)
  702. * @param {Number} tenderId
  703. * @param {Number} selectId
  704. * @param {Object} stdData
  705. * @return {Promise<*>}
  706. */
  707. async addStdNode(tenderId, selectId, stdData) {
  708. const newData = this._filterStdData(stdData);
  709. const result = await this.addNode(tenderId, selectId, newData);
  710. return result;
  711. }
  712. async addChild(tenderId, selectId, data) {
  713. if ((tenderId <= 0) || (selectId <= 0)) {
  714. return [];
  715. }
  716. const selectData = await this.getDataByNodeId(tenderId, selectId);
  717. if (!selectData) {
  718. throw '新增节点数据错误';
  719. }
  720. const children = await this.getChildrenByParentId(tenderId, selectId);
  721. const cacheKey = keyPre + tenderId;
  722. let maxId = parseInt(await this.cache.get(cacheKey));
  723. if (!maxId) {
  724. maxId = await this._getMaxNodeId(tenderId);
  725. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  726. }
  727. data.tender_id = tenderId;
  728. data.ledger_id = maxId + 1;
  729. data.ledger_pid = selectData.ledger_id;
  730. data.level = selectData.level + 1;
  731. data.order = children.length + 1;
  732. data.full_path = selectData.full_path + '.' + data.ledger_id;
  733. data.is_leaf = true;
  734. const result = await this.db.insert(this.tableName, data);
  735. this.cache.set(cacheKey, maxId + 1, 'EX', this.ctx.app.config.cacheTime);
  736. // 查询应返回的结果
  737. const createData = await this.getDataByNodeId(tenderId, data.ledger_id);
  738. return { create: createData };
  739. }
  740. async addStdNodeAsChild(tenderId, selectId, stdData) {
  741. const newData = this._filterStdData(stdData);
  742. const result = await this.addChild(tenderId, selectId, newData);
  743. return result;
  744. }
  745. /**
  746. * 添加节点,并同步添加父节点
  747. * @param {Number} tenderId - 标段id
  748. * @param {Number} selectId - 选中节点id
  749. * @param {Object} stdData - 节点数据
  750. * @param {StandardLib} stdLib - 标准库
  751. * @return {Promise<void>}
  752. */
  753. async addStdNodeWithParent(tenderId, stdData, stdLib) {
  754. // 查询完整标准清单,并按层次排序
  755. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  756. fullLevel.sort(function(x, y) {
  757. return x.level - y.level;
  758. });
  759. let isNew = false,
  760. node,
  761. firstNew,
  762. updateParent,
  763. addResult;
  764. const expandIds = [];
  765. this.transaction = await this.db.beginTransaction();
  766. try {
  767. // 从最顶层节点依次查询是否存在,否则添加
  768. for (let i = 0, len = fullLevel.length; i < len; i++) {
  769. const stdNode = fullLevel[i];
  770. if (isNew) {
  771. const newData = this._filterStdData(stdNode);
  772. newData.is_leaf = (i === len - 1);
  773. [addResult, node] = await this._addChildNodeData(tenderId, node, newData);
  774. } else {
  775. const parent = node;
  776. node = await this.getDataByCondition({
  777. tender_id: tenderId,
  778. ledger_pid: parent ? parent.ledger_id : rootId,
  779. code: stdNode.code,
  780. name: stdNode.name,
  781. });
  782. if (!node) {
  783. isNew = true;
  784. const newData = this._filterStdData(stdNode);
  785. newData.is_leaf = (i === len - 1);
  786. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData);
  787. if (parent && parent.is_leaf) {
  788. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false });
  789. updateParent = parent;
  790. }
  791. firstNew = node;
  792. } else {
  793. expandIds.push(node.ledger_id);
  794. }
  795. }
  796. }
  797. await this.transaction.commit();
  798. } catch (err) {
  799. await this.transaction.rollback();
  800. throw err;
  801. }
  802. // 查询应返回的结果
  803. let createData = [],
  804. updateData = [];
  805. if (firstNew) {
  806. createData = await this.getDataByFullPath(tenderId, firstNew.full_path + '%');
  807. updateData = await this.getNextsData(tenderId, firstNew.ledger_pid, firstNew.order);
  808. if (updateParent) {
  809. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  810. }
  811. }
  812. //const expandData = await this.getChildrenByParentId(tenderId, expandIds);
  813. return { create: createData, update: updateData };
  814. }
  815. /**
  816. * 删除节点
  817. * @param {Number} tenderId - 标段id
  818. * @param {Object} deleteData - 删除节点数据
  819. * @return {Promise<*>}
  820. * @private
  821. */
  822. async _deleteNodeData(tenderId, deleteData) {
  823. this.initSqlBuilder();
  824. this.sqlBuilder.setAndWhere('tender_id', {
  825. value: tenderId,
  826. operate: '=',
  827. });
  828. this.sqlBuilder.setAndWhere('full_path', {
  829. value: this.db.escape(deleteData.full_path + '%'),
  830. operate: 'Like',
  831. });
  832. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'delete');
  833. const result = await this.transaction.query(sql, sqlParam);
  834. return result;
  835. }
  836. /**
  837. * tenderId标段中, 删除选中节点及其子节点
  838. *
  839. * @param {Number} tenderId - 标段id
  840. * @param {Number} selectId - 选中节点id
  841. * @return {Array} - 被删除的数据
  842. */
  843. async deleteNode(tenderId, selectId) {
  844. if ((tenderId <= 0) || (selectId <= 0)) {
  845. return [];
  846. }
  847. const selectData = await this.getDataByNodeId(tenderId, selectId);
  848. if (!selectData) {
  849. throw '删除节点数据错误';
  850. }
  851. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  852. this.transaction = await this.db.beginTransaction();
  853. let deleteData = [];
  854. try {
  855. // 获取将要被删除的数据
  856. deleteData = await this.getDataByFullPath(tenderId, selectData.full_path + '%');
  857. // 删除
  858. const operate = await this._deleteNodeData(tenderId, selectData);
  859. // 选中节点--父节点 只有一个子节点时,应升级is_leaf
  860. if (parentData) {
  861. const count = await this.db.count(this.tableName, { tender_id: tenderId, ledger_pid: selectData.ledger_pid });
  862. if (count === 1) {
  863. await this.transaction.update(this.tableName, { id: parentData.id, is_leaf: true });
  864. }
  865. }
  866. // 选中节点--全部后节点 order--
  867. await this._updateSelectNextsOrder(selectData, -1);
  868. // 删除部位明细
  869. await this.transaction.delete(this.ctx.service.pos.tableName, { tid: tenderId, lid: this._.map(deleteData, 'id') });
  870. await this.ctx.service.pos.deletePosData(this.transaction, tenderId, this._.map(deleteData, 'id'));
  871. await this.transaction.commit();
  872. } catch (err) {
  873. deleteData = [];
  874. await this.transaction.rollback();
  875. throw err;
  876. }
  877. // 查询结果
  878. let updateData = [];
  879. if (deleteData.length > 0) {
  880. updateData = await this.getNextsData(tenderId, selectData.ledger_pid, selectData.order - 1);
  881. updateData = updateData ? updateData : [];
  882. if (selectData.ledger_pid !== rootId) {
  883. const updateData1 = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  884. if (updateData1.is_leaf !== parentData.is_leaf) {
  885. updateData.push(updateData1);
  886. }
  887. }
  888. }
  889. return { delete: deleteData, update: updateData };
  890. }
  891. /**
  892. * tenderId标段中, 选中节点selectId上移
  893. *
  894. * @param {Number} tenderId - 标段id
  895. * @param {Number} selectId - 选中节点id
  896. * @return {Array} - 发生改变的数据
  897. */
  898. async upMoveNode(tenderId, selectId) {
  899. if ((tenderId <= 0) || (selectId <= 0)) {
  900. return [];
  901. }
  902. const selectData = await this.getDataByNodeId(tenderId, selectId);
  903. if (!selectData) {
  904. throw '上移节点数据错误';
  905. }
  906. const preData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order - 1);
  907. if (!preData) {
  908. throw '节点不可上移';
  909. }
  910. this.transaction = await this.db.beginTransaction();
  911. try {
  912. const sData = await this.transaction.update(this.tableName, { id: selectData.id, order: selectData.order - 1 });
  913. const pData = await this.transaction.update(this.tableName, { id: preData.id, order: preData.order + 1 });
  914. await this.transaction.commit();
  915. } catch (err) {
  916. await this.transaction.rollback();
  917. throw err;
  918. }
  919. const resultData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, [selectData.order, preData.order]);
  920. return { update: resultData };
  921. }
  922. /**
  923. * tenderId标段中, 选中节点selectId下移
  924. *
  925. * @param {Number} tenderId - 标段id
  926. * @param {Number} selectId - 选中节点id
  927. * @return {Array} - 发生改变的数据
  928. */
  929. async downMoveNode(tenderId, selectId) {
  930. if ((tenderId <= 0) || (selectId <= 0)) {
  931. return [];
  932. }
  933. const selectData = await this.getDataByNodeId(tenderId, selectId);
  934. if (!selectData) {
  935. throw '下移节点数据错误';
  936. }
  937. const nextData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order + 1);
  938. if (!nextData) {
  939. throw '节点不可下移';
  940. }
  941. this.transaction = await this.db.beginTransaction();
  942. try {
  943. const sData = await this.transaction.update(this.tableName, { id: selectData.id, order: selectData.order + 1 });
  944. const pData = await this.transaction.update(this.tableName, { id: nextData.id, order: nextData.order - 1 });
  945. await this.transaction.commit();
  946. } catch (err) {
  947. await this.transaction.rollback();
  948. throw err;
  949. }
  950. const resultData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, [selectData.order, nextData.order]);
  951. return { update: resultData };
  952. }
  953. /**
  954. * 升级selectData, 同步修改所有子节点
  955. * @param {Object} selectData - 升级操作,选中节点
  956. * @return {Object}
  957. * @private
  958. */
  959. async _syncUplevelChildren(selectData) {
  960. this.initSqlBuilder();
  961. this.sqlBuilder.setAndWhere('tender_id', {
  962. value: selectData.tender_id,
  963. operate: '=',
  964. });
  965. this.sqlBuilder.setAndWhere('full_path', {
  966. value: this.db.escape(selectData.full_path + '.%'),
  967. operate: 'like',
  968. });
  969. this.sqlBuilder.setUpdateData('level', {
  970. value: 1,
  971. selfOperate: '-',
  972. });
  973. this.sqlBuilder.setUpdateData('full_path', {
  974. value: ['`full_path`', this.db.escape(selectData.ledger_pid + '.'), this.db.escape('')],
  975. literal: 'Replace',
  976. });
  977. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  978. const data = await this.transaction.query(sql, sqlParam);
  979. return data;
  980. }
  981. /**
  982. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  983. * @param {Object} selectData - 选中节点
  984. * @return {Object}
  985. * @private
  986. */
  987. async _syncUpLevelNexts(selectData) {
  988. // 查询selectData的lastChild
  989. const lastChildData = await this.getLastChildData(selectData.tender_id, selectData.ledger_id);
  990. const nextsData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order);
  991. if (nextsData && nextsData.length > 0) {
  992. // 修改nextsData pid, 排序
  993. this.initSqlBuilder();
  994. this.sqlBuilder.setUpdateData('ledger_pid', {
  995. value: selectData.ledger_id,
  996. });
  997. const orderInc = lastChildData ? lastChildData.order - selectData.order : -selectData.order;
  998. this.sqlBuilder.setUpdateData('order', {
  999. value: Math.abs(orderInc),
  1000. selfOperate: orderInc > 0 ? '+' : '-',
  1001. });
  1002. this.sqlBuilder.setAndWhere('tender_id', {
  1003. value: selectData.tender_id,
  1004. operate: '=',
  1005. });
  1006. this.sqlBuilder.setAndWhere('ledger_pid', {
  1007. value: selectData.ledger_pid,
  1008. operate: '=',
  1009. });
  1010. this.sqlBuilder.setAndWhere('order', {
  1011. value: selectData.order,
  1012. operate: '>',
  1013. });
  1014. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  1015. await this.transaction.query(sql1, sqlParam1);
  1016. // 选中节点 is_leaf应为false
  1017. if (selectData.is_leaf) {
  1018. const updateData = { id: selectData.id,
  1019. is_leaf: false,
  1020. };
  1021. await this.transaction.update(this.tableName, updateData);
  1022. }
  1023. // 修改nextsData及其子节点的full_path
  1024. const oldSubStr = this.db.escape(selectData.ledger_pid + '.');
  1025. const newSubStr = this.db.escape(selectData.ledger_id + '.');
  1026. const sqlArr = [];
  1027. sqlArr.push('Update ?? SET `full_path` = Replace(`full_path`,' + oldSubStr + ',' + newSubStr + ') Where');
  1028. sqlArr.push('(`tender_id` = ' + selectData.tender_id + ')');
  1029. sqlArr.push(' And (');
  1030. for (const data of nextsData) {
  1031. sqlArr.push('`full_path` Like ' + this.db.escape(data.full_path + '%'));
  1032. if (nextsData.indexOf(data) < nextsData.length - 1) {
  1033. sqlArr.push(' Or ');
  1034. }
  1035. }
  1036. sqlArr.push(')');
  1037. const sql = sqlArr.join('');
  1038. const resultData = await this.transaction.query(sql, [this.tableName]);
  1039. return resultData;
  1040. }
  1041. }
  1042. /**
  1043. * 升级节点
  1044. *
  1045. * @param {Number} tenderId - 标段id
  1046. * @param {Number} selectId - 选中节点id
  1047. * @return {Array} - 发生改变的数据
  1048. */
  1049. async upLevelNode(tenderId, selectId) {
  1050. if ((tenderId <= 0) || (selectId <= 0)) {
  1051. return [];
  1052. }
  1053. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1054. if (!selectData) {
  1055. throw '升级节点数据错误';
  1056. }
  1057. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  1058. if (!parentData) {
  1059. throw '升级节点数据错误';
  1060. }
  1061. this.transaction = await this.db.beginTransaction();
  1062. const newFullPath = selectData.full_path.replace(selectData.ledger_pid + '.', '');
  1063. try {
  1064. // 选中节点--父节点 选中节点为firstChild时,修改is_leaf
  1065. if (selectData.order === 1) {
  1066. await this.transaction.update(this.tableName, {
  1067. id: parentData.id,
  1068. is_leaf: true,
  1069. });
  1070. }
  1071. // 选中节点--父节点--全部后兄弟节点 order+1
  1072. await this._updateSelectNextsOrder(parentData);
  1073. // 选中节点 修改pid, order, full_path
  1074. const updateData = { id: selectData.id,
  1075. ledger_pid: parentData.ledger_pid,
  1076. order: parentData.order + 1,
  1077. level: selectData.level - 1,
  1078. full_path: newFullPath,
  1079. };
  1080. const nexts = await this.getNextsData(tenderId, parentData.ledger_id, selectData.order);
  1081. if (nexts.length > 0) {
  1082. updateData.unit_price = null;
  1083. updateData.quantity = null;
  1084. updateData.total_price = null;
  1085. updateData.deal_qty = null;
  1086. updateData.deal_tp = null;
  1087. }
  1088. await this.transaction.update(this.tableName, updateData);
  1089. // 选中节点--全部子节点(含孙) level-1, full_path变更
  1090. await this._syncUplevelChildren(selectData);
  1091. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, full_path
  1092. await this._syncUpLevelNexts(selectData);
  1093. await this.transaction.commit();
  1094. } catch (err) {
  1095. await this.transaction.rollback();
  1096. throw err;
  1097. }
  1098. // 查询修改的数据
  1099. const resultData1 = await this.getDataByFullPath(tenderId, newFullPath + '%');
  1100. const resultData2 = await this.getNextsData(tenderId, parentData.ledger_pid, parentData.order + 1);
  1101. // 默认原Parent被刷新过,不核对total_price修改
  1102. const preParent = await this.getDataByNodeId(tenderId, parentData.ledger_id);
  1103. resultData2.push(preParent);
  1104. return { update: resultData1.concat(resultData2) };
  1105. }
  1106. /**
  1107. * 降级selectData, 同步修改所有子节点
  1108. * @param {Object} selectData - 选中节点
  1109. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  1110. * @return {Promise<*>}
  1111. * @private
  1112. */
  1113. async _syncDownlevelChildren(selectData, preData) {
  1114. this.initSqlBuilder();
  1115. this.sqlBuilder.setAndWhere('tender_id', {
  1116. value: selectData.tender_id,
  1117. operate: '=',
  1118. });
  1119. this.sqlBuilder.setAndWhere('full_path', {
  1120. value: this.db.escape(selectData.full_path + '.%'),
  1121. operate: 'like',
  1122. });
  1123. this.sqlBuilder.setUpdateData('level', {
  1124. value: 1,
  1125. selfOperate: '+',
  1126. });
  1127. this.sqlBuilder.setUpdateData('full_path', {
  1128. value: ['`full_path`', this.db.escape('.' + selectData.ledger_id), this.db.escape('.' + preData.ledger_id + '.' + selectData.ledger_id)],
  1129. literal: 'Replace',
  1130. });
  1131. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  1132. const data = await this.transaction.query(sql, sqlParam);
  1133. return data;
  1134. }
  1135. /**
  1136. * 降级节点
  1137. *
  1138. * @param {Number} tenderId - 标段id
  1139. * @param {Number} selectId - 选中节点id
  1140. * @return {Array} - 发生改变的数据
  1141. */
  1142. async downLevelNode(tenderId, selectId) {
  1143. if ((tenderId <= 0) || (selectId <= 0)) {
  1144. return [];
  1145. }
  1146. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1147. if (!selectData) {
  1148. throw '降级节点数据错误';
  1149. }
  1150. const preData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order - 1);
  1151. if (!preData) {
  1152. throw '节点不可降级';
  1153. }
  1154. const preLastChildData = await this.getLastChildData(tenderId, preData.ledger_id);
  1155. this.transaction = await this.db.beginTransaction();
  1156. const orgLastPath = selectData.level === 1 ? selectData.ledger_id : '.' + selectData.ledger_id;
  1157. const newLastPath = selectData.level === 1 ? preData.ledger_id + '.' + selectData.ledger_id : '.' + preData.ledger_id + '.' + selectData.ledger_id;
  1158. const newFullPath = selectData.full_path.replace(orgLastPath, newLastPath);
  1159. try {
  1160. // 选中节点--全部后节点 order--
  1161. await this._updateSelectNextsOrder(selectData, -1);
  1162. // 选中节点 修改pid, level, order, full_path
  1163. const updateData = {
  1164. id: selectData.id,
  1165. ledger_pid: preData.ledger_id,
  1166. order: preLastChildData ? preLastChildData.order + 1 : 1,
  1167. level: selectData.level + 1,
  1168. full_path: newFullPath,
  1169. };
  1170. await this.transaction.update(this.tableName, updateData);
  1171. // 选中节点--全部子节点(含孙) level++, full_path
  1172. await this._syncDownlevelChildren(selectData, preData);
  1173. // 选中节点--前兄弟节点 is_leaf应为false, 清空计算相关字段
  1174. if (preData.is_leaf || preData.unit_price || preData.quantity || preData.total_price || preData.deal_qty || preData.deal_tp) {
  1175. const updateData2 = {
  1176. id: preData.id,
  1177. is_leaf: false,
  1178. unit_price: null,
  1179. quantity: null,
  1180. total_price: null,
  1181. deal_qty: null,
  1182. deal_tp: null,
  1183. };
  1184. await this.transaction.update(this.tableName, updateData2);
  1185. }
  1186. await this.transaction.commit();
  1187. } catch (err) {
  1188. await this.transaction.rollback();
  1189. throw err;
  1190. }
  1191. // 查询修改的数据
  1192. // 选中节点及子节点
  1193. const resultData1 = await this.getDataByFullPath(tenderId, newFullPath + '%');
  1194. // 选中节点--原前兄弟节点&全部后兄弟节点
  1195. const queryOrder = (preData.is_leaf || this.ctx.helper.checkZero(selectData.total_price)) ? preData.order - 1 : preData.order;
  1196. const resultData2 = await this.getNextsData(tenderId, preData.ledger_pid, queryOrder);
  1197. return { update: resultData1.concat(resultData2) };
  1198. }
  1199. /**
  1200. * 过滤data中update方式不可提交的字段
  1201. * @param {Number} id - 主键key
  1202. * @param {Object} data
  1203. * @return {Object<{id: *}>}
  1204. * @private
  1205. */
  1206. _filterUpdateInvalidField(id, data) {
  1207. const result = {
  1208. id,
  1209. };
  1210. for (const prop in data) {
  1211. if (readOnlyFields.indexOf(prop) === -1) {
  1212. result[prop] = data[prop];
  1213. }
  1214. }
  1215. return result;
  1216. }
  1217. /**
  1218. * newData中,以orgData为基准,过滤掉orgData中未定义或值相等的部分
  1219. * @param {Object} orgData
  1220. * @param {Object} newData
  1221. * @private
  1222. */
  1223. _filterChangedField(orgData, newData) {
  1224. const result = {};
  1225. let bChanged = false;
  1226. for (const prop in orgData) {
  1227. if (this._.isEmpty(newData[prop]) && newData[prop] !== orgData[prop]) {
  1228. result[prop] = newData[prop];
  1229. bChanged = true;
  1230. }
  1231. }
  1232. return bChanged ? result : undefined;
  1233. }
  1234. _checkField(data, field) {
  1235. const fields = field instanceof Array ? field : [field];
  1236. for (const prop in data) {
  1237. if (fields.indexOf(prop) >= 0) {
  1238. return true;
  1239. }
  1240. }
  1241. return false;
  1242. }
  1243. /**
  1244. * 检查data中是否含有计算字段
  1245. * @param {Object} data
  1246. * @return {boolean}
  1247. * @private
  1248. */
  1249. _checkCalcField(data) {
  1250. for (const prop in data) {
  1251. if (calcFields.indexOf(prop) >= 0) {
  1252. return true;
  1253. }
  1254. }
  1255. return false;
  1256. }
  1257. /**
  1258. * 提交数据 - 不影响计算等未提交项
  1259. * @param {Number} tenderId - 标段id
  1260. * @param {Object} data - 提交数据
  1261. * @return {Object} - 提交后的数据
  1262. */
  1263. async updateInfo(tenderId, data) {
  1264. // 简单校验数据
  1265. if (tenderId <= 0) {
  1266. throw '标段不存在';
  1267. }
  1268. if (tenderId !== data.tender_id) {
  1269. throw '提交数据错误';
  1270. }
  1271. try {
  1272. // 过滤不可提交字段
  1273. const updateNode = await this.getDataById(data.id);
  1274. if (!updateNode || tenderId !== updateNode.tender_id || data.ledger_id !== updateNode.ledger_id) {
  1275. throw '提交数据错误';
  1276. }
  1277. const updateData = this._filterUpdateInvalidField(updateNode.id, data);
  1278. await this.db.update(this.tableName, updateData);
  1279. } catch (err) {
  1280. throw err;
  1281. }
  1282. const result = await this.getDataByNodeId(tenderId, data.ledger_id);
  1283. return result;
  1284. }
  1285. /**
  1286. * 提交多条数据 - 不影响计算等未提交项
  1287. * @param {Number} tenderId - 标段id
  1288. * @param {Array} datas - 提交数据
  1289. * @return {Array} - 提交后的数据
  1290. */
  1291. async updateInfos(tenderId, datas) {
  1292. if (tenderId <= 0) {
  1293. throw '标段不存在';
  1294. }
  1295. for (const data of datas) {
  1296. if (tenderId !== data.tender_id) {
  1297. throw '提交数据错误';
  1298. }
  1299. }
  1300. this.transaction = await this.db.beginTransaction();
  1301. try {
  1302. for (const data of datas) {
  1303. const updateNode = await this.getDataById(data.id);
  1304. if (!updateNode || tenderId !== updateNode.tender_id || data.ledger_id !== updateNode.ledger_id) {
  1305. throw '提交数据错误';
  1306. }
  1307. const updateData = this._filterUpdateInvalidField(updateNode.id, data);
  1308. await this.transaction.update(this.tableName, updateData);
  1309. }
  1310. await this.transaction.commit();
  1311. } catch (err) {
  1312. await this.transaction.rollback();
  1313. throw err;
  1314. }
  1315. const filter = [];
  1316. for (const data of datas) {
  1317. filter.push(data.id);
  1318. }
  1319. this.initSqlBuilder();
  1320. this.sqlBuilder.setAndWhere('id', {
  1321. value: filter,
  1322. operate: 'in',
  1323. });
  1324. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  1325. const resultData = await this.db.query(sql, sqlParam);
  1326. return resultData;
  1327. }
  1328. /**
  1329. * 复制粘贴整块
  1330. * @param {Number} tenderId - 标段Id
  1331. * @param {Number} selectId - 选中几点Id
  1332. * @param {Array} block - 复制节点Id
  1333. * @return {Object} - 提价后的数据(其中新增粘贴数据,只返回第一层)
  1334. */
  1335. async pasteBlock(tenderId, selectId, block) {
  1336. if ((tenderId <= 0) || (selectId <= 0)) {
  1337. return [];
  1338. }
  1339. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1340. if (!selectData) {
  1341. throw '位置数据错误';
  1342. }
  1343. const newParentPath = selectData.full_path.replace(selectData.ledger_id, '');
  1344. const copyNodes = await this.getDataByNodeIds(tenderId, block);
  1345. if (!copyNodes || copyNodes.length <= 0) {
  1346. throw '复制数据错误';
  1347. }
  1348. let bSameParent = true;
  1349. for (const node of copyNodes) {
  1350. if (node.ledger_pid !== copyNodes[0].ledger_pid) {
  1351. bSameParent = false;
  1352. break;
  1353. }
  1354. }
  1355. if (!bSameParent) {
  1356. throw '复制数据错误:仅可操作同层节点';
  1357. }
  1358. const orgParentPath = copyNodes[0].full_path.replace(copyNodes[0].ledger_id, '');
  1359. const newIds = [];
  1360. this.transaction = await this.db.beginTransaction();
  1361. try {
  1362. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1363. await this._updateSelectNextsOrder(selectData, copyNodes.length);
  1364. // 数据库创建新增节点数据
  1365. for (const node of copyNodes) {
  1366. const datas = await this.getDataByFullPath(tenderId, node.full_path + '%');
  1367. const cacheKey = keyPre + tenderId;
  1368. let maxId = parseInt(await this.cache.get(cacheKey));
  1369. if (!maxId) {
  1370. maxId = await this._getMaxNodeId(tenderId);
  1371. }
  1372. this.cache.set(cacheKey, maxId + datas.length, 'EX', this.ctx.app.config.cacheTime);
  1373. const leafBillsId = [];
  1374. // 计算粘贴数据中需更新部分
  1375. for (let index = 0; index < datas.length; index++) {
  1376. const data = datas[index];
  1377. const newId = maxId + index + 1;
  1378. const idChange = {
  1379. org: data.id,
  1380. };
  1381. delete data.id;
  1382. if (!data.is_leaf) {
  1383. for (const children of datas) {
  1384. children.full_path = children.full_path.replace('.' + data.ledger_id, '.' + newId);
  1385. if (children.ledger_pid === data.ledger_id) {
  1386. children.ledger_pid = newId;
  1387. }
  1388. }
  1389. } else {
  1390. data.full_path = data.full_path.replace('.' + data.ledger_id, '.' + newId);
  1391. }
  1392. data.ledger_id = newId;
  1393. data.full_path = data.full_path.replace(orgParentPath, newParentPath);
  1394. if (data.ledger_pid === copyNodes[0].ledger_pid) {
  1395. data.ledger_pid = selectData.ledger_pid;
  1396. data.order = selectData.order + index + 1;
  1397. }
  1398. data.level = data.level + selectData.level - copyNodes[0].level;
  1399. const newData = await this.transaction.insert(this.tableName, data);
  1400. if (data.is_leaf) {
  1401. idChange.new = newData.insertId;
  1402. leafBillsId.push(idChange);
  1403. }
  1404. newIds.push(newData.insertId);
  1405. }
  1406. for (const id of leafBillsId) {
  1407. await this.ctx.service.pos.copyBillsPosData(id.org, id.new, this.transaction);
  1408. }
  1409. }
  1410. await this.transaction.commit();
  1411. } catch (err) {
  1412. await this.transaction.rollback();
  1413. throw err;
  1414. }
  1415. // 查询应返回的结果
  1416. const order = [];
  1417. for (let i = 1; i <= copyNodes.length; i++) {
  1418. order.push(selectData.order + i);
  1419. }
  1420. const createData = await this.getDataByIds(newIds);
  1421. const updateData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + copyNodes.length);
  1422. const posData = await this.ctx.service.pos.getPosData({ lid: newIds });
  1423. return {
  1424. ledger: { create: createData, update: updateData },
  1425. pos: posData,
  1426. };
  1427. }
  1428. /**
  1429. * 增量更新父项金额
  1430. * @param {Number} tenderId - 标段id
  1431. * @param {Object} updateMap - 增量更新数,使用更新父项的full_path为索引
  1432. * e.g: {'1.2.6.8': 30, '1.2.6.10': 40}表示'1.2.6.8'增量30,'1.2.6.10'增量40(此处同步更新'1.2.6', '1.2', '1')
  1433. * @return {Promise<void>}
  1434. * @private
  1435. */
  1436. async _increCalcParent(tenderId, updateMap) {
  1437. for (const prop in updateMap) {
  1438. this.initSqlBuilder();
  1439. this.sqlBuilder.setAndWhere('tender_id', {
  1440. value: tenderId,
  1441. operate: '=',
  1442. });
  1443. const fullPath = this.ctx.helper.explodePath(prop);
  1444. this.sqlBuilder.setAndWhere('full_path', {
  1445. value: this.ctx.helper.explodePath(prop),
  1446. operate: 'in',
  1447. });
  1448. this.sqlBuilder.setUpdateData('total_price', {
  1449. value: updateMap[prop] > 0 ? updateMap[prop] : -updateMap[prop],
  1450. selfOperate: updateMap[prop] > 0 ? '+' : '-',
  1451. });
  1452. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  1453. await this.transaction.query(sql, sqlParam);
  1454. }
  1455. }
  1456. /**
  1457. * 提交数据 - 响应计算(增量方式计算)
  1458. * @param {Number} tenderId
  1459. * @param {Object} data
  1460. * @return {Promise<*>}
  1461. */
  1462. async updateCalc(tenderId, data) {
  1463. // 简单验证数据
  1464. if (tenderId <= 0) {
  1465. throw '标段不存在';
  1466. }
  1467. if (!data) {
  1468. throw '提交数据错误';
  1469. }
  1470. const datas = data instanceof Array ? data : [data];
  1471. const ids = [];
  1472. for (const row of datas) {
  1473. if (tenderId !== row.tender_id) {
  1474. throw '提交数据错误';
  1475. }
  1476. ids.push(row.id);
  1477. }
  1478. this.transaction = await this.db.beginTransaction();
  1479. try {
  1480. for (const row of datas) {
  1481. const updateNode = await this.getDataById(row.id);
  1482. if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  1483. throw '提交数据错误';
  1484. }
  1485. let updateData;
  1486. if (row.unit) {
  1487. if (!row.quantity) { row.quantity = updateNode.quantity; }
  1488. if (!row.deal_qty) { row.deal_qty = updateNode.deal_qty; }
  1489. }
  1490. if (this._checkCalcField(row)) {
  1491. let calcData = JSON.parse(JSON.stringify(row));
  1492. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, row.unit ? row.unit : updateNode.unit);
  1493. // 数量保留小数位数
  1494. this.ctx.helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  1495. // 单位保留小数位数
  1496. this.ctx.helper.checkFieldPrecision(calcData, upFields, this.ctx.tender.info.decimal.up);
  1497. // 计算
  1498. if (row.quantity !== undefined) {
  1499. if (row.unit_price !== undefined) {
  1500. calcData.total_price = this.ctx.helper.times(calcData.quantity, calcData.unit_price);
  1501. } else {
  1502. calcData.total_price = this.ctx.helper.times(calcData.quantity, updateNode.unit_price);
  1503. }
  1504. } else if (row.unit_price !== undefined) {
  1505. calcData.total_price = this.ctx.helper.times(updateNode.quantity, calcData.unit_price);
  1506. }
  1507. if (row.total_price !== undefined) {
  1508. calcData.quantity = null;
  1509. }
  1510. if (row.deal_qty !== undefined) {
  1511. if (row.unit_price !== undefined) {
  1512. calcData.deal_tp = this.ctx.helper.times(calcData.deal_qty, calcData.unit_price);
  1513. } else {
  1514. calcData.deal_tp = this.ctx.helper.times(calcData.deal_qty, updateNode.unit_price);
  1515. }
  1516. } else if (row.unit_price !== undefined) {
  1517. calcData.deal_tp = this.ctx.helper.times(updateNode.deal_qty, calcData.unit_price);
  1518. }
  1519. if (row.deal_tp !== undefined) {
  1520. calcData.deal_qty = null;
  1521. }
  1522. updateData = this._filterUpdateInvalidField(updateNode.id, calcData);
  1523. } else {
  1524. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  1525. }
  1526. await this.transaction.update(this.tableName, updateData);
  1527. }
  1528. await this.transaction.commit();
  1529. } catch (err) {
  1530. await this.transaction.rollback();
  1531. throw err;
  1532. }
  1533. return { update: await this.getDataByIds(ids) };
  1534. }
  1535. /**
  1536. *
  1537. * @param tenderId
  1538. * @param xmj
  1539. * @param order
  1540. * @param parentData
  1541. * @return {Promise<*[]>}
  1542. * @private
  1543. */
  1544. async _sortBatchInsertData(tenderId, xmj, order, parentData) {
  1545. const result = [],
  1546. newIds = [];
  1547. let tp = 0;
  1548. const cacheKey = keyPre + tenderId;
  1549. let maxId = parseInt(await this.cache.get(cacheKey));
  1550. if (!maxId) {
  1551. maxId = await this._getMaxNodeId(tenderId);
  1552. }
  1553. this.cache.set(cacheKey, maxId + xmj.children.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1554. // 添加xmj数据
  1555. const parent = {
  1556. tender_id: tenderId,
  1557. ledger_id: maxId + 1,
  1558. ledger_pid: parentData.ledger_id,
  1559. is_leaf: xmj.children.length === 0,
  1560. order,
  1561. level: parentData.level + 1,
  1562. name: xmj.name,
  1563. };
  1564. parent.full_path = parentData.full_path + '.' + parent.ledger_id;
  1565. // 添加gcl数据
  1566. for (let i = 0, iLen = xmj.children.length; i < iLen; i++) {
  1567. const gcl = xmj.children[i];
  1568. const child = {
  1569. tender_id: tenderId,
  1570. ledger_id: maxId + 1 + i + 1,
  1571. ledger_pid: parent.ledger_id,
  1572. is_leaf: true,
  1573. order: i + 1,
  1574. level: parent.level + 1,
  1575. b_code: gcl.b_code,
  1576. name: gcl.name,
  1577. unit: gcl.unit,
  1578. unit_price: gcl.unit_price,
  1579. quantity: gcl.quantity,
  1580. };
  1581. child.full_path = parent.full_path + '.' + child.ledger_id;
  1582. child.total_price = child.unit_price * child.quantity;
  1583. tp = tp + child.total_price;
  1584. result.push(child);
  1585. newIds.push(child.ledger_id);
  1586. }
  1587. parent.total_price = tp;
  1588. result.push(parent);
  1589. newIds.push(parent.ledger_id);
  1590. return [result, tp, newIds];
  1591. }
  1592. /**
  1593. * 批量插入子项
  1594. * @param {Number} tenderId - 标段Id
  1595. * @param {Number} selectId - 选中节点Id
  1596. * @param {Object} data - 批量插入数据
  1597. * @return {Promise<void>}
  1598. */
  1599. async batchInsertChild(tenderId, selectId, data) {
  1600. const result = { ledger: {}, pos: null };
  1601. if ((tenderId <= 0) || (selectId <= 0)) {
  1602. return result;
  1603. }
  1604. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1605. if (!selectData) {
  1606. throw '位置数据错误';
  1607. }
  1608. this.transaction = await this.db.beginTransaction();
  1609. const newIds = [];
  1610. try {
  1611. const lastChild = await this.getLastChildData(tenderId, selectId);
  1612. // 更新父项isLeaf
  1613. if (!lastChild) {
  1614. await this.transaction.update(this.tableName, {
  1615. id: selectData.id,
  1616. is_leaf: false,
  1617. });
  1618. }
  1619. const order = lastChild ? lastChild.order : 0;
  1620. // 计算id
  1621. const cacheKey = keyPre + tenderId;
  1622. let maxId = parseInt(await this.cache.get(cacheKey));
  1623. if (!maxId) {
  1624. maxId = await this._getMaxNodeId(tenderId);
  1625. }
  1626. // 数据库创建新增节点数据
  1627. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1628. // 合并新增数据
  1629. const qd = {
  1630. tender_id: tenderId,
  1631. ledger_id: maxId + i + 1,
  1632. ledger_pid: selectData.ledger_id,
  1633. is_leaf: true,
  1634. order: order + i + 1,
  1635. level: selectData.level + 1,
  1636. b_code: data[i].b_code,
  1637. name: data[i].name,
  1638. unit: data[i].unit,
  1639. unit_price: data[i].price,
  1640. };
  1641. qd.full_path = selectData.full_path + '.' + qd.ledger_id;
  1642. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, qd.unit);
  1643. this.ctx.helper.checkFieldPrecision(qd, qtyFields, precision.value);
  1644. const insertResult = await this.transaction.insert(this.tableName, qd);
  1645. qd.id = insertResult.insertId;
  1646. newIds.push(insertResult.insertId);
  1647. if (data[i].pos.length > 0) {
  1648. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  1649. await this.calc(tenderId, insertResult.insertId, this.transaction);
  1650. }
  1651. }
  1652. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1653. await this.transaction.commit();
  1654. } catch (err) {
  1655. await this.transaction.rollback();
  1656. throw err;
  1657. }
  1658. // 查询应返回的结果
  1659. result.ledger.create = await this.getDataByIds(newIds);
  1660. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1661. return result;
  1662. }
  1663. /**
  1664. * 批量插入后项
  1665. * @param {Number} tenderId - 标段Id
  1666. * @param {Number} selectId - 选中节点Id
  1667. * @param {Object} data - 批量插入数据
  1668. * @return {Promise<void>}
  1669. */
  1670. async batchInsertNext(tenderId, selectId, data) {
  1671. const result = { ledger: {}, pos: null };
  1672. if ((tenderId <= 0) || (selectId <= 0)) {
  1673. return result;
  1674. }
  1675. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1676. if (!selectData) {
  1677. throw '位置数据错误';
  1678. }
  1679. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  1680. if (!parentData) {
  1681. throw '位置数据错误';
  1682. }
  1683. this.transaction = await this.db.beginTransaction();
  1684. const newIds = [];
  1685. try {
  1686. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1687. await this._updateSelectNextsOrder(selectData, data.length);
  1688. // 计算id和order
  1689. const cacheKey = keyPre + tenderId;
  1690. let maxId = parseInt(await this.cache.get(cacheKey));
  1691. if (!maxId) {
  1692. maxId = await this._getMaxNodeId(tenderId);
  1693. }
  1694. const order = selectData.order;
  1695. // 数据库创建新增节点数据
  1696. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1697. // 合并新增数据
  1698. const qd = {
  1699. tender_id: tenderId,
  1700. ledger_id: maxId + i + 1,
  1701. ledger_pid: parentData.ledger_id,
  1702. is_leaf: true,
  1703. order: order + i + 1,
  1704. level: parentData.level + 1,
  1705. b_code: data[i].b_code,
  1706. name: data[i].name,
  1707. unit: data[i].unit,
  1708. unit_price: data[i].price,
  1709. };
  1710. qd.full_path = parentData.full_path + '.' + qd.ledger_id;
  1711. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, qd.unit);
  1712. this.ctx.helper.checkFieldPrecision(qd, qtyFields, precision.value);
  1713. const insertResult = await this.transaction.insert(this.tableName, qd);
  1714. qd.id = insertResult.insertId;
  1715. newIds.push(insertResult.insertId);
  1716. if (data[i].pos.length > 0) {
  1717. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  1718. await this.calc(tenderId, insertResult.insertId, this.transaction);
  1719. }
  1720. }
  1721. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1722. await this.transaction.commit();
  1723. } catch (err) {
  1724. await this.transaction.rollback();
  1725. throw err;
  1726. }
  1727. // 查询应返回的结果
  1728. result.ledger.create = await this.getDataByIds(newIds);
  1729. result.ledger.update = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + data.length);
  1730. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1731. return result;
  1732. }
  1733. /**
  1734. *
  1735. * @param {Number} tid - 标段id
  1736. * @param {Number} id - 需要计算的节点的id
  1737. * @param {Object} transaction - 操作所属事务,没有则创建
  1738. * @return {Promise<void>}
  1739. */
  1740. async calc(tid, id, transaction) {
  1741. const node = await this.getAllDataByCondition({ id });
  1742. if (!node) {
  1743. throw '数据错误';
  1744. }
  1745. const calcQtySql = 'UPDATE ??' +
  1746. ' SET `quantity` = (SELECT SUM(`quantity`) FROM ?? WHERE `lid` = ?), `total_price` = `quantity` * `unit_price`' +
  1747. ' WHERE `id` = ?';
  1748. await transaction.query(this.db.format(calcQtySql, [this.tableName, this.ctx.service.pos.tableName, id, id]));
  1749. }
  1750. /**
  1751. * 查找定位 --> 废弃
  1752. * @param tenderId
  1753. * @param nodeId
  1754. * @return {Promise<{expand: *}>}
  1755. */
  1756. async locateNode(tenderId, nodeId) {
  1757. const node = await this.getDataByNodeId(tenderId, nodeId);
  1758. if (!node) {
  1759. throw '查询数据有误';
  1760. }
  1761. const expandIds = node.full_path.split('.');
  1762. expandIds.pop();
  1763. const expandData = await this.getChildrenByParentId(tenderId, expandIds);
  1764. return { expand: expandData };
  1765. }
  1766. async _importCacheTreeNode(transaction, node) {
  1767. const data = {
  1768. tender_id: this.ctx.tender.id,
  1769. ledger_id: node.ledger_id,
  1770. ledger_pid: node.ledger_pid,
  1771. level: node.level,
  1772. order: node.order,
  1773. is_leaf: !node.children || node.children.length === 0,
  1774. full_path: node.full_path,
  1775. code: node.code,
  1776. b_code: node.b_code,
  1777. name: node.name,
  1778. unit: node.unit,
  1779. quantity: node.quantity,
  1780. unit_price: node.unit_price,
  1781. total_price: node.total_price,
  1782. dgn_qty1: node.dgn_qty1,
  1783. dgn_qty2: node.dgn_qty2,
  1784. memo: node.memo,
  1785. drawing_code: node.drawing_code,
  1786. };
  1787. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, data.unit);
  1788. this.ctx.helper.checkFieldPrecision(data, qtyFields, precision.value);
  1789. const result = await transaction.insert(this.tableName, data);
  1790. data.id = result.insertId;
  1791. if (node.children && node.children.length > 0) {
  1792. for (const child of node.children) {
  1793. await this._importCacheTreeNode(transaction, child);
  1794. }
  1795. } else if (node.pos && node.pos.length > 0) {
  1796. await this.ctx.service.pos.insertLedgerPosData(transaction, this.ctx.tender.id, data, node.pos);
  1797. }
  1798. }
  1799. /**
  1800. * 导入Excel数据
  1801. * @param excelData
  1802. * @returns {Promise<void>}
  1803. */
  1804. async importExcel(excelData) {
  1805. const AnalysisExcel = require('../lib/analysis_excel');
  1806. const analysisExcel = new AnalysisExcel();
  1807. const tempData = await this.ctx.service.tenderNodeTemplate.getData(true);
  1808. const cacheTree = analysisExcel.analysisData(excelData, tempData);
  1809. const cacheKey = keyPre + this.ctx.tender.id;
  1810. const orgMaxId = parseInt(await this.cache.get(cacheKey));
  1811. const transaction = await this.db.beginTransaction();
  1812. try {
  1813. await transaction.delete(this.tableName, {tender_id: this.ctx.tender.id});
  1814. await transaction.delete(this.ctx.service.pos.tableName, {tid: this.ctx.tender.id});
  1815. for (const node of cacheTree.roots) {
  1816. await this._importCacheTreeNode(transaction, node);
  1817. }
  1818. await transaction.commit();
  1819. this.cache.set(cacheKey, cacheTree.items.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1820. } catch (err) {
  1821. await transaction.rollback();
  1822. if (orgMaxId) {
  1823. this.cache.set(cacheKey, orgMaxId, 'EX', this.ctx.app.config.cacheTime);
  1824. }
  1825. throw err;
  1826. }
  1827. }
  1828. }
  1829. return Ledger;
  1830. };