# InitializedTransactionForm



The `InitializedTransactionForm` is used to update a transaction that
is in an `initialized` state, such as a change to a policy after it
has been issued. It renders a form based on the specified product model
and handles the data collection needed to update the transaction’s
underlying element. A key feature of this form is its ability to handle
complex field dependencies and recalculations by evaluating constraints.

Usage [#usage]

To use this form, you need to provide the `elementResponse` of the
transaction, the `productModel`, and a `handleSubmit` function. For
advanced functionality, such as automatic field updates based on user
input, you must also provide a `dependencyMap` and a
`getEvaluatedConstraints` async function.

```ts
import { InitializedTransactionForm } from './InitializedTransactionForm';
import {
    ProductConfig,
    ElementResponse,
    ParamsChangeInstructionResponse,
    DependencyMapResponse,
    EvaluateConstraintsResponse,
    EvaluateConstraintsRequest,
} from '@socotra/ec-react-schemas';

// Example Usage
const MyQuoteComponent = ({
    productModel,
    elementResponse,
    paramsChangeInstruction,
    dependencyMap,
}: {
    productModel: ProductConfig,
    elementResponse: ElementResponse,
    paramsChangeInstruction: ParamsChangeInstructionResponse,
    dependencyMap: DependencyMapResponse,
}) => {
    const handleSubmit = (elementRequest) => {
        console.log('Element Update Request:', elementRequest);
        // Handle API call to update the transaction element
    };

    const handleEvaluateConstraints = async (
        request: EvaluateConstraintsRequest,
    ): Promise<EvaluateConstraintsResponse | undefined> => {
        // API call to evaluate constraints and get back updated values
        console.log('Evaluating constraints for:', request);
        return Promise.resolve(undefined); // Replace with actual API call
    };

    return (
        <InitializedTransactionForm
            productModel={productModel}
            elementResponse={elementResponse}
            paramsChangeInstruction={paramsChangeInstruction}
            timezone='America/New_York'
            handleSubmit={handleSubmit}
            dependencyMap={dependencyMap}
            getEvaluatedConstraints={handleEvaluateConstraints}
            submitButtonText='Update Quote'
        />
    );
};
```

Props [#props]

| Prop                         | Type                                                                                        | Description                                                                                                                   | Default      |
| ---------------------------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------ |
| `elementResponse`            | `ElementResponse`                                                                           | The element object for the initialized transaction.                                                                           | **Required** |
| `paramsChangeInstruction`    | `ParamsChangeInstructionResponse`                                                           | The parameter change instruction associated with the transaction.                                                             | **Required** |
| `productModel`               | `ProductConfig`                                                                             | The product configuration that defines the form’s structure.                                                                  | **Required** |
| `timezone`                   | `string`                                                                                    | The timezone for the policy, used for date/time field handling.                                                               | **Required** |
| `handleSubmit`               | `(data: ElementRequest) => void`                                                            | Callback triggered on submit, receiving the `ElementRequest` payload for updating the transaction.                            | **Required** |
| `coverageTerms`              | `CoverageTermsConfigRecord`                                                                 | Configuration for any coverage terms associated with the product.                                                             | `undefined`  |
| `dataTypes`                  | `DataTypeConfigRecord`                                                                      | Custom data types used within the product model.                                                                              | `undefined`  |
| `dependencyMap`              | `DependencyMapResponse`                                                                     | An optional map defining the dependencies between fields for constraint evaluation. Required to enable constraint evaluation. | `undefined`  |
| `getEvaluatedConstraints`    | `(request, tenantLocator, locator) => Promise&lt;EvaluateConstraintsResponse \| undefined>` | An optional async function to call the backend to evaluate constraints. Required to enable constraint evaluation.             | `undefined`  |
| `disabled`                   | `boolean`                                                                                   | When true, disables the entire form.                                                                                          | `false`      |
| `isSubmitting`               | `boolean`                                                                                   | When true, disables the form to indicate a submission is in progress.                                                         | `false`      |
| `preventFormResetOnDisabled` | `boolean`                                                                                   | If `false`, the form’s data resets to initial values when `disabled` becomes true.                                            | `true`       |
| `validateOnSubmit`           | `boolean`                                                                                   | If `true`, validation runs on submit, blocking submission if invalid.                                                         | `false`      |
| `hideSubmitButton`           | `boolean`                                                                                   | If `true`, the submit button is not rendered.                                                                                 | `false`      |
| `submitButtonText`           | `string`                                                                                    | Custom text for the submit button.                                                                                            | `'Update'`   |
| `id`                         | `string`                                                                                    | A unique ID for the form wrapper element.                                                                                     | `undefined`  |
| `titles`                     | `object`                                                                                    | An object to override default labels for form sections.                                                                       | `{}`         |

State Management [#state-management]

The form state is managed internally using `useState` and
`useEffect` hooks.

* Form data is initialized using the
  `getDefaultInitializedTransactionValues` utility.
* **Constraint Evaluation:** When `dependencyMap` and
  `getEvaluatedConstraints` are provided, the form watches for data
  changes. A `useEffect` hook triggers the `getEvaluatedConstraints`
  function when a field that others depend on is modified. The results
  are stored in an `evaluatedConstraints` state variable, which is
  then used to update the JSON schema and disable the modified fields.
* **Data Syncing:** A `useEffect` hook compares the incoming
  `elementResponse` prop with a local copy in state. If they differ
  (e.g., after a save), the form data is recalculated to reflect the
  latest updates.
* The `JsonForms` `onChange` handler updates the form data state and
  clears any existing `evaluatedConstraints` to allow for
  re-evaluation.

Validation [#validation]

Validation is handled by [Ajv ](https://ajv.js.org/).

* A JSON schema is dynamically built by `dataModelToJSONSchema` based
  on the `productModel`, `dataTypes`, and current `timezone`.
* If constraint evaluation is active, the schema is updated with
  information from the `dependencyMap` and `evaluatedConstraints`
  response to make dependent fields read-only and update their values.
* The schema is also extended with definitions for any
  `coverageTerms`.
* The `validateOnSubmit` prop controls whether to block form
  submission if the data is invalid.
* The `translateError` utility provides user-friendly validation
  messages.

Labels and Translations [#labels-and-translations]

The text for UI labels and validation messages can be customized.

**UI Labels**

Labels for sections and fields can be overridden by passing a `titles`
object prop.

| Key             | Description                             | Default Value      |
| --------------- | --------------------------------------- | ------------------ |
| `formTitle`     | The main title for the entire form.     | `'Transaction'`    |
| `coverageTerms` | Title for the “Coverage Terms” section. | `'Coverage Terms'` |
| `truthyLabel`   | Text for a “true” boolean value.        | `'Yes'`            |
| `falsyLabel`    | Text for a “false” boolean value.       | `'No'`             |
