ledger.js 67 KB

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