ledger.js 77 KB

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