tools: rewrite makeDisposable function => disposableReaction

This commit is contained in:
vchikalkin 2023-04-11 23:40:10 +03:00
parent 891bb889d1
commit f77e8768d3
12 changed files with 447 additions and 500 deletions

View File

@ -4,7 +4,7 @@ import * as CRMTypes from '@/graphql/crm.types';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { reaction } from 'mobx';
import { makeDisposable } from 'tools';
import { disposableReaction } from 'tools';
dayjs.extend(utc);
@ -20,33 +20,30 @@ export default function reactions(context: ProcessContext) {
* Если продукта нет или нет коэффициента по условиям, то поле tbxSaleBonus = 0 и закрыто для редактирования
*/
makeDisposable(
() =>
reaction(
() => $calculation.element('selectProduct').getValue(),
async (productId) => {
if (!productId) {
$calculation.element('tbxSaleBonus').resetValue().block();
disposableReaction(
() => $process.has('LoadKP'),
() => $calculation.element('selectProduct').getValue(),
async (productId) => {
if (!productId) {
$calculation.element('tbxSaleBonus').resetValue().block();
return;
}
return;
}
const coefficient = await getCoefficient(productId);
const coefficient = await getCoefficient(productId);
if (!coefficient?.evo_sot_coefficient) {
$calculation.element('tbxSaleBonus').resetValue().block();
if (!coefficient?.evo_sot_coefficient) {
$calculation.element('tbxSaleBonus').resetValue().block();
return;
}
return;
}
const maxBonus = (coefficient?.evo_sot_coefficient || 0) * 100;
$calculation.element('tbxSaleBonus').setValue(maxBonus).unblock();
},
{
fireImmediately: true,
}
),
() => $process.has('LoadKP')
const maxBonus = (coefficient?.evo_sot_coefficient || 0) * 100;
$calculation.element('tbxSaleBonus').setValue(maxBonus).unblock();
},
{
fireImmediately: true,
}
);
/**

View File

@ -5,7 +5,7 @@ import type { ProcessContext } from '@/process/types';
import ValidationHelper from '@/stores/validation/helper';
import { reaction } from 'mobx';
import { uid } from 'radash';
import { makeDisposable } from 'tools';
import { disposableReaction } from 'tools';
import type { BaseOption } from 'ui/elements/types';
function hasInvalidValueOrOptions(value: unknown, options: Array<BaseOption<unknown>>) {
@ -19,36 +19,33 @@ function hasInvalidValueOrOptions(value: unknown, options: Array<BaseOption<unkn
export default function reactions({ store }: ProcessContext) {
const { $calculation, $tables, $process } = store;
makeDisposable(
() =>
reaction(
() => {
const hasElementsErrors = Object.values($calculation.$validation).some(
(validation) => validation.hasErrors
);
disposableReaction(
() => $process.has('Unlimited'),
() => {
const hasElementsErrors = Object.values($calculation.$validation).some(
(validation) => validation.hasErrors
);
const hasPaymentsErrors = $tables.payments.validation.hasErrors;
const hasInsuranceErrors = $tables.insurance.validation.hasErrors;
const hasFingapErrors = $tables.fingap.validation.hasErrors;
const hasPaymentsErrors = $tables.payments.validation.hasErrors;
const hasInsuranceErrors = $tables.insurance.validation.hasErrors;
const hasFingapErrors = $tables.fingap.validation.hasErrors;
return hasElementsErrors || hasPaymentsErrors || hasInsuranceErrors || hasFingapErrors;
},
(hasErrors) => {
if (hasErrors) {
$calculation.$status.setStatus('btnCalculate', 'Disabled');
$calculation.$status.setStatus('btnCreateKP', 'Disabled');
$calculation.$status.setStatus('btnCreateKPMini', 'Disabled');
} else {
$calculation.$status.setStatus('btnCalculate', 'Default');
$calculation.$status.setStatus('btnCreateKP', 'Default');
$calculation.$status.setStatus('btnCreateKPMini', 'Default');
}
},
{
fireImmediately: true,
}
),
() => $process.has('Unlimited')
return hasElementsErrors || hasPaymentsErrors || hasInsuranceErrors || hasFingapErrors;
},
(hasErrors) => {
if (hasErrors) {
$calculation.$status.setStatus('btnCalculate', 'Disabled');
$calculation.$status.setStatus('btnCreateKP', 'Disabled');
$calculation.$status.setStatus('btnCreateKPMini', 'Disabled');
} else {
$calculation.$status.setStatus('btnCalculate', 'Default');
$calculation.$status.setStatus('btnCreateKP', 'Default');
$calculation.$status.setStatus('btnCreateKPMini', 'Default');
}
},
{
fireImmediately: true,
}
);
/**

View File

@ -1,41 +1,37 @@
import * as CRMTypes from '@/graphql/crm.types';
import type { ProcessContext } from '@/process/types';
import { reaction } from 'mobx';
import { makeDisposable, normalizeOptions } from 'tools';
import { disposableReaction, normalizeOptions } from 'tools';
export default function unlimitedReactions({ store, apolloClient }: ProcessContext) {
const { $calculation, $process } = store;
makeDisposable(
() =>
reaction(
() => $calculation.element('selectUser').getValue(),
async (domainname) => {
if (!domainname) {
$calculation.element('selectLead').reset();
$calculation.element('selectOpportunity').reset();
disposableReaction(
() => !$process.has('Unlimited'),
() => $calculation.element('selectUser').getValue(),
async (domainname) => {
if (!domainname) {
$calculation.element('selectLead').reset();
$calculation.element('selectOpportunity').reset();
return;
}
const {
data: { leads },
} = await apolloClient.query({
query: CRMTypes.GetLeadsDocument,
variables: { domainname },
});
return;
}
const {
data: { leads },
} = await apolloClient.query({
query: CRMTypes.GetLeadsDocument,
variables: { domainname },
});
$calculation.element('selectLead').setOptions(normalizeOptions(leads));
$calculation.element('selectLead').setOptions(normalizeOptions(leads));
const {
data: { opportunities },
} = await apolloClient.query({
query: CRMTypes.GetOpportunitiesDocument,
variables: { domainname },
});
const {
data: { opportunities },
} = await apolloClient.query({
query: CRMTypes.GetOpportunitiesDocument,
variables: { domainname },
});
$calculation.element('selectOpportunity').setOptions(normalizeOptions(opportunities));
}
),
() => !$process.has('Unlimited')
$calculation.element('selectOpportunity').setOptions(normalizeOptions(opportunities));
}
);
}

View File

@ -5,7 +5,7 @@ import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { reaction } from 'mobx';
import { first, sort } from 'radash';
import { makeDisposable, normalizeOptions } from 'tools';
import { disposableReaction, normalizeOptions } from 'tools';
dayjs.extend(utc);
@ -84,35 +84,31 @@ export default function valuesReactions({ store, apolloClient }: ProcessContext)
}
);
makeDisposable(
() =>
reaction(
() => $calculation.element('selectTarif').getValue(),
async (tarifId) => {
if (!tarifId) {
$calculation.element('tbxIRR_Perc').resetValue();
disposableReaction(
() => $process.has('LoadKP'),
() => $calculation.element('selectTarif').getValue(),
async (tarifId) => {
if (!tarifId) {
$calculation.element('tbxIRR_Perc').resetValue();
return;
}
const {
data: { evo_tarif },
} = await apolloClient.query({
fetchPolicy: 'network-only',
query: CRMTypes.GetTarifDocument,
variables: {
tarifId,
},
});
return;
}
const {
data: { evo_tarif },
} = await apolloClient.query({
fetchPolicy: 'network-only',
query: CRMTypes.GetTarifDocument,
variables: {
tarifId,
},
});
if (evo_tarif?.evo_irr) {
$calculation.element('tbxIRR_Perc').setValue(evo_tarif?.evo_irr);
} else {
$calculation.element('tbxIRR_Perc').resetValue();
}
}
),
() => $process.has('LoadKP')
if (evo_tarif?.evo_irr) {
$calculation.element('tbxIRR_Perc').setValue(evo_tarif?.evo_irr);
} else {
$calculation.element('tbxIRR_Perc').resetValue();
}
}
);
reaction(

View File

@ -12,7 +12,7 @@ import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { reaction } from 'mobx';
import { uid } from 'radash';
import { debouncedReaction, makeDisposable, normalizeOptions } from 'tools';
import { debouncedReaction, disposableReaction, normalizeOptions } from 'tools';
dayjs.extend(utc);
@ -45,41 +45,38 @@ export function common({ store, apolloClient, queryClient }: ProcessContext) {
}
);
makeDisposable(
disposableReaction(
() => $process.has('LoadKP'),
() =>
reaction(
() =>
$calculation.$values.getValues([
'leaseObjectType',
'objectCategoryTax',
'objectRegistration',
]),
async ({ leaseObjectType: leaseObjectTypeId, objectRegistration, objectCategoryTax }) => {
if (objectRegistration === 100_000_001) {
if (objectCategoryTax && [100_000_006, 100_000_009].includes(objectCategoryTax)) {
$calculation.element('selectObjectTypeTax').setValue(100_000_002);
} else if (leaseObjectTypeId) {
const {
data: { evo_leasingobject_type },
} = await apolloClient.query({
query: CRMTypes.GetLeaseObjectTypeDocument,
variables: { leaseObjectTypeId },
});
$calculation.$values.getValues([
'leaseObjectType',
'objectCategoryTax',
'objectRegistration',
]),
async ({ leaseObjectType: leaseObjectTypeId, objectRegistration, objectCategoryTax }) => {
if (objectRegistration === 100_000_001) {
if (objectCategoryTax && [100_000_006, 100_000_009].includes(objectCategoryTax)) {
$calculation.element('selectObjectTypeTax').setValue(100_000_002);
} else if (leaseObjectTypeId) {
const {
data: { evo_leasingobject_type },
} = await apolloClient.query({
query: CRMTypes.GetLeaseObjectTypeDocument,
variables: { leaseObjectTypeId },
});
if (evo_leasingobject_type?.evo_vehicle_type_tax) {
$calculation
.element('selectObjectTypeTax')
.setValue(evo_leasingobject_type?.evo_vehicle_type_tax);
} else {
$calculation.element('selectObjectTypeTax').resetValue();
}
}
if (evo_leasingobject_type?.evo_vehicle_type_tax) {
$calculation
.element('selectObjectTypeTax')
.setValue(evo_leasingobject_type?.evo_vehicle_type_tax);
} else {
$calculation.element('selectObjectTypeTax').resetValue();
}
}
),
() => $process.has('LoadKP')
} else {
$calculation.element('selectObjectTypeTax').resetValue();
}
}
);
reaction(
@ -149,82 +146,79 @@ export function common({ store, apolloClient, queryClient }: ProcessContext) {
return mapObjectTypeTaxToCategory[objectTypeTax as keyof typeof mapObjectTypeTaxToCategory];
}
makeDisposable(
disposableReaction(
() => $process.has('LoadKP'),
() =>
reaction(
() =>
$calculation.$values.getValues([
'objectRegistration',
'objectTypeTax',
'regionRegistration',
'leaseObjectYear',
'leaseObjectMotorPower',
]),
async ({
objectRegistration,
objectTypeTax,
regionRegistration,
leaseObjectYear,
leaseObjectMotorPower,
}) => {
if (
objectRegistration === null ||
objectRegistration !== 100_000_001 ||
objectTypeTax === null ||
regionRegistration === null ||
leaseObjectYear === 0 ||
leaseObjectMotorPower === 0
) {
$calculation.element('tbxVehicleTaxInYear').resetValue();
$calculation.$values.getValues([
'objectRegistration',
'objectTypeTax',
'regionRegistration',
'leaseObjectYear',
'leaseObjectMotorPower',
]),
async ({
objectRegistration,
objectTypeTax,
regionRegistration,
leaseObjectYear,
leaseObjectMotorPower,
}) => {
if (
objectRegistration === null ||
objectRegistration !== 100_000_001 ||
objectTypeTax === null ||
regionRegistration === null ||
leaseObjectYear === 0 ||
leaseObjectMotorPower === 0
) {
$calculation.element('tbxVehicleTaxInYear').resetValue();
return;
}
return;
}
const {
data: { evo_region },
} = await apolloClient.query({
query: CRMTypes.GetRegionDocument,
variables: {
regionId: regionRegistration,
const {
data: { evo_region },
} = await apolloClient.query({
query: CRMTypes.GetRegionDocument,
variables: {
regionId: regionRegistration,
},
});
const OKTMO = evo_region?.evo_oktmo;
const carCategory = getCarCategory(objectTypeTax);
if (OKTMO) {
const currentDate = dayjs().utc(false).toDate();
const request = (context: QueryFunctionContext) =>
getTransTax(
{
OKTMO,
calcDate: currentDate,
carCategory,
power: leaseObjectMotorPower,
year: leaseObjectYear,
},
});
const OKTMO = evo_region?.evo_oktmo;
const carCategory = getCarCategory(objectTypeTax);
if (OKTMO) {
const currentDate = dayjs().utc(false).toDate();
const request = (context: QueryFunctionContext) =>
getTransTax(
{
OKTMO,
calcDate: currentDate,
carCategory,
power: leaseObjectMotorPower,
year: leaseObjectYear,
},
context
);
const { tax, error } = await queryClient.fetchQuery(
['1c', 'trans-tax', carCategory, leaseObjectMotorPower, leaseObjectYear],
request,
{
staleTime: STALE_TIME,
}
);
if (!error && tax) {
$calculation.element('tbxVehicleTaxInYear').setValue(tax);
} else {
$calculation.element('tbxVehicleTaxInYear').resetValue();
}
} else {
$calculation.element('tbxVehicleTaxInYear').resetValue();
context
);
const { tax, error } = await queryClient.fetchQuery(
['1c', 'trans-tax', carCategory, leaseObjectMotorPower, leaseObjectYear],
request,
{
staleTime: STALE_TIME,
}
);
if (!error && tax) {
$calculation.element('tbxVehicleTaxInYear').setValue(tax);
} else {
$calculation.element('tbxVehicleTaxInYear').resetValue();
}
),
() => $process.has('LoadKP')
} else {
$calculation.element('tbxVehicleTaxInYear').resetValue();
}
}
);
// Не дышать на реакцию

View File

@ -2,7 +2,7 @@ import * as CRMTypes from '@/graphql/crm.types';
import type { ProcessContext } from '@/process/types';
import { reaction } from 'mobx';
import { normalizeOptions } from 'tools/entity';
import { makeDisposable } from 'tools/mobx';
import { disposableReaction } from 'tools/mobx';
export default function reactions({ store, apolloClient }: ProcessContext) {
const { $calculation, $process } = store;
@ -14,34 +14,31 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
* Иначе ничего не указывается
*/
makeDisposable(
() =>
reaction(
() => $calculation.element('selectLead').getValue(),
async (leadid) => {
if (!leadid) {
$calculation.element('selectOpportunity').resetValue();
disposableReaction(
() => $process.has('LoadKP'),
() => $calculation.element('selectLead').getValue(),
async (leadid) => {
if (!leadid) {
$calculation.element('selectOpportunity').resetValue();
return;
}
return;
}
const {
data: { lead },
} = await apolloClient.query({
query: CRMTypes.GetLeadDocument,
variables: {
leadid,
},
});
const {
data: { lead },
} = await apolloClient.query({
query: CRMTypes.GetLeadDocument,
variables: {
leadid,
},
});
if (lead?.evo_opportunityidData?.value) {
$calculation.element('selectOpportunity').setValue(lead?.evo_opportunityidData?.value);
} else {
$calculation.element('selectOpportunity').resetValue();
}
}
),
() => $process.has('LoadKP')
if (lead?.evo_opportunityidData?.value) {
$calculation.element('selectOpportunity').setValue(lead?.evo_opportunityidData?.value);
} else {
$calculation.element('selectOpportunity').resetValue();
}
}
);
reaction(

View File

@ -8,7 +8,7 @@ import type { Row } from '@/stores/tables/payments/types';
import { comparer, reaction, toJS } from 'mobx';
import { shift } from 'radash';
import { difference } from 'tools/array';
import { makeDisposable } from 'tools/mobx';
import { disposableReaction } from 'tools/mobx';
const {
generateSeasonPaymentsRows,
@ -245,74 +245,68 @@ export default function reactions({ store }: ProcessContext) {
// }
// );
makeDisposable(
() =>
reaction(
() => $calculation.$values.getValues(['leasingPeriod', 'seasonType']),
({ seasonType, leasingPeriod }) => {
const middlePayments: Row[] = degressionTools.generateDegressionRows({
leasingPeriod,
seasonType,
});
disposableReaction(
() => $calculation.element('radioGraphType').getValue() !== 100_000_001,
() => $calculation.$values.getValues(['leasingPeriod', 'seasonType']),
({ seasonType, leasingPeriod }) => {
const middlePayments: Row[] = degressionTools.generateDegressionRows({
leasingPeriod,
seasonType,
});
const firstPaymentPerc = $calculation.element('tbxFirstPaymentPerc').getValue();
const lastPaymentPerc = $calculation.element('tbxLastPaymentPerc').getValue();
const firstPaymentPerc = $calculation.element('tbxFirstPaymentPerc').getValue();
const lastPaymentPerc = $calculation.element('tbxLastPaymentPerc').getValue();
const rows: Row[] = [
{
status: 'Disabled',
value: firstPaymentPerc,
},
...middlePayments,
{
status: 'Disabled',
value: lastPaymentPerc,
},
];
const rows: Row[] = [
{
status: 'Disabled',
value: firstPaymentPerc,
},
...middlePayments,
{
status: 'Disabled',
value: lastPaymentPerc,
},
];
if (!$process.has('LoadKP')) {
$tables.payments.setValues(rows.map((row) => row.value));
}
if (!$process.has('LoadKP')) {
$tables.payments.setValues(rows.map((row) => row.value));
}
$tables.payments.setStatuses(rows.map((row) => row.status));
}
),
() => $calculation.element('radioGraphType').getValue() !== 100_000_001
$tables.payments.setStatuses(rows.map((row) => row.status));
}
);
makeDisposable(
() =>
reaction(
() => toJS($tables.payments.values),
(nextPayments, prevPayments) => {
const graphType = $calculation.element('radioGraphType').getValue();
const degressionType = $calculation.element('selectSeasonType').getValue();
disposableReaction(
() => $process.has('LoadKP'),
() => toJS($tables.payments.values),
(nextPayments, prevPayments) => {
const graphType = $calculation.element('radioGraphType').getValue();
const degressionType = $calculation.element('selectSeasonType').getValue();
if (graphType === 100_000_001 && degressionType === 100_000_007) {
const changes = difference(nextPayments, prevPayments);
if (graphType === 100_000_001 && degressionType === 100_000_007) {
const changes = difference(nextPayments, prevPayments);
if (!changes?.length || changes.length > 1) return;
if (!changes?.length || changes.length > 1) return;
const [changeIndex] = changes;
const value = nextPayments[changeIndex];
const payments = nextPayments.slice(1, -1).map((payment, i) => {
if (i <= changeIndex - 2) return payment;
const [changeIndex] = changes;
const value = nextPayments[changeIndex];
const payments = nextPayments.slice(1, -1).map((payment, i) => {
if (i <= changeIndex - 2) return payment;
return value;
});
return value;
});
const firstPaymentPerc = $calculation.element('tbxFirstPaymentPerc').getValue();
const lastPaymentPerc = $calculation.element('tbxLastPaymentPerc').getValue();
const firstPaymentPerc = $calculation.element('tbxFirstPaymentPerc').getValue();
const lastPaymentPerc = $calculation.element('tbxLastPaymentPerc').getValue();
$tables.payments.setValues([firstPaymentPerc, ...payments, lastPaymentPerc]);
}
},
{
delay: 50,
equals: comparer.structural,
}
),
() => $process.has('LoadKP')
$tables.payments.setValues([firstPaymentPerc, ...payments, lastPaymentPerc]);
}
},
{
delay: 50,
equals: comparer.structural,
}
);
/**
@ -408,72 +402,66 @@ export default function reactions({ store }: ProcessContext) {
}
);
makeDisposable(
() =>
reaction(
() => {
const payments = toJS($tables.payments.values);
disposableReaction(
() => $process.has('LoadKP'),
() => {
const payments = toJS($tables.payments.values);
return payments.slice(1, SEASONS_PERIOD_NUMBER + 1);
},
(nextSeasons, prevSeasons) => {
const graphType = $calculation.element('radioGraphType').getValue();
if (graphType !== 100_000_003) return;
return payments.slice(1, SEASONS_PERIOD_NUMBER + 1);
},
(nextSeasons, prevSeasons) => {
const graphType = $calculation.element('radioGraphType').getValue();
if (graphType !== 100_000_003) return;
const seasonType = $calculation.element('selectSeasonType').getValue();
const highSeasonStartOption = $calculation.element('selectHighSeasonStart').getOption();
if (!seasonType || !highSeasonStartOption) return;
const seasonType = $calculation.element('selectSeasonType').getValue();
const highSeasonStartOption = $calculation.element('selectHighSeasonStart').getOption();
if (!seasonType || !highSeasonStartOption) return;
const shiftNumber = Number.parseInt(highSeasonStartOption.label, 10) - 2;
const unshiftedNextSeasons = shift(nextSeasons, -shiftNumber);
const unshiftedPrevSeasons = shift(prevSeasons, -shiftNumber);
const shiftNumber = Number.parseInt(highSeasonStartOption.label, 10) - 2;
const unshiftedNextSeasons = shift(nextSeasons, -shiftNumber);
const unshiftedPrevSeasons = shift(prevSeasons, -shiftNumber);
const changes = difference(unshiftedNextSeasons, unshiftedPrevSeasons);
if (changes === null || changes.length > 1) return;
const changes = difference(unshiftedNextSeasons, unshiftedPrevSeasons);
if (changes === null || changes.length > 1) return;
const [changeIndex] = changes;
const positionIndex = getPositionIndex(seasonType, changeIndex);
const [changeIndex] = changes;
const positionIndex = getPositionIndex(seasonType, changeIndex);
const values = getSeasonsValues(seasonType, unshiftedNextSeasons);
values[positionIndex] = unshiftedNextSeasons[changeIndex];
const values = getSeasonsValues(seasonType, unshiftedNextSeasons);
values[positionIndex] = unshiftedNextSeasons[changeIndex];
const seasons = generateSeasons(seasonType, values);
const leasingPeriod = $calculation.element('tbxLeasingPeriod').getValue();
const payments = generateSeasonsPayments(leasingPeriod, shift(seasons, shiftNumber));
const rows: Row[] = generateSeasonPaymentsRows(seasonType, shiftNumber, payments);
const firstPaymentPerc = $calculation.element('tbxFirstPaymentPerc').getValue();
const lastPaymentPerc = $calculation.element('tbxLastPaymentPerc').getValue();
const seasons = generateSeasons(seasonType, values);
const leasingPeriod = $calculation.element('tbxLeasingPeriod').getValue();
const payments = generateSeasonsPayments(leasingPeriod, shift(seasons, shiftNumber));
const rows: Row[] = generateSeasonPaymentsRows(seasonType, shiftNumber, payments);
const firstPaymentPerc = $calculation.element('tbxFirstPaymentPerc').getValue();
const lastPaymentPerc = $calculation.element('tbxLastPaymentPerc').getValue();
$tables.payments.setRows([
{
status: 'Disabled',
value: firstPaymentPerc,
},
...rows,
{
status: 'Disabled',
value: lastPaymentPerc,
},
]);
},
$tables.payments.setRows([
{
delay: 50,
equals: comparer.structural,
}
),
() => $process.has('LoadKP')
status: 'Disabled',
value: firstPaymentPerc,
},
...rows,
{
status: 'Disabled',
value: lastPaymentPerc,
},
]);
},
{
delay: 50,
equals: comparer.structural,
}
);
makeDisposable(
() =>
reaction(
() => $calculation.element('radioGraphType').getValue(),
() => {
$calculation.element('selectSeasonType').resetValue();
$calculation.element('selectHighSeasonStart').resetValue();
$calculation.element('tbxParmentsDecreasePercent').resetValue();
}
),
() => $process.has('LoadKP')
disposableReaction(
() => $process.has('LoadKP'),
() => $calculation.element('radioGraphType').getValue(),
() => {
$calculation.element('selectSeasonType').resetValue();
$calculation.element('selectHighSeasonStart').resetValue();
$calculation.element('tbxParmentsDecreasePercent').resetValue();
}
);
}

View File

@ -2,7 +2,7 @@ import { VAT } from '@/constants/values';
import * as CRMTypes from '@/graphql/crm.types';
import type { ProcessContext } from '@/process/types';
import { reaction } from 'mobx';
import { makeDisposable, round } from 'tools';
import { disposableReaction, round } from 'tools';
export default function reactions({ store, apolloClient }: ProcessContext) {
const { $calculation, $process } = store;
@ -35,25 +35,23 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
/**
* Расчет размера скидки поставщика в валюте
*/
makeDisposable(
() =>
reaction(
() => $calculation.$values.getValues(['leaseObjectPrice', 'supplierDiscountRub']),
({ leaseObjectPrice, supplierDiscountRub }) => {
// NaN fix
if (leaseObjectPrice === 0) {
$calculation.element('tbxSupplierDiscountPerc').resetValue();
} else {
$calculation
.element('tbxSupplierDiscountPerc')
.setValue((supplierDiscountRub / leaseObjectPrice) * 100);
}
},
{
fireImmediately: true,
}
),
() => $process.has('LoadKP')
disposableReaction(
() => $process.has('LoadKP'),
() => $calculation.$values.getValues(['leaseObjectPrice', 'supplierDiscountRub']),
({ leaseObjectPrice, supplierDiscountRub }) => {
// NaN fix
if (leaseObjectPrice === 0) {
$calculation.element('tbxSupplierDiscountPerc').resetValue();
} else {
$calculation
.element('tbxSupplierDiscountPerc')
.setValue((supplierDiscountRub / leaseObjectPrice) * 100);
}
},
{
fireImmediately: true,
}
);
/**
@ -117,19 +115,14 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
}
);
makeDisposable(
() =>
reaction(
() => $calculation.element('tbxFirstPaymentRub').getValue(),
(firstPaymentRub) => {
const { plPriceRub, addEquipmentPrice, importProgramSum } =
$calculation.$values.getValues();
const perc =
(firstPaymentRub / (plPriceRub + addEquipmentPrice - importProgramSum)) * 100;
$calculation.element('tbxFirstPaymentPerc').setValue(perc);
}
),
() => $process.has('LoadKP')
disposableReaction(
() => $process.has('LoadKP'),
() => $calculation.element('tbxFirstPaymentRub').getValue(),
(firstPaymentRub) => {
const { plPriceRub, addEquipmentPrice, importProgramSum } = $calculation.$values.getValues();
const perc = (firstPaymentRub / (plPriceRub + addEquipmentPrice - importProgramSum)) * 100;
$calculation.element('tbxFirstPaymentPerc').setValue(perc);
}
);
reaction(
@ -146,63 +139,53 @@ export default function reactions({ store, apolloClient }: ProcessContext) {
}
);
makeDisposable(
() =>
reaction(
() => $calculation.element('tbxComissionRub').getValue(),
(comissionRub) => {
const { plPriceRub, addEquipmentPrice, importProgramSum } =
$calculation.$values.getValues();
const perc = (comissionRub / (plPriceRub + addEquipmentPrice - importProgramSum)) * 100;
$calculation.element('tbxComissionPerc').setValue(perc);
}
),
() => $process.has('LoadKP')
disposableReaction(
() => $process.has('LoadKP'),
() => $calculation.element('tbxComissionRub').getValue(),
(comissionRub) => {
const { plPriceRub, addEquipmentPrice, importProgramSum } = $calculation.$values.getValues();
const perc = (comissionRub / (plPriceRub + addEquipmentPrice - importProgramSum)) * 100;
$calculation.element('tbxComissionPerc').setValue(perc);
}
);
makeDisposable(
disposableReaction(
() => $process.has('LoadKP'),
() =>
reaction(
() =>
$calculation.$values.getValues([
'plPriceRub',
'lastPaymentPerc',
'addEquipmentPrice',
'importProgramSum',
'lastPaymentRule',
]),
({ addEquipmentPrice, lastPaymentPerc, plPriceRub, importProgramSum, lastPaymentRule }) => {
if (lastPaymentRule === 100_000_000) {
return;
}
$calculation.$values.getValues([
'plPriceRub',
'lastPaymentPerc',
'addEquipmentPrice',
'importProgramSum',
'lastPaymentRule',
]),
({ addEquipmentPrice, lastPaymentPerc, plPriceRub, importProgramSum, lastPaymentRule }) => {
if (lastPaymentRule === 100_000_000) {
return;
}
const rub = (lastPaymentPerc * (plPriceRub + addEquipmentPrice - importProgramSum)) / 100;
$calculation.element('tbxLastPaymentRub').setValue(rub);
}
),
() => $process.has('LoadKP')
const rub = (lastPaymentPerc * (plPriceRub + addEquipmentPrice - importProgramSum)) / 100;
$calculation.element('tbxLastPaymentRub').setValue(rub);
}
);
makeDisposable(
disposableReaction(
() => $process.has('LoadKP'),
() =>
reaction(
() =>
$calculation.$values.getValues([
'plPriceRub',
'lastPaymentRub',
'addEquipmentPrice',
'importProgramSum',
'lastPaymentRule',
]),
({ lastPaymentRub, plPriceRub, addEquipmentPrice, importProgramSum, lastPaymentRule }) => {
if (lastPaymentRule === 100_000_001) {
return;
}
$calculation.$values.getValues([
'plPriceRub',
'lastPaymentRub',
'addEquipmentPrice',
'importProgramSum',
'lastPaymentRule',
]),
({ lastPaymentRub, plPriceRub, addEquipmentPrice, importProgramSum, lastPaymentRule }) => {
if (lastPaymentRule === 100_000_001) {
return;
}
const perc = (lastPaymentRub / (plPriceRub + addEquipmentPrice - importProgramSum)) * 100;
$calculation.element('tbxLastPaymentPerc').setValue(perc);
}
),
() => $process.has('LoadKP')
const perc = (lastPaymentRub / (plPriceRub + addEquipmentPrice - importProgramSum)) * 100;
$calculation.element('tbxLastPaymentPerc').setValue(perc);
}
);
}

View File

@ -9,7 +9,7 @@ import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { reaction } from 'mobx';
import { uid } from 'radash';
import { debouncedReaction, makeDisposable, normalizeOptions } from 'tools';
import { debouncedReaction, disposableReaction, normalizeOptions } from 'tools';
dayjs.extend(utc);
@ -21,34 +21,27 @@ export function common({ store, apolloClient }: ProcessContext) {
() => $calculation.element('selectQuote').resetValue()
);
makeDisposable(
disposableReaction(
() => $calculation.element('cbxRecalcWithRevision').getValue() === true,
() =>
reaction(
() =>
$calculation.$values.getValues([
'discountRub',
'addEquipmentPrice',
'importProgramSum',
'plPriceRub',
]),
({ discountRub, importProgramSum, addEquipmentPrice, plPriceRub }) => {
const price = plPriceRub + addEquipmentPrice - importProgramSum;
const maxPriceChange =
price - discountRub < 800_000
? price - discountRub + 50_000
: (price - discountRub) * 1.05;
$calculation.$values.getValues([
'discountRub',
'addEquipmentPrice',
'importProgramSum',
'plPriceRub',
]),
({ discountRub, importProgramSum, addEquipmentPrice, plPriceRub }) => {
const price = plPriceRub + addEquipmentPrice - importProgramSum;
const maxPriceChange =
price - discountRub < 800_000 ? price - discountRub + 50_000 : (price - discountRub) * 1.05;
$calculation.element('tbxMaxPriceChange').setValue(maxPriceChange);
$calculation.element('tbxMaxPriceChange').setValue(maxPriceChange);
const minPriceChange =
price - discountRub < 800_000
? price - discountRub - 50_000
: (price - discountRub) * 0.95;
const minPriceChange =
price - discountRub < 800_000 ? price - discountRub - 50_000 : (price - discountRub) * 0.95;
$calculation.element('tbxMinPriceChange').setValue(minPriceChange);
}
),
() => $calculation.element('cbxRecalcWithRevision').getValue() === true
$calculation.element('tbxMinPriceChange').setValue(minPriceChange);
}
);
reaction(

View File

@ -6,7 +6,7 @@ import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { reaction } from 'mobx';
import { normalizeOptions } from 'tools/entity';
import { makeDisposable } from 'tools/mobx';
import { disposableReaction } from 'tools/mobx';
dayjs.extend(utc);
@ -61,34 +61,31 @@ export function fillAgentRewardSummReaction(
const { $calculation, $process } = store;
const { rewardConditionField, rewardSummField } = agentParams;
makeDisposable(
() =>
reaction(
() => $calculation.element(rewardConditionField).getValue(),
async (rewardConditionId) => {
if (!rewardConditionId) {
$calculation.element(rewardSummField).reset();
disposableReaction(
() => $process.has('LoadKP'),
() => $calculation.element(rewardConditionField).getValue(),
async (rewardConditionId) => {
if (!rewardConditionId) {
$calculation.element(rewardSummField).reset();
return;
}
return;
}
const {
data: { evo_reward_condition },
} = await apolloClient.query({
query: CRMTypes.GetRewardConditionDocument,
variables: {
conditionId: rewardConditionId,
},
});
const {
data: { evo_reward_condition },
} = await apolloClient.query({
query: CRMTypes.GetRewardConditionDocument,
variables: {
conditionId: rewardConditionId,
},
});
if (evo_reward_condition?.evo_reward_summ) {
$calculation.element(rewardSummField).setValue(evo_reward_condition.evo_reward_summ);
} else {
$calculation.element(rewardSummField).resetValue();
}
}
),
() => $process.has('LoadKP')
if (evo_reward_condition?.evo_reward_summ) {
$calculation.element(rewardSummField).setValue(evo_reward_condition.evo_reward_summ);
} else {
$calculation.element(rewardSummField).resetValue();
}
}
);
reaction(

View File

@ -6,7 +6,7 @@ import type { ProcessContext } from '@/process/types';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { reaction } from 'mobx';
import { makeDisposable } from 'tools/mobx';
import { disposableReaction } from 'tools/mobx';
const { fillIndAgent, fillCalcBroker, fillCalcDoubleAgent, fillFinDepartment } = fillAgentsFromLead;
const { fillAgentRewardReaction, fillAgentRewardSummReaction } = createReactions;
@ -33,18 +33,16 @@ export function common({ store, apolloClient }: ProcessContext) {
/**
* Заполняем агентов из Интереса
*/
makeDisposable(
() =>
reaction(
() => $calculation.element('selectLead').getValue(),
(leadid) => {
fillIndAgent(store, apolloClient, leadid);
fillCalcDoubleAgent(store, apolloClient, leadid);
fillCalcBroker(store, apolloClient, leadid);
fillFinDepartment(store, apolloClient, leadid);
}
),
() => $process.has('LoadKP')
disposableReaction(
() => $process.has('LoadKP'),
() => $calculation.element('selectLead').getValue(),
(leadid) => {
fillIndAgent(store, apolloClient, leadid);
fillCalcDoubleAgent(store, apolloClient, leadid);
fillCalcBroker(store, apolloClient, leadid);
fillFinDepartment(store, apolloClient, leadid);
}
);
/**

View File

@ -1,13 +1,23 @@
import type { IReactionDisposer, IReactionOptions, IReactionPublic } from 'mobx';
import { autorun, reaction } from 'mobx';
import { debounce } from 'radash';
import { debounce, omit } from 'radash';
export function makeDisposable(
createReaction: () => IReactionDisposer,
mustBeDisposed: () => boolean
export function disposableReaction<T, FireImmediately extends boolean = false>(
mustBeDisposed: () => boolean,
expression: (r: IReactionPublic) => T,
effect: (
arg: T,
prev: FireImmediately extends true ? T | undefined : T,
r: IReactionPublic
) => void,
reactionOpts?: IReactionOptions<T, FireImmediately>
) {
let disposer: IReactionDisposer | undefined;
if (!mustBeDisposed()) {
disposer = reaction(expression, effect, reactionOpts);
}
function cleanDisposer() {
disposer = undefined;
}
@ -17,7 +27,8 @@ export function makeDisposable(
if (disposer !== undefined) disposer();
cleanDisposer();
} else {
disposer = createReaction();
const opts = reactionOpts ? omit(reactionOpts, ['fireImmediately']) : undefined;
disposer = reaction(expression, effect, opts);
}
});
}