如何对子表进行数值计算?


代码如下:

const formValues = await ctx.getVar(‘ctx.formValues’);
const details = formValues?.order_details || ;

const totalAmount = details.reduce((sum, item) => {
const quantity = Number(item?.quantity) || 0;
const price = Number(item?.code?.price) || 0;
return sum + (quantity * price);
}, 0);
return totalAmount;

只能返回金额和,而不能返回每行的金额,请帮忙看看如何解决?

参考

// 终极解决方案:强制重新计算所有行
// 注意:这会在每次触发时计算所有行,但只返回当前相关的值

const recalculateAmount = () => {
const formValues = ctx.form?.getFieldsValue(true);

if (!formValues?.order_details || !Array.isArray(formValues.order_details)) {
return 0;
}

// 在实际运行时,我们需要确定当前行
// 由于技术限制,我们假设当前正在编辑的行是最后一个有数据的行
let targetRow = null;

// 从后往前找,找到第一个有quantity或price的行
for (let i = formValues.order_details.length - 1; i >= 0; i–) {
const row = formValues.order_details[i];
if (row.quantity !== undefined || row.price !== undefined) {
targetRow = row;
break;
}
}

// 如果没找到,使用第一行
targetRow = targetRow || formValues.order_details[0];

if (targetRow) {
const quantity = parseFloat(targetRow.quantity) || 0;
const price = parseFloat(targetRow.price) || 0;
return Math.round((quantity * price) * 100) / 100;
}

return 0;
};

return recalculateAmount();

用NocoBase的AI编写的,试了很多方法,要么为0,要么是把结果写到所有的行内金额字段值,并不能进行单行的计算!

// 获取当前表单值
const formValues = ctx.form?.getFieldsValue();
var total_amount=0;
// 假设子表格字段名为 ‘items’,请根据实际情况修改
if (formValues && formValues.items) {
formValues.items.forEach((item, index) => {
// 获取当前行的数量和单价
const quantity = item.quantity || 0;
const unitPrice = item.unit_price || 0;

// 计算金额
const lineAmount = quantity * unitPrice;
total_amount=total_amount+lineAmount;
// 更新当前行的金额字段
// 路径格式: ['子表格字段名', 行索引, '金额字段名']
ctx.form?.setFieldValue(['items', index, 'line_amount'], lineAmount);

});
total_amount=total_amount+formValues.shipping_handling;
ctx.form?.setFieldValue(‘total_amount’,total_amount);

}

// 为子表格每一行的合计字段 (f_wivp0iqzmxj) 设置值 = 数量 × 单价

const subTableRows = ctx.form.getFieldValue(‘f_tomore_id’) || ;

if (!Array.isArray(subTableRows)) {
return;
}

// 使用 setFieldValue 确保每个字段都被正确设置
subTableRows.forEach((row, index) => {
const quantity = (typeof row?.f_vwcbbcstrun === ‘number’ && !isNaN(row.f_vwcbbcstrun)) ? row.f_vwcbbcstrun : 0;
const unitPrice = (typeof row?.f_avwweicsgbk === ‘number’ && !isNaN(row.f_avwweicsgbk)) ? row.f_avwweicsgbk : 0;
const total = quantity * unitPrice;
// console.log(‘【调试】获取到的数量:’, quantity, ‘类型:’, typeof quantity);
// console.log(‘【调试】获取到的单价:’, unitPrice, ‘类型:’, typeof unitPrice);
// 直接设置合计字段
if (ctx.form.setFieldValue) {
ctx.form.setFieldValue([‘f_tomore_id’, index, ‘f_wivp0iqzmxj’], total);
}
});

提供参考