ledger.js 77 KB

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