tree_expr_calc.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const TreeExprCalc = (function(){
  10. const calcRela = {
  11. calcType: {zero: 0, direct: 1, cache: 2, sortCache: 4},
  12. SerialReg: new RegExp('<<f[0-9]+\\$[a-z]+>>', 'ig'),
  13. SerialFirstReg: new RegExp('^<<f[0-9]+\\$[a-z]+>>', 'i'),
  14. IdReg: new RegExp('<<[a-z0-9\-]+\\$[a-z]+>>', 'ig'),
  15. OrderReg: new RegExp('f[0-9]+', 'ig'),
  16. valueChar: '$',
  17. calcCache: {},
  18. error: { loop: '', deep: '' },
  19. // 计算必须项
  20. tree: null,
  21. decimal: null,
  22. calcField: null,
  23. getCalcNum: null,
  24. calcCacheFun: null,
  25. exprCacheKey: [],
  26. exprFieldsIndex: {},
  27. exprCacheFields: [],
  28. errorMsg: true,
  29. };
  30. const getCalcField = function(value) {
  31. return calcRela.exprFieldsIndex[value];
  32. };
  33. const init = function(setting) {
  34. calcRela.tree = setting.tree;
  35. calcRela.decimal = setting.decimal || { qty: 2, tp: 0 };
  36. calcRela.calcField = setting.calcField || { qty: 'quantity', tp: 'total_price' };
  37. setCalcType(setting.calcType || calcRela.calcType.zero);
  38. calcRela.calcCacheFun = setting.calcCacheFun;
  39. if (setting.exprFieldsIndex) calcRela.exprFieldsIndex = setting.exprFieldsIndex;
  40. if (setting.exprCacheKey) {
  41. calcRela.exprCacheKey = setting.exprCacheKey;
  42. calcRela.exprCacheFields = calcRela.exprCacheKey.map(x => { return getCalcField(x); });
  43. }
  44. calcRela.errorMsg = setting.errorMsg || true;
  45. };
  46. const checkExprValid = function(expr, invalidOrders = []) {
  47. if (!expr) return [true, ''];
  48. const param = [];
  49. let num = '';
  50. for (let i = 0, iLen = expr.length; i < iLen; i++) {
  51. const subExpr = expr.substring(i, expr.length);
  52. if (/^[\d\.%]+/.test(expr[i])) {
  53. num = num + expr[i];
  54. } else if (calcRela.SerialFirstReg.test(subExpr)) {
  55. if (num !== '') {
  56. param.push({type: 'num', value: num});
  57. num = '';
  58. }
  59. const order = calcRela.SerialFirstReg.exec(subExpr);
  60. param.push({type: 'order', value: order[0]});
  61. i = i + order[0].length - 1;
  62. } else if (expr[i] === '(') {
  63. if (num !== '') {
  64. param.push({type: 'num', value: num});
  65. num = '';
  66. }
  67. param.push({type: 'left', value: '('});
  68. } else if (expr[i] === ')') {
  69. if (num !== '') {
  70. param.push({type: 'num', value: num});
  71. num = '';
  72. }
  73. param.push({type: 'right', value: ')'});
  74. } else if (/^[\+\-*\/]/.test(expr[i])) {
  75. if (num !== '') {
  76. param.push({type: 'num', value: num});
  77. num = '';
  78. }
  79. param.push({type: 'calc', value: expr[i]});
  80. } else {
  81. return [false, '输入的表达式含有非法字符: ' + expr[i]];
  82. }
  83. }
  84. if (num !== '') {
  85. param.push({type: 'num', value: num});
  86. num = '';
  87. }
  88. if (param.length === 0) return [true, ''];
  89. if (param.length > 1) {
  90. if (param[0].value === '-' && param[1].type === 'num') {
  91. param[1].value = '-' + param[1].value;
  92. param.shift();
  93. }
  94. }
  95. const iLen = param.length;
  96. let iLeftCount = 0, iRightCount = 0;
  97. for (const [i, p] of param.entries()) {
  98. if (p.type === 'calc') {
  99. if (i === 0 || i === iLen - 1)
  100. return [false, '输入的表达式非法:计算符号' + p.value + '前后应有数字或计算基数'];
  101. }
  102. if (p.type === 'num') {
  103. num = p.value.replace('%', '');
  104. if (p.value.length - num.length > 1)
  105. return [false, '输入的表达式非法:' + p.value + '不是一个有效的数字'];
  106. num = _.toNumber(num);
  107. if (num === undefined || num === null || _.isNaN(num))
  108. return [false, '输入的表达式非法:' + p.value + '不是一个有效的数字'];
  109. if (i > 0) {
  110. if (param[i - 1].type !== 'calc' && param[i - 1].type !== 'left') {
  111. return [false, '输入的表达式非法:' + p.value + '前应有运算符'];
  112. } else if (param[i - 1].value === '/' && num === 0) {
  113. return [false, '输入的表达式非法:请勿除0'];
  114. }
  115. }
  116. }
  117. if (p.type === 'order') {
  118. const match = invalidOrders.find(x => { p.value.indexOf(`f${x.orderStr}$`) > 0; });
  119. if (match) return [false, `输入的表达式非法:循环引用,请勿引用${match.orderStr}`];
  120. if (i > 0) {
  121. if (param[i - 1].type !== 'calc' && param[i - 1].type !== 'left') {
  122. return [false, '输入的表达式非法:' + p.value.replace(/</ig, '&lt;').replace(/>/ig, '&gt;') + '前应有运算符'];
  123. }
  124. }
  125. }
  126. if (p.type === 'left') {
  127. iLeftCount += 1;
  128. if (i !== 0 && param[i-1].type !== 'calc')
  129. return [false, '输入的表达式非法:(前应有运算符'];
  130. }
  131. if (p.type === 'right') {
  132. iRightCount += 1;
  133. if (i !== iLen - 1 && param[i+1].type !== 'calc')
  134. return [false, '输入的表达式非法:)后应有运算符'];
  135. if (iRightCount > iLeftCount)
  136. return [false, '输入的表达式非法:")"前无对应的"("'];
  137. }
  138. }
  139. if (iLeftCount > iRightCount)
  140. return [false, '输入的表达式非法:"("后无对应的")"'];
  141. return [true, ''];
  142. };
  143. const _getCalcNumZero = function (node, field) {
  144. return node.calc_expr && calcRela.exprInitFields.indexOf(field) >= 0 ? 0 : node[field] || 0;
  145. };
  146. const _getCalcNumDirect = function (node, field) {
  147. return node[field] || 0;
  148. };
  149. const _getCalcNumCache = function (node, field) {
  150. if (node.calc_expr && calcRela.exprCacheFields.indexOf(field) >= 0) {
  151. return calcRela.calcCache[node.id] ? calcRela.calcCache[node.id][field] || 0 : 0;
  152. }
  153. return node[field] || 0;
  154. };
  155. const getIdParamValue = function(idParam) {
  156. const [id, value] = idParam.substring(2, idParam.length - 2).split(calcRela.valueChar);
  157. const node = calcRela.tree.nodes.find(x => { return x.id === id; });
  158. if (!node) return 0;
  159. const calcField = getCalcField(value);
  160. if (!node.children || node.children.length === 0) {
  161. return calcRela.getCalcNum(node, calcField);
  162. } else {
  163. const posterity = calcRela.tree.getLeafPosterity(node);
  164. const calcMap = posterity.map(x => { return calcRela.getCalcNum(x, calcField) });
  165. return ZhCalc.sum(calcMap);
  166. }
  167. };
  168. const calcExpr = function(expr) {
  169. if (!expr) return 0;
  170. let formula = expr;
  171. const idParam = expr.match(calcRela.IdReg);
  172. if (idParam) {
  173. for (const ip of idParam) {
  174. formula = formula.replace(ip, getIdParamValue(ip));
  175. }
  176. }
  177. return [formula, math.evaluate(formula)];
  178. };
  179. const addCache = function(expr) {
  180. const cache = { id: expr.id };
  181. if (expr.calcField === 'qty') {
  182. cache[calcRela.calcField.qty] = ZhCalc.round(expr.value, calcRela.decimal.qty);
  183. cache[calcRela.calcField.tp] = ZhCalc.mul(cache[calcRela.calcField.qty], expr.unit_price, calcRela.decimal.tp);
  184. } else if (expr.calcField === 'tp') {
  185. cache[calcRela.calcField.qty] = 0;
  186. cache[calcRela.calcField.tp] = ZhCalc.round(expr.value, calcRela.decimal.tp);
  187. }
  188. if (calcRela.calcCacheFun) calcRela.calcCacheFun(cache, expr);
  189. calcRela.calcCache[expr.id] = cache;
  190. };
  191. const sortExprList = function(exprList) {
  192. const exprIds = exprList.map(x => { return x.id; });
  193. exprList.forEach(x => {
  194. x.sort = calcRela.tree.nodes.findIndex(n => { return n.id === x.id; });
  195. x.relaExprId = [];
  196. const idParam = x.expr.match(calcRela.IdReg);
  197. if (idParam) {
  198. for (const ip of idParam) {
  199. const [id, value] = ip.substring(2, ip.length - 2).split(calcRela.valueChar);
  200. if (value.indexOf('bq') < 0) continue;
  201. const node = calcRela.tree.nodes.find(x => { return x.id === id; });
  202. if (!node) continue;
  203. if (!node.children || node.children.length === 0) {
  204. if (exprIds.indexOf(node.id) >= 0) x.relaExprId.push(node.id);
  205. } else {
  206. const posterity = calcRela.tree.getLeafPosterity(node);
  207. posterity.forEach(p => { if (exprIds.indexOf(p.id) >= 0) x.relaExprId.push(p.id); });
  208. }
  209. }
  210. }
  211. });
  212. exprList.forEach(x => {
  213. if (x.relaExprId.length === 0) {
  214. x.calcSort = 1;
  215. return;
  216. }
  217. let calcSort = 1;
  218. let calcExprId = [...x.relaExprId];
  219. while (calcExprId.length > 0 && calcSort <= 100) {
  220. const sortIds = [];
  221. for (const id of calcExprId) {
  222. const relaNode = exprList.find(y => { return y.id === id; });
  223. if (relaNode.relaExprId.length > 0) {
  224. sortIds.push(...relaNode.relaExprId);
  225. }
  226. }
  227. calcSort++;
  228. if (sortIds.indexOf(x.id) >= 0) {
  229. calcSort = 'max';
  230. break;
  231. }
  232. calcExprId = sortIds;
  233. }
  234. if (calcSort > 100 && !calcRela.error.deep) calcRela.error.deep = x.id;
  235. if (calcSort === 'max' && !calcRela.error.loop) calcRela.error.loop = x.id;
  236. x.calcSort = calcSort;
  237. });
  238. exprList.sort((x, y) => {
  239. if (x.calcSort === 'max') return 1000;
  240. if (x.calcSort === 'max') return -1000;
  241. return x.calcSort - y.calcSort;
  242. });
  243. };
  244. const _initCache = function() {
  245. calcRela.calcCache = {};
  246. calcRela.error.deep = '';
  247. calcRela.error.loop = '';
  248. };
  249. const checkError = function() {
  250. if (!calcRela.errorMsg) return;
  251. if (calcRela.error.loop) {
  252. const nodeIndex = calcRela.tree.nodes.findIndex(x => { return x.id === calcRela.error.loop; });
  253. const node = calcRela.tree.nodes[nodeIndex];
  254. const hintCode = (node.code || '') + (node.b_code || '');
  255. toastr.warning(`第${nodeIndex + 1}行 ${hintCode} 公式存在循环计算,请检查`);
  256. return;
  257. }
  258. if (calcRela.error.deep) {
  259. const nodeIndex = calcRela.tree.nodes.findIndex(x => { return x.id === calcRela.error.deep; });
  260. const node = calcRela.tree.nodes[nodeIndex];
  261. const hintCode = (node.code || '') + (node.b_code || '');
  262. toastr.warning(`第${nodeIndex + 1}行 ${hintCode} 公式引用层次过深,请检查`);
  263. return;
  264. }
  265. };
  266. const calcAllExpr = function(exprList) {
  267. _initCache();
  268. if (calcRela.sort) sortExprList(exprList);
  269. for (const expr of exprList) {
  270. [expr.formula, expr.value] = calcExpr(expr.expr);
  271. addCache(expr);
  272. }
  273. checkError();
  274. const result = JSON.parse(JSON.stringify(calcRela.error));
  275. _initCache();
  276. return result;
  277. };
  278. const expr2ExprStr = function(expr) {
  279. if (!expr) return '';
  280. let formula = expr;
  281. const idParam = expr.match(calcRela.IdReg);
  282. if (idParam) {
  283. for (const ip of idParam) {
  284. const [id, value] = ip.substring(2, ip.length - 2).split(calcRela.valueChar);
  285. const order = calcRela.tree.nodes.findIndex(x => { return x.id === id });
  286. const orderParam = `<<f${order + 1}$${value}>>`;
  287. formula = formula.replace(ip, orderParam);
  288. }
  289. }
  290. return formula;
  291. };
  292. const exprStr2Expr = function(exprStr) {
  293. if (!exprStr) return '';
  294. let formula = exprStr;
  295. const orderParam = exprStr.match(calcRela.SerialReg);
  296. if (orderParam) {
  297. for (const op of orderParam) {
  298. const orderStr = op.match(calcRela.OrderReg)[0];
  299. const order = parseInt(orderStr.substring(1, op.length));
  300. const node = calcRela.tree.nodes[order - 1];
  301. const idParam = op.replace(orderStr, node.id);
  302. formula = formula.replace(op, idParam);
  303. }
  304. }
  305. return formula;
  306. };
  307. const setCalcType = function (calcType) {
  308. if (calcType === calcRela.calcType.zero) calcRela.getCalcNum = _getCalcNumZero;
  309. if (calcType === calcRela.calcType.direct) calcRela.getCalcNum = _getCalcNumDirect;
  310. if (calcType === calcRela.calcType.cache) calcRela.getCalcNum = _getCalcNumCache;
  311. if (calcType === calcRela.calcType.sortCache) calcRela.getCalcNum = _getCalcNumCache;
  312. calcRela.sort = calcType === calcRela.calcType.sortCache;
  313. };
  314. return {
  315. calcType: calcRela.calcType,
  316. init, setCalcType,
  317. checkExprValid, expr2ExprStr, exprStr2Expr,
  318. calcExpr, calcAllExpr,
  319. }
  320. })();