Skip to content

Commit

Permalink
SimpleEval
Browse files Browse the repository at this point in the history
  • Loading branch information
getrebuild committed Dec 5, 2023
1 parent 3f7feaf commit 7b7ce27
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,19 @@ public class EasyFieldConfigProps {
* 日期格式
*/
public static final String DATE_FORMAT = "dateFormat";
/**
* 表单公式
*/
public static final String DATE_CALCFORMULA = NUMBER_CALCFORMULA;

/**
* 日期格式
*/
public static final String DATETIME_FORMAT = "datetimeFormat";
/**
* 表单公式
*/
public static final String DATETIME_CALCFORMULA = NUMBER_CALCFORMULA;

/**
* 时间格式
Expand Down
19 changes: 19 additions & 0 deletions src/main/java/com/rebuild/core/support/SimpleEval.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*!
Copyright (c) REBUILD <https://getrebuild.com/> and/or its owners. All rights reserved.
rebuild is dual-licensed under commercial and open source licenses (GPLv3).
See LICENSE and COMMERCIAL in the project root for license information.
*/

package com.rebuild.core.support;

/**
* 简单公式计算
*
* @author RB
* @since 2023/12/5
*/
public class SimpleEval {


}
14 changes: 14 additions & 0 deletions src/main/java/com/rebuild/web/general/ModelExtrasController.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
package com.rebuild.web.general;

import cn.devezhao.bizz.privileges.impl.BizzPermission;
import cn.devezhao.commons.web.ServletUtils;
import cn.devezhao.persist4j.Entity;
import cn.devezhao.persist4j.Field;
import cn.devezhao.persist4j.engine.ID;
Expand All @@ -32,6 +33,7 @@
import com.rebuild.web.IdParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

Expand Down Expand Up @@ -195,4 +197,16 @@ public JSON checkCreates(HttpServletRequest request) {
}
return allowed;
}

