@@ -18,6 +18,7 @@ import { AUDIO_FIELD, DOCUMENT_FIELD, PHOTO_FIELD } from "../constants";
18
18
import { LEGITIMATE_BASIS } from "../../record-creation-flow/components/consent-prompt/constants" ;
19
19
import renderFormSections from "../components/render-form-sections" ;
20
20
import { useApp } from "../../application" ;
21
+ import { parseExpression } from "../../../libs/expressions" ;
21
22
22
23
import { RECORD_FORM_NAME } from "./constants" ;
23
24
import { fieldValidations } from "./validations" ;
@@ -54,6 +55,7 @@ function RecordForm({
54
55
const formikValues = useRef ( ) ;
55
56
const bindedSetValues = useRef ( null ) ;
56
57
const bindedResetForm = useRef ( null ) ;
58
+ const bindedRecalculateFields = useRef ( null ) ;
57
59
58
60
const bindSetValues = setValues => {
59
61
bindedSetValues . current = setValues ;
@@ -63,6 +65,10 @@ function RecordForm({
63
65
bindedResetForm . current = resetForm ;
64
66
} ;
65
67
68
+ const bindRecalculateFields = recalculateFields => {
69
+ bindedRecalculateFields . current = recalculateFields ;
70
+ } ;
71
+
66
72
const buildValidationSchema = formSections => {
67
73
const schema = formSections . reduce ( ( obj , item ) => {
68
74
return Object . assign (
@@ -174,6 +180,14 @@ function RecordForm({
174
180
}
175
181
} , [ mode . isNew , dataProtectionInitialValues ] ) ;
176
182
183
+ const calculatedFields = forms . flatMap ( fs => fs . fields . filter ( field => field . calculation ?. expression ) ) ;
184
+
185
+ useEffect ( ( ) => {
186
+ if ( typeof bindedRecalculateFields . current === "function" ) {
187
+ bindedRecalculateFields . current ( ) ;
188
+ }
189
+ } ) ;
190
+
177
191
const handleConfirm = onConfirm => {
178
192
onConfirm ( ) ;
179
193
if ( incidentFromCase ?. size ) {
@@ -207,11 +221,23 @@ function RecordForm({
207
221
>
208
222
{ props => {
209
223
// eslint-disable-next-line react/prop-types
210
- const { submitForm, values } = props ;
224
+ const { submitForm, values, setFieldValue } = props ;
211
225
212
226
bindSubmitForm ( submitForm ) ;
213
227
setFormikValuesForNav ( values ) ;
214
228
229
+ bindRecalculateFields ( ( ) => {
230
+ if ( values ) {
231
+ calculatedFields . forEach ( field => {
232
+ const result = parseExpression ( field . calculation . expression ) . evaluate ( values ) ;
233
+
234
+ if ( values [ field . name ] !== result ) {
235
+ setFieldValue ( field . name , result , false ) ;
236
+ }
237
+ } ) ;
238
+ }
239
+ } ) ;
240
+
215
241
return (
216
242
< FormikForm
217
243
{ ...props }
0 commit comments