diff --git a/process/payments/reactions.ts b/process/payments/reactions.ts index c91be25..a1cf67a 100644 --- a/process/payments/reactions.ts +++ b/process/payments/reactions.ts @@ -3,10 +3,11 @@ import type { ApolloClient } from '@apollo/client'; import type { QueryClient } from '@tanstack/react-query'; import { selectSeasonType } from 'config/default-options'; -import { reaction, toJS } from 'mobx'; +import { comparer, reaction, toJS } from 'mobx'; import type { CalculationOptions } from 'stores/calculation/options/types'; import type RootStore from 'stores/root'; import type { Row } from 'stores/tables/payments/types'; +import { difference } from 'tools/array'; import validatePaymentsTable from './validation'; export default function paymentsReactions( @@ -314,6 +315,43 @@ export default function paymentsReactions( } ); + reaction( + () => { + const graphType = $calculation.getElementValue('radioGraphType'); + const payments = toJS($tables.payments.values); + const degressionType = $calculation.getElementValue('selectSeasonType'); + + return { + graphType, + payments, + degressionType, + }; + }, + (nextParams, prevParams) => { + if (nextParams.graphType === 100_000_001 && nextParams.degressionType === 100_000_007) { + const index = difference(nextParams.payments, prevParams.payments); + + if (index) { + const value = nextParams.payments[index]; + const payments = nextParams.payments.slice(1, -1).map((payment, i) => { + if (i <= index - 2) return payment; + + return value; + }); + + const firstPaymentPerc = $calculation.getElementValue('tbxFirstPaymentPerc'); + const lastPaymentPerc = $calculation.getElementValue('tbxLastPaymentPerc'); + + $tables.payments.setValues([firstPaymentPerc, ...payments, lastPaymentPerc]); + } + } + }, + { + delay: 10, + equals: comparer.structural, + } + ); + let removeError: () => void; reaction( @@ -333,6 +371,10 @@ export default function paymentsReactions( if (errorText) { removeError = $tables.payments.validation.addError(errorText); } + }, + { + delay: 10, + equals: comparer.structural, } ); } diff --git a/tools/array.ts b/tools/array.ts index 10ea29b..fd75999 100644 --- a/tools/array.ts +++ b/tools/array.ts @@ -1,4 +1,15 @@ -/* eslint-disable import/prefer-default-export */ -export function areEqual(arr1: Array, arr2: Array) { +export function areEqual(arr1: ReadonlyArray, arr2: ReadonlyArray) { return arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]); } + +export function difference(arr1: ReadonlyArray, arr2: ReadonlyArray) { + if (arr1.length !== arr2.length) return null; + // eslint-disable-next-line unicorn/no-for-loop + for (let i = 0; i < arr1.length; i += 1) { + if (arr1[i] !== arr2[i]) { + return i; + } + } + + return null; +}