@PostMapping("eval-calc-formula")
public RespBody evalCalcFormula(@EntityParam Entity entity, HttpServletRequest request) {
String fieldName = getParameterNotNull(request, "field");
if (!entity.containsField(fieldName)) return RespBody.error();

JSON data = ServletUtils.getRequestJson(request);

System.out.println(data.toJSONString());

return RespBody.ok();
}
}
7 changes: 5 additions & 2 deletions src/main/resources/web/admin/metadata/field-edit.html
Original file line number Diff line number Diff line change
Expand Up @@ -359,14 +359,17 @@ <h5>[[${bundle.L('常用')}]]</h5>
</div>
</div>
</div>
<div th:if="${fieldType == 'DECIMAL' or fieldType == 'NUMBER'}" class="form-group row J_for-DECIMAL J_for-NUMBER">
<div
th:if="${fieldType == 'DECIMAL' or fieldType == 'NUMBER' or fieldType == 'DATE' or fieldType == 'DATETIME'}"
class="form-group row J_for-DECIMAL J_for-NUMBER J_for-DATE J_for-DATETIME"
>
<label class="col-md-12 col-xl-3 col-lg-4 col-form-label text-lg-right">[[${bundle.L('表单计算公式')}]]</label>
<div class="col-md-12 col-xl-6 col-lg-8">
<input type="hidden" class="form-control" id="calcFormula" />
<div class="form-control-plaintext formula" id="calcFormula2" th:_title="${bundle.L('无')}">[[${calcFormula ?: calcFormula}]]</div>
<p
class="form-text"
th:utext="${bundle.L('本公式仅做前端计算,如公式中所用字段未布局/未显示,则无法进行计算。你也可以通过 [触发器 (字段更新)](/admin/robot/triggers) 实现更强大的计算规则')}"
th:utext="${bundle.L('如公式中所用字段未布局/未显示,则无法进行计算。本公式适用前端简单计算,你可以通过 [触发器 (字段更新)](/admin/robot/triggers) 实现更强大的计算规则')}"
></p>
</div>
</div>
Expand Down
56 changes: 28 additions & 28 deletions src/main/resources/web/assets/js/general/rb-forms.js
Original file line number Diff line number Diff line change
Expand Up @@ -1186,6 +1186,7 @@ class RbFormNumber extends RbFormText {

// 表单计算
let _timer
const evalUrl = `/app/entity/extras/eval-calc-formula?entity=${this.props.$$$parent.props.entity}&field=${this.props.field}`
this.props.$$$parent.onFieldValueChange((s) => {
if (!watchFields.includes(`{${s.name}}`)) {
if (rb.env === 'dev') console.log('onFieldValueChange ignored :', s, this.props.field)
Expand All @@ -1194,47 +1195,46 @@ class RbFormNumber extends RbFormText {
console.log('onFieldValueChange for calcFormula :', s, this.props.field)
}

// // fix: 3.2 字段相互使用导致死循环
// this.__fixUpdateDepth = (this.__fixUpdateDepth || 0) + 1
// if (this.__fixUpdateDepth > 9) {
// console.log(`Maximum update depth exceeded : ${this.props.field}=${this.props.calcFormula}`)
// setTimeout(() => (this.__fixUpdateDepth = 0), 100)
// return false
// }

if ($emptyNum(s.value)) {
delete calcFormulaValues[s.name]
} else {
calcFormulaValues[s.name] = this._removeComma(s.value)
}

let formula = calcFormula
for (let key in calcFormulaValues) {
formula = formula.replace(new RegExp(`{${key}}`, 'ig'), calcFormulaValues[key] || 0)
}

if (_timer) {
clearTimeout(_timer)
_timer = null
}

// v34 延迟执行
// v36
_timer = setTimeout(() => {
// 还有变量无值
if (formula.includes('{')) {
this.setValue(null)
return false
}

try {
let calcv = null
eval(`calcv = ${formula}`)
if (!isNaN(calcv)) this.setValue(calcv.toFixed(fixed))
} catch (err) {
if (rb.env === 'dev') console.log(err)
}
return true
$.post(evalUrl, JSON.stringify(calcFormulaValues), (res) => {
console.log(res)
})
}, 200)

// let formula = calcFormula
// for (let key in calcFormulaValues) {
// formula = formula.replace(new RegExp(`{${key}}`, 'ig'), calcFormulaValues[key] || 0)
// }

// // v34 延迟执行
// _timer = setTimeout(() => {
// // 还有变量无值
// if (formula.includes('{')) {
// this.setValue(null)
// return false
// }

// try {
// let calcv = null
// eval(`calcv = ${formula}`)
// if (!isNaN(calcv)) this.setValue(calcv.toFixed(fixed))
// } catch (err) {
// if (rb.env === 'dev') console.log(err)
// }
// return true
// }, 200)
// _timer end
})
}, 200) // init
Expand Down
10 changes: 5 additions & 5 deletions src/main/resources/web/assets/js/metadata/field-edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ $(document).ready(function () {
} else if (dt === 'SERIES') {
_handleSeries()
} else if (dt === 'DATE' || dt === 'DATETIME' || dt === 'TIME') {
if (dt === 'DATE' || dt === 'DATETIME') _handleCalcFormula(extConfig.calcFormula)
_handleDatetime(dt)
} else if (dt === 'FILE' || dt === 'IMAGE') {
_handleFile(extConfig.uploadNumber)
Expand All @@ -247,8 +248,7 @@ $(document).ready(function () {
} else if (dt === 'BARCODE') {
$('.J_fieldAttrs input').attr('disabled', true)
} else if (dt === 'NUMBER' || dt === 'DECIMAL') {
_handleNumber(extConfig.calcFormula)

_handleCalcFormula(extConfig.calcFormula)
if (dt === 'DECIMAL') {
if (!extConfig.decimalType || extConfig.decimalType === 0 || extConfig.decimalType === '0' || extConfig.decimalType === '%') {
// 数字、百分比
Expand Down Expand Up @@ -580,7 +580,7 @@ const _loadRefsLabel = function ($dv, $dvClear) {
}

let FIELDS_CACHE
const _handleNumber = function (calcFormula) {
const _handleCalcFormula = function (formula) {
const $el = $('#calcFormula2')
function _call(s) {
$('#calcFormula').val(s || '')
Expand All @@ -591,13 +591,13 @@ const _handleNumber = function (calcFormula) {
$.get(`/commons/metadata/fields?entity=${wpc.entityName}`, (res) => {
const fs = []
res.data.forEach((item) => {
if ((item.type === 'NUMBER' || item.type === 'DECIMAL') && item.name !== wpc.fieldName) {
if (['NUMBER', 'DECIMAL', 'DATE', 'DATETIME'].includes(item.type) && !['approvalLastTime', 'modifiedOn'].includes(item.name) && item.name !== wpc.fieldName) {
fs.push(item)
}
})

FIELDS_CACHE = fs
if (calcFormula) _call(calcFormula)
if (formula) _call(formula)
})
}

Expand Down

0 comments on commit 7b7ce27

Please sign in to comment.