diff --git a/Components/Calculation/Form/Insurance/FinGAPTable/index.jsx b/Components/Calculation/Form/Insurance/FinGAPTable/index.jsx index 0e2bbe2..fc2f226 100644 --- a/Components/Calculation/Form/Insurance/FinGAPTable/index.jsx +++ b/Components/Calculation/Form/Insurance/FinGAPTable/index.jsx @@ -1,16 +1,39 @@ +import Alert from 'Elements/Alert'; import Table from 'Elements/Table'; +import { toJS } from 'mobx'; import { observer } from 'mobx-react-lite'; import { useStore } from 'stores/hooks'; +import styled from 'styled-components'; +import { Flex } from 'UIKit/grid'; import { columns } from './config'; +const Grid = styled(Flex)` + flex-direction: column; +`; + +const Validation = observer(() => { + const store = useStore(); + + const messages = store.$tables.fingap.validation.getMessages(); + + if (messages?.length) { + return ; + } + + return null; +}); + const FinGAPTable = observer(() => { const { $tables } = useStore(); const { fingap } = $tables; + const dataSource = toJS(fingap.risks); + const selectedRowKeys = [...toJS(fingap.selectedKeys)]; + return ( { @@ -23,6 +46,7 @@ const FinGAPTable = observer(() => { fingap.setSelectedKeys(selectedKeys); }, + selectedRowKeys, }} pagination={false} size="small" @@ -33,4 +57,11 @@ const FinGAPTable = observer(() => { ); }); -export default FinGAPTable; +export default function () { + return ( + + + + + ); +} diff --git a/Components/Calculation/addons/currency-addon.tsx b/Components/Calculation/addons/currency-addon.tsx index 09abcfc..b2499b7 100644 --- a/Components/Calculation/addons/currency-addon.tsx +++ b/Components/Calculation/addons/currency-addon.tsx @@ -1,7 +1,6 @@ -import { gql, useApolloClient } from '@apollo/client'; +import { gql, useQuery } from '@apollo/client'; import type * as CRMTypes from 'graphql/crm.types'; import { observer } from 'mobx-react-lite'; -import { useState } from 'react'; import { useStore } from 'stores/hooks'; const QUERY_GET_CURRENCY_SYMBOL = gql` @@ -17,26 +16,17 @@ const CurrencyAddon = observer(() => { const currencyid = $calculation.$values.getValue('supplierCurrency'); - const [currencySymbol, setCurrencySymbol] = useState(null); - - const { query } = useApolloClient(); - - if (!currencyid) return null; - - query({ - query: QUERY_GET_CURRENCY_SYMBOL, + const { data } = useQuery< + CRMTypes.GetCurrencySymbolQuery, + CRMTypes.GetCurrencySymbolQueryVariables + >(QUERY_GET_CURRENCY_SYMBOL, { variables: { currencyid, }, - }) - .then(({ data }) => { - setCurrencySymbol(data?.transactioncurrency?.currencysymbol); - }) - .catch(() => { - setCurrencySymbol(null); - }); + skip: !currencyid, + }); - return {currencySymbol}; + return {data?.transactioncurrency?.currencysymbol}; }); export default ; diff --git a/Dockerfile b/Dockerfile index cb0d116..d1743e8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -25,6 +25,8 @@ ARG NEXT_PUBLIC_URL_CRM_GRAPHQL_PROXY ARG NEXT_PUBLIC_URL_CRM_GRAPHQL_DIRECT ARG NEXT_PUBLIC_URL_GET_USER_PROXY ARG NEXT_PUBLIC_URL_GET_USER_DIRECT +ARG NEXT_PUBLIC_URL_CORE_FINGAP_PROXY +ARG NEXT_PUBLIC_URL_CORE_FINGAP_DIRECT # Next.js collects completely anonymous telemetry data about general usage. # Learn more here: https://nextjs.org/telemetry diff --git a/api/core/query.ts b/api/core/query.ts new file mode 100644 index 0000000..74d03c8 --- /dev/null +++ b/api/core/query.ts @@ -0,0 +1,9 @@ +/* eslint-disable import/prefer-default-export */ +import axios from 'axios'; +import type { RequestFinGAP, ResponseFinGAP } from './types'; + +export async function calculateFinGAP(payload: RequestFinGAP, signal?: AbortSignal) { + return axios.post(process.env.NEXT_PUBLIC_URL_CORE_FINGAP_PROXY!, payload, { + signal, + }); +} diff --git a/api/core/types.ts b/api/core/types.ts new file mode 100644 index 0000000..2a66d8d --- /dev/null +++ b/api/core/types.ts @@ -0,0 +1,21 @@ +export type PaymentRow = { + numberPayment?: number; + percentPayment: number; +}; + +export type RequestFinGAP = { + calcType: number; + payments: Array; + values: { + plPrice: number; + discount: number; + firstPayment: number; + leasingPeriod: number; + premiumPerc: number; + }; +}; + +export type ResponseFinGAP = { + sum: number; + premium: number; +}; diff --git a/config/default-values.ts b/config/default-values.ts index c62a013..16308b6 100644 --- a/config/default-values.ts +++ b/config/default-values.ts @@ -135,6 +135,8 @@ const defaultValues: CalculationValues = { importProgramSum: 0, addEquipmentPrice: 0, bonusCoefficient: 1, + plPriceRub: 0, + discountRub: 0, }; export default defaultValues; diff --git a/graphql/crm.schema.graphql b/graphql/crm.schema.graphql index 40b5fb4..12301b3 100644 --- a/graphql/crm.schema.graphql +++ b/graphql/crm.schema.graphql @@ -74,7 +74,7 @@ type Query { evo_client_types(statecode: Int): [evo_client_type] evo_coefficients(evo_client_riskid: Uuid, evo_client_typeid: Uuid, evo_corfficient_type: Int, evo_datefrom_param: DateParamInput, evo_dateto_param: DateParamInput, evo_job_titleid: Uuid, evo_max_period_param: DecimalParamInput, evo_min_period_param: DecimalParamInput, statecode: Int): [evo_coefficient] evo_contract(evo_contractid: Uuid!): evo_contract - evo_contracts(evo_accountid: Uuid, evo_name: String, statecode: Int): [evo_contract] + evo_contracts(evo_accountid: Uuid, evo_name: String, orderby: OrderByInput, statecode: Int): [evo_contract] evo_countries(evo_code_numeric: String): [evo_countryGraphQL] evo_country(evo_countryid: Uuid!): evo_countryGraphQL evo_currencychanges(evo_coursedate_param: DateParamInput, evo_ref_transactioncurrency: Uuid, statecode: Int): [evo_currencychange] @@ -108,15 +108,19 @@ type Query { """Регион. statecode по умолчанию 0""" evo_regions(evo_businessunit_evolution: Boolean, evo_creditregistry_id: Int, statecode: Int): [evo_region] + evo_request_client(evo_request_clientid: Uuid!): evo_request_client evo_request_payment(evo_request_paymentid: Uuid!): evo_request_payment evo_request_payments(evo_id: String, evo_name: String, statecode: Int): [evo_request_payment] evo_reward_condition(evo_reward_conditionid: Uuid!): evo_reward_condition evo_reward_conditions(evo_agency_agreementid_param: GuidParamInput, evo_agent_accountid: Uuid, evo_datefrom_param: DateParamInput, evo_dateto_param: DateParamInput, statecode: Int): [evo_reward_condition] + evo_scheduled_call(evo_scheduled_callid: Uuid!): evo_scheduled_call + evo_scheduled_calls(evo_inn: String, evo_status: [Int!], evo_telephone1: String, evo_telephone2: String, statecode: Int): [evo_scheduled_call] evo_sot_coefficient_types(statecode: Int): [evo_sot_coefficient_type] evo_statuscode(evo_id: String, evo_statuscodeid: Uuid): evo_statuscode evo_statuscodes(statecode: Int): [evo_statuscode] evo_subject_incidents(statecode: Int): [evo_subject_incident] evo_subsidies(evo_datefrom_param: DateParamInput, evo_dateto_param: DateParamInput, statecode: Int): [evo_subsidy] + evo_subsidy(evo_subsidyid: Uuid!): evo_subsidy evo_tarif(evo_tarifid: Uuid!): evo_tarif evo_tarifs(evo_balance_holder: [Int!], evo_baseproductid: Uuid, evo_datefrom_param: DateParamInput, evo_dateto_param: DateParamInput, evo_graphtype_exception: [Int!], evo_ins_type: [Int!], evo_max_first_payment_param: DecimalParamInput, evo_max_last_payment_param: DecimalParamInput, evo_max_period_param: DecimalParamInput, evo_min_first_payment_param: DecimalParamInput, evo_min_last_payment_param: DecimalParamInput, evo_min_period_param: DecimalParamInput, evo_used: Boolean, statecode: Int): [evo_tarif] evo_town(evo_fias_id: String, evo_townid: Uuid): evo_town @@ -153,7 +157,7 @@ type Query { """Поставщики ЮЛ салона. statecode по умолчанию 0""" salon_providers(salonaccountid: Uuid!, statecode: Int): [account] systemuser(domainname: String, systemuserid: Uuid): systemuser - systemusers(evo_employee_id: String, isdisabled: Boolean = false): [systemuser] + systemusers(domainname: String, evo_employee_id: String, isdisabled: Boolean = false): [systemuser] templates(description: String): [template] """Валюта. statecode по умолчанию 0""" @@ -165,19 +169,40 @@ type Mutation { by(systemuserid: Uuid): MutationBy } -type entity_schema { - entity_id: String - entity_set_name: String - icon_large_name: String - icon_medium_name: String - icon_small_name: String - logical_name: String - object_type_code: Int! - picklists: [picklist] +type evo_request_client { + createdon: DateTime + evo_accountid: Uuid + evo_accountidData: account + evo_caseorigincode: Int + evo_caseorigincodename: String + evo_client_request_text: String + evo_comment: String + evo_documents: [evo_document] + evo_number: String + evo_owner_systemuserid: Uuid + evo_owner_systemuseridData: systemuser + evo_phonecallid: Uuid + evo_request_clientid: Uuid + evo_site_email: String + evo_site_name: String + evo_site_telephone: String + evo_site_text: String + evo_statuscodeid: Uuid + evo_statuscodeidData: evo_statuscode + evo_storage: String + incidents: [incidentGraphQL] + link: String + modifiedon: DateTime + toObjectString: String } scalar Uuid +input OrderByInput { + fieldName: String + sortingType: SortingType! +} + input StringParamInput { eq: String } @@ -213,9 +238,63 @@ input GuidParamInput { """The built-in `Decimal` scalar type.""" scalar Decimal -input OrderByInput { - fieldName: String - sortingType: SortingType! +type evo_subject_incident { + createdon: DateTime + evo_group: Int + evo_groupname: String + evo_name: String + evo_subjectid: Uuid + evo_subject_incidentid: Uuid + evo_type_incident: Int + evo_type_incidentname: String + link: String + modifiedon: DateTime + toObjectString: String +} + +type incidentGraphQL { + caseorigincode: Int + createdon: DateTime + customerid: Uuid + customerid_account: Uuid + customerid_contact: Uuid + description: String + evo_accountid_new: Uuid + evo_cession_opportunityid: Uuid + evo_contracts: [evo_contract] + evo_creat_request_client: Uuid + evo_fast_advice: Boolean + evo_plan_execut_date: DateTime + evo_statuscodeid: Uuid + evo_statuscodeidData: evo_statuscode + evo_storage: String + evo_subject_incidentid: Uuid + evo_subject_incidentidData: evo_subject_incident + evo_taken_work_date: DateTime + evo_typedocpackageid: Uuid + incidentid: Uuid + link: String + modifiedon: DateTime + ownerid: Uuid + owneridData: systemuser + ownerid_systemuser: Uuid + ownerid_team: Uuid + subjectid: Uuid + subjectidData: subjectGraphQL + ticketnumber: String + title: String + toObjectString: String +} + +type entity_schema { + entity_id: String + entity_set_name: String + icon_large_name: String + icon_medium_name: String + icon_small_name: String + logical_name: String + object_type_code: Int! + picklists: [picklist] } type evo_debtwork_contract { @@ -341,7 +420,6 @@ type account { evo_ifns_code_branch: String evo_ifns_name: String evo_inn: String - evo_insurance_agent_accountid: Uuid evo_invoice_number_fix: String evo_invoice_number_rules: Int evo_kpp: String @@ -361,16 +439,21 @@ type account { evo_orglegalformid: Uuid evo_orglegalformidData: evo_orglegalform evo_osago_with_kasko: Boolean + evo_request_clients: [evo_request_client] + evo_return_leasing_dealer: Boolean evo_smb_category: Int evo_smb_issue_date: DateTime + evo_special_accounting: Int evo_state_actuality_date: DateTime evo_state_liquidation_date: DateTime evo_state_registration_date: DateTime evo_state_status: Int - evo_storage: String evo_subsidies(statecode: Int): [evo_subsidy] + evo_supplier_type: Int evo_tax_system: Int evo_type_ins_policy: [Int!] + evo_unscrupulous_supplier: Boolean + incidents: [incidentGraphQL] link: String modifiedon: DateTime name: String @@ -382,6 +465,8 @@ type account { ownerid_team: Uuid statecode: Int telephone1: String + telephone2: String + telephone3: String toObjectString: String } @@ -523,7 +608,6 @@ type evo_graph { evo_cost_price_telematics_withoutnds_sum: Decimal evo_cost_telematics_sum: Decimal evo_cost_telematics_withoutnds_sum: Decimal - evo_graf_date_approve: DateTime evo_graphid: Uuid evo_name: String evo_nds: Decimal @@ -543,6 +627,7 @@ type evo_insurance_period { evo_age_drivers: Int evo_base_reward_factor: Decimal evo_base_reward_rub: Decimal + evo_calc_dateend: DateTime evo_change_insurer_accountid: Uuid evo_close: Boolean evo_comment: String @@ -551,6 +636,7 @@ type evo_insurance_period { evo_dateto: DateTime evo_dgo_price: Decimal evo_elt_id: String + evo_evokasko_price: Decimal evo_exp_drivers: Int evo_franchise: Decimal evo_id: String @@ -686,7 +772,6 @@ type evo_leasingobject { evo_color: String evo_contractid: Uuid evo_create_contract_purchase: Boolean - evo_date_withdrawal: DateTime evo_delivery_time: Int evo_driving_axle: String evo_ecological_class: Int @@ -814,6 +899,7 @@ type lead { evo_new_client: String evo_opportunityid: Uuid evo_opportunityidData: opportunity + evo_scheduled_callid: Uuid evo_statuscodeid: Uuid evo_supplier_accountid: Uuid evo_utm_campaign: String @@ -822,6 +908,7 @@ type lead { evo_utm_source: String evo_utm_term: String fullname: String + jobtitle: String leadid: Uuid leadsourcecode: Int link: String @@ -848,6 +935,7 @@ type opportunity { evo_all_credit_evoprofi: Decimal evo_all_credit_evosmart: Decimal evo_approvallogs: [evo_approvallog] + evo_assignor_accountid: Uuid evo_businessunitid: Uuid evo_businessunitidData: businessunit evo_check_type: [Int!] @@ -894,6 +982,7 @@ type opportunity { evo_sfm_comment: [Int!] evo_solution_average_cost: Int evo_solution_average_cost_com: String + evo_solution_average_cost_reason: String evo_solution_db: Int evo_statuscodeid: Uuid evo_statuscodeidData: evo_statuscode @@ -934,6 +1023,7 @@ type quote { evo_agent_accountid: Uuid evo_agent_reward_conditionid: Uuid evo_agent_reward_summ: Decimal + evo_agent_reward_tech: Decimal evo_agent_reward_total: Decimal evo_age_drivers: Int evo_another_payments: Decimal @@ -947,6 +1037,7 @@ type quote { evo_broker_accountid: Uuid evo_broker_reward_conditionid: Uuid evo_broker_reward_summ: Decimal + evo_broker_reward_tech: Decimal evo_broker_reward_total: Decimal evo_calc_irr: Decimal evo_calc_profit: Decimal @@ -955,6 +1046,7 @@ type quote { evo_card_quote: Boolean evo_category: Int evo_category_tr: Int + evo_check_average_result: Int evo_check_ins_result: Int evo_client_riskid: Uuid evo_client_typeid: Uuid @@ -968,8 +1060,10 @@ type quote { evo_dealer_broker_accountid: Uuid evo_dealer_broker_reward_conditionid: Uuid evo_dealer_broker_reward_summ: Decimal + evo_dealer_broker_reward_tech: Decimal evo_dealer_broker_reward_total: Decimal evo_dealer_person_accountid: Uuid + evo_dealer_person_reward_tech: Decimal evo_dealer_reward_conditionid: Uuid evo_dealer_reward_summ: Decimal evo_dealer_reward_total: Decimal @@ -980,6 +1074,7 @@ type quote { evo_declaration_year: Int evo_delivery_time: Int evo_dgo_price: Decimal + evo_diagnostic: Int evo_director_bonus: Decimal evo_director_fingap_bonus: Decimal evo_director_nsib_bonus: Decimal @@ -990,6 +1085,7 @@ type quote { evo_double_agent_accountid: Uuid evo_double_agent_reward_conditionid: Uuid evo_double_agent_reward_summ: Decimal + evo_double_agent_reward_tech: Decimal evo_double_agent_reward_total: Decimal evo_economic: Decimal evo_economic_with_nds: Decimal @@ -999,6 +1095,7 @@ type quote { evo_equipmentid: Uuid evo_equip_price: Decimal evo_equity_capital: Decimal + evo_evokasko_price: Decimal evo_exp_drivers: Int evo_fingap_accountid: Uuid evo_fingap_bonus_sum: Decimal @@ -1009,6 +1106,7 @@ type quote { evo_fin_department_accountid: Uuid evo_fin_department_reward_conditionid: Uuid evo_fin_department_reward_summ: Decimal + evo_fin_department_reward_tech: Decimal evo_fin_department_reward_total: Decimal evo_first_dgo_price: Decimal evo_first_kasko_accountid: Uuid @@ -1147,6 +1245,7 @@ type quote { evo_report_year: Int evo_req_telematic: Int evo_req_telematic_accept: Int + evo_return_leasing: Boolean evo_risk: Int evo_risk_coefficientid: Uuid evo_risk_profit_coefficientid: Uuid @@ -1163,6 +1262,7 @@ type quote { evo_subsidy_summ: Decimal evo_supplier_accountid: Uuid evo_supplier_currency_price: Decimal + evo_supplier_type: Int evo_tarifid: Uuid evo_tax_period: Decimal evo_telematic: Boolean @@ -1359,6 +1459,29 @@ type evo_gps_model { toObjectString: String } +type evo_scheduled_call { + createdon: DateTime + evo_accountid: Uuid + evo_channel: String + evo_comment: String + evo_company_name: String + evo_contact_jobtitle: String + evo_contact_lastname: String + evo_contact_name: String + evo_inn: String + evo_leadid: Uuid + evo_name: String + evo_note: String + evo_scheduled_callid: Uuid + evo_scheduled_time: DateTime + evo_status: Int + evo_telephone1: String + evo_telephone2: String + modifiedon: DateTime + ownerid: Uuid + toObjectString: String +} + type evo_impairment_group { createdon: DateTime evo_impairment_groupid: Uuid @@ -1415,13 +1538,13 @@ type evo_request_payment { evo_finegibddidData: evo_finegibdd evo_id: String evo_inn: String - evo_insurance_addcontractid: Uuid evo_insurance_periodid: Uuid evo_insurance_policyid: Uuid evo_insurance_policyidData: evo_insurance_policy evo_kpp: String evo_leasingobjectid: Uuid evo_name: String + evo_new_version: Boolean evo_number_dkp: String evo_oktmo_mreo: String evo_opportunityid: Uuid @@ -1442,9 +1565,11 @@ type evo_request_payment { evo_region_director_systemuserid: Uuid evo_request_paymentid: Uuid evo_request_payment_type: Int + evo_service_list: [Int!] evo_statuscodeid: Uuid evo_storage: String evo_supplier_payment_type: Int + evo_top_agency_agreementid: Uuid evo_transactioncurrencyid: Uuid evo_transfer_contact: Boolean evo_vat: Decimal @@ -1466,10 +1591,13 @@ type evo_contract { evo_add_bonus_summ: Decimal evo_add_director_bonus: Decimal evo_add_region_director_bonus: Decimal + evo_advance_pay_long_delivery: Decimal evo_agent_accountid: Uuid + evo_agent_request_paymentid: Uuid evo_agent_reward: Decimal evo_agent_reward_conditionid: Uuid evo_agent_reward_summ: Decimal + evo_agent_service_list: [Int!] evo_approvallogs: [evo_approvallog] evo_balance_holder: Int evo_bank_detailsid: Uuid @@ -1477,9 +1605,11 @@ type evo_contract { evo_base_calc_pay: Decimal evo_bonus_pay_systemuserid: Uuid evo_broker_accountid: Uuid + evo_broker_request_paymentid: Uuid evo_broker_reward: Decimal evo_broker_reward_conditionid: Uuid evo_broker_reward_summ: Decimal + evo_broker_service_list: [Int!] evo_businessunitid: Uuid evo_calc_irr: Decimal evo_calc_profit: Decimal @@ -1495,26 +1625,31 @@ type evo_contract { evo_contract_status_1cname: String evo_contract_status_change_date_in_crm: DateTime evo_contract_status_date_1c: DateTime + evo_cre_uuid: String evo_dateend: DateTime evo_date_of_pledge_claim: DateTime evo_date_of_pledge_leasobject: DateTime evo_date_termination: DateTime evo_dealer_broker_accountid: Uuid + evo_dealer_broker_request_paymentid: Uuid evo_dealer_broker_reward: Decimal evo_dealer_broker_reward_conditionid: Uuid evo_dealer_broker_reward_summ: Decimal + evo_dealer_broker_service_list: [Int!] evo_dealer_person_accountid: Uuid evo_dealer_person_accountidData: account + evo_dealer_person_request_paymentid: Uuid evo_dealer_person_reward: Decimal evo_dealer_person_reward_conditionid: Uuid evo_dealer_person_reward_summ: Decimal + evo_dealer_person_service_list: [Int!] evo_debtwork_contractid: Uuid + evo_debtwork_contractidData: evo_debtwork_contract evo_debtwork_contracts: [evo_debtwork_contract] evo_debt_leasing: Decimal evo_debt_penalty_fee: Decimal evo_debt_total: Decimal evo_delay_days_count: Int - evo_delay_period: DateTime evo_director_bonus: Decimal evo_director_fingap_bonus: Decimal evo_director_nsib_bonus: Decimal @@ -1522,12 +1657,15 @@ type evo_contract { evo_discount_supplier_currency: Decimal evo_docdate: DateTime evo_docdate_dkp: DateTime + evo_documents: [evo_document] evo_dogovortype: Int evo_dog_credit: Decimal evo_double_agent_accountid: Uuid + evo_double_agent_request_paymentid: Uuid evo_double_agent_reward: Decimal evo_double_agent_reward_conditionid: Uuid evo_double_agent_reward_summ: Decimal + evo_double_agent_service_list: [Int!] evo_economic: Decimal evo_economic_actual: Decimal evo_economic_with_nds: Decimal @@ -1542,9 +1680,11 @@ type evo_contract { evo_fingap_period: Int evo_finmon_message_date: DateTime evo_fin_department_accountid: Uuid + evo_fin_department_request_paymentid: Uuid evo_fin_department_reward: Decimal evo_fin_department_reward_conditionid: Uuid evo_fin_department_reward_summ: Decimal + evo_fin_department_service_list: [Int!] evo_first_payment_fact: Decimal evo_first_payment_fact_date: DateTime evo_first_payment_perc: Decimal @@ -1552,6 +1692,7 @@ type evo_contract { evo_first_payment_rub: Decimal evo_first_payment_rub_without_subsidy: Decimal evo_forwarder_contactid: Uuid + evo_for_export_cre: Boolean evo_fuel_card_addproductid: Uuid evo_fuel_card_addproduct_typeid: Uuid evo_graphs(statecode: Int): [evo_graph] @@ -1568,6 +1709,10 @@ type evo_contract { evo_irr_msfo_final_actual: Decimal evo_issue_date_buh: DateTime evo_issue_place_addressid: Uuid + evo_issue_without_pay: Boolean + evo_issue_without_pay_comm: String + evo_last_formation_cre_date: DateTime + evo_last_formation_cre_status: Int evo_last_payment_redemption: Boolean evo_leasingobjectid: Uuid evo_leasingobjectidData: evo_leasingobject @@ -1580,7 +1725,6 @@ type evo_contract { evo_name: String evo_nds_in_price_supplier_currency: Decimal evo_nds_perc: Decimal - evo_nearest_payment_num: String evo_net_irr: Decimal evo_niatinception_msfo: Decimal evo_niatinception_msfo_actual: Decimal @@ -1633,13 +1777,16 @@ type evo_contract { evo_supplier_bank_detailsidData: evo_bank_details evo_supplier_currency_price: Decimal evo_supplier_pay1_sum: Decimal + evo_supplier_pay2_sum: Decimal evo_supplier_payfull_date: DateTime evo_supplier_pay_actual: Decimal evo_supplier_pay_actual_currency: Decimal evo_supplier_signer_contactid: Uuid + evo_supplier_type: Int evo_tarifid: Uuid evo_telematics_addproduct_typeid: Uuid evo_telematics_addproduct_typeid_new: Uuid + evo_telematics_equipment2_addproductid: Uuid evo_telematics_equipment_addproductid: Uuid evo_telematics_equipment_addproductidData: evo_addproduct evo_telematics_service_addproductid: Uuid @@ -1899,6 +2046,7 @@ type evo_address { evo_federal_district: String evo_fias: Boolean evo_fias_code: String + evo_fias_id: String evo_fias_level: Int evo_flat: String evo_flat_type: String @@ -1909,6 +2057,8 @@ type evo_address { evo_house_fias_id: String evo_house_type: String evo_house_type_full: String + evo_okato: String + evo_oktmo: String evo_postal_box: String evo_postal_code: String evo_region: String @@ -1937,8 +2087,11 @@ type systemuser { businessunitidData: businessunit createdon: DateTime domainname: String + evo_available_assignment_director: Boolean evo_baseproducts(statecode: Int): [evo_baseproduct] evo_callrecords_access: Boolean + evo_can_export_cre: Boolean + evo_can_import_sheduled_calls: Boolean evo_datebirth: DateTime evo_employee_id: String evo_fedresurs_rules: Boolean @@ -2025,23 +2178,33 @@ type evo_agency_agreement { evo_agency_agreement_type: Int evo_agent_accountid: Uuid evo_agent_accountidData: account + evo_agent_type: Int + evo_agreement_date: DateTime evo_bank_detailsid: Uuid evo_boss_comment: String evo_boss_decision: Int + evo_branch_agreement: Boolean evo_businessunitid: Uuid evo_contactid: Uuid evo_datefrom: DateTime evo_dateto: DateTime evo_date_change_statuscode: DateTime + evo_decentral: Boolean evo_director_comment: String evo_director_decision: Int evo_leasingobject_price: Int + evo_location: String evo_name: String + evo_new_version: Boolean evo_number: Int + evo_pay_period: Int evo_region_director_comment: String evo_region_director_decision: Int evo_required_reward: Boolean evo_reward_without_other_agent: Boolean + evo_select_lp: Boolean + evo_select_vin: Boolean + evo_service_period: Int evo_signer_systemuserid: Uuid evo_statuscodeid: Uuid evo_storage: String @@ -2053,7 +2216,9 @@ type evo_agency_agreement { evo_term_topboss_systemuserid: Uuid evo_topboss_comment: String evo_topboss_decision: Int + evo_top_agency_agreementid: Uuid evo_top_termination: Int + evo_untype_doc: Boolean modifiedon: DateTime ownerid_systemuser: Uuid ownerid_team: Uuid @@ -2073,6 +2238,7 @@ type evo_addcontract { evo_add_bonus_summ: Decimal evo_add_director_bonus: Decimal evo_add_region_director_bonus: Decimal + evo_agent_reward: Decimal evo_agent_reward_summ: Decimal evo_age_drivers: Int evo_age_drivers_new: Int @@ -2087,6 +2253,7 @@ type evo_addcontract { evo_base_bonus: Decimal evo_base_calc_pay: Decimal evo_base_new: String + evo_broker_reward: Decimal evo_broker_reward_summ: Decimal evo_businessunitid: Uuid evo_calculation_method: Int @@ -2144,6 +2311,7 @@ type evo_addcontract { evo_discount_supplier_currency_new: Decimal evo_dog_credit: Decimal evo_dog_credit_new: Decimal + evo_double_agent_reward: Decimal evo_double_agent_reward_summ: Decimal evo_driving_axle: String evo_driving_axle_new: String @@ -2171,8 +2339,10 @@ type evo_addcontract { evo_equip_price_new: Decimal evo_exp_drivers: Int evo_exp_drivers_new: Int + evo_fin_department_reward: Decimal evo_fin_department_reward_conditionid: Uuid evo_fin_department_reward_conditionid_new: Uuid + evo_fin_department_reward_new: Decimal evo_fin_department_reward_summ: Decimal evo_fin_department_reward_summ_new: Decimal evo_fix_last_payment: Boolean @@ -2183,6 +2353,7 @@ type evo_addcontract { evo_graph_irr: Decimal evo_importer_reward_rub: Decimal evo_insurance_change: Boolean + evo_insurance_checking: Boolean evo_insurance_period: Int evo_insurance_period_new: Int evo_insurance_price_result: Decimal @@ -2367,12 +2538,12 @@ type email { evo_accountid: Uuid modifiedon: DateTime regardingobjectid_account: Uuid - regardingobjectid_evo_addcontract: Uuid regardingobjectid_evo_contract: Uuid regardingobjectid_evo_insurance_period: Uuid regardingobjectid_evo_insurance_policy: Uuid regardingobjectid_evo_insurance_policyData: evo_insurance_policy regardingobjectid_evo_list: Uuid + regardingobjectid_incident: Uuid regardingobjectid_opportunity: Uuid statuscode: Int subject: String @@ -2431,99 +2602,22 @@ type evo_typedocpackage { evo_name: String evo_opportunity: Boolean evo_programsolution: [Int!] + evo_request_client: Boolean evo_request_payment: Boolean evo_typedocpackageid: Uuid modifiedon: DateTime toObjectString: String } -type evo_subject_incident { - createdon: DateTime - evo_group: Int - evo_groupname: String - evo_name: String - evo_subjectid: Uuid - evo_subject_incidentid: Uuid - evo_type_incident: Int - evo_type_incidentname: String - link: String - modifiedon: DateTime - toObjectString: String -} - -type incidentGraphQL { - createdon: DateTime - customerid: Uuid - customerid_account: Uuid - customerid_contact: Uuid - description: String - evo_fast_advice: Boolean - evo_plan_execut_date: DateTime - evo_statuscodeid: Uuid - evo_statuscodeidData: evo_statuscode - evo_storage: String - evo_subject_incidentid: Uuid - evo_subject_incidentidData: evo_subject_incident - evo_taken_work_date: DateTime - evo_typedocpackageid: Uuid - incidentid: Uuid - link: String - modifiedon: DateTime - ownerid: Uuid - owneridData: systemuser - subjectid: Uuid - ticketnumber: String - title: String - toObjectString: String -} - type MutationBy { associateBankDetailsAndAgencyAgreement_(evo_agency_agreementid: Uuid!, evo_bank_detailsid: Uuid!): Entity createEntity(data: EntityDataInput): Uuid! createIncident_(contracts: [Uuid!], customerid_account: Uuid, description: String, evo_fast_advice: Boolean, evo_subject_incidentid: Uuid, subjectid: Uuid, title: String): Entity + createScheduledCall_(evo_accountid: Uuid, evo_channel: String, evo_company_name: String, evo_contact_lastname: String, evo_contact_name: String, evo_inn: String, evo_name: String, evo_note: String, evo_scheduled_time: DateTime, evo_status: Int, evo_telephone1: String, ownerid: Uuid): Entity updateAccount_(accountid: Uuid!, evo_agency_agreementid: Uuid): Entity updateEntity(data: EntityDataInput): Boolean! } -type picklist { - name: String - values: [picklist_value] -} - -"""The `DateTime` scalar represents an ISO-8601 compliant date time type.""" -scalar DateTime - -input FilterInput { - fieldname: String - guidvalues: [Uuid] - intvalues: [Int!] - operation: FilterOperation! - stringvalues: [String] -} - -enum LogicOperation { - AND - OR -} - -enum SortingType { - DESC - ASC -} - -type businessunit { - businessunitid: Uuid - createdon: DateTime - evo_addressid: Uuid - evo_boss_systemuserid: Uuid - evo_director_systemuserid: Uuid - evo_region_director_systgemuserid: Uuid - evo_region_director_systgemuseridname: String - modifiedon: DateTime - name: String - toObjectString: String -} - type evo_document { createdon: DateTime evo_accountid: Uuid @@ -2551,6 +2645,53 @@ type evo_document { toObjectString: String } +"""The `DateTime` scalar represents an ISO-8601 compliant date time type.""" +scalar DateTime + +enum SortingType { + DESC + ASC +} + +input FilterInput { + fieldname: String + guidvalues: [Uuid] + intvalues: [Int!] + operation: FilterOperation! + stringvalues: [String] +} + +enum LogicOperation { + AND + OR +} + +type subjectGraphQL { + createdon: DateTime + modifiedon: DateTime + subjectid: Uuid + title: String + toObjectString: String +} + +type picklist { + name: String + values: [picklist_value] +} + +type businessunit { + businessunitid: Uuid + createdon: DateTime + evo_addressid: Uuid + evo_boss_systemuserid: Uuid + evo_director_systemuserid: Uuid + evo_region_director_systgemuserid: Uuid + evo_region_director_systgemuseridname: String + modifiedon: DateTime + name: String + toObjectString: String +} + type team { createdon: DateTime evo_baseproducts(statecode: Int): [evo_baseproduct] @@ -2665,24 +2806,6 @@ type Entity { logical_name: String } -type picklist_value { - color: String - label: String - order: Int! - value: Int! -} - -enum FilterOperation { - ISNULL - EQUAL - CONTAINS - NOTCONTAINS - MORETHEN - MOREOREQUALTHEN - LESSTHEN - LESSOREQUALTHEN -} - type evo_documenttype { createdon: DateTime evo_comment: String @@ -2701,6 +2824,24 @@ type evo_documenttype { toObjectString: String } +enum FilterOperation { + ISNULL + EQUAL + CONTAINS + NOTCONTAINS + MORETHEN + MOREOREQUALTHEN + LESSTHEN + LESSOREQUALTHEN +} + +type picklist_value { + color: String + label: String + order: Int! + value: Int! +} + input EntityFieldInput { activitypartiesvalue: [activitypartyInput] boolvalue: Boolean diff --git a/graphql/crm.types.ts b/graphql/crm.types.ts index 01db7d7..29c545b 100644 --- a/graphql/crm.types.ts +++ b/graphql/crm.types.ts @@ -122,6 +122,41 @@ export type GetCurrencySymbolQueryVariables = Exact<{ export type GetCurrencySymbolQuery = { __typename?: 'Query', transactioncurrency?: { __typename?: 'transactioncurrency', currencysymbol?: string | null } | null }; +export type GetAgentQueryVariables = Exact<{ + agentid: Scalars['Uuid']; +}>; + + +export type GetAgentQuery = { __typename?: 'Query', agent?: { __typename?: 'account', label?: string | null, value?: any | null } | null }; + +export type GetAgentAccountIdFromLeadQueryVariables = Exact<{ + leadid: Scalars['Uuid']; +}>; + + +export type GetAgentAccountIdFromLeadQuery = { __typename?: 'Query', lead?: { __typename?: 'lead', agentid?: any | null } | null }; + +export type GetDoubleAgentAccountIdQueryVariables = Exact<{ + leadid: Scalars['Uuid']; +}>; + + +export type GetDoubleAgentAccountIdQuery = { __typename?: 'Query', lead?: { __typename?: 'lead', agentid?: any | null } | null }; + +export type GetBrokerAccountIdQueryVariables = Exact<{ + leadid: Scalars['Uuid']; +}>; + + +export type GetBrokerAccountIdQuery = { __typename?: 'Query', lead?: { __typename?: 'lead', agentid?: any | null } | null }; + +export type GetFinDepartmentAccountIdQueryVariables = Exact<{ + leadid: Scalars['Uuid']; +}>; + + +export type GetFinDepartmentAccountIdQuery = { __typename?: 'Query', lead?: { __typename?: 'lead', agentid?: any | null } | null }; + export type GetDealerPersonQueryVariables = Exact<{ dealerId: Scalars['Uuid']; }>; @@ -136,13 +171,6 @@ export type GetBrokerAccountIdFromDealerQueryVariables = Exact<{ export type GetBrokerAccountIdFromDealerQuery = { __typename?: 'Query', dealer?: { __typename?: 'account', evo_broker_accountid?: any | null } | null }; -export type GetAgentQueryVariables = Exact<{ - agentid: Scalars['Uuid']; -}>; - - -export type GetAgentQuery = { __typename?: 'Query', agent?: { __typename?: 'account', label?: string | null, value?: any | null } | null }; - export type GetRewardConditionsQueryVariables = Exact<{ agentid: Scalars['Uuid']; currentDate?: InputMaybe; @@ -158,6 +186,13 @@ export type GetRewardSummQueryVariables = Exact<{ export type GetRewardSummQuery = { __typename?: 'Query', evo_reward_condition?: { __typename?: 'evo_reward_condition', evo_reward_summ?: any | null } | null }; +export type GetFinGapAddProductTypesQueryVariables = Exact<{ + currentDate?: InputMaybe; +}>; + + +export type GetFinGapAddProductTypesQuery = { __typename?: 'Query', evo_addproduct_types?: Array<{ __typename?: 'evo_addproduct_type', evo_addproduct_typeid?: any | null, evo_name?: string | null, evo_type_calc_cerebellum?: number | null, evo_cost_service_provider_withoutnds?: any | null, evo_addproduct_types?: Array<{ __typename?: 'evo_addproduct_type', evo_addproduct_typeid?: any | null } | null> | null } | null> | null }; + export type GetAddproductTypesQueryVariables = Exact<{ [key: string]: never; }>; @@ -206,6 +241,11 @@ export type GetOwnerDataQueryVariables = Exact<{ export type GetOwnerDataQuery = { __typename?: 'Query', selectLead?: Array<{ __typename?: 'lead', label?: string | null, value?: any | null } | null> | null, selectOpportunity?: Array<{ __typename?: 'opportunity', label?: string | null, value?: any | null } | null> | null }; +export type GetTransactionCurrenciesQueryVariables = Exact<{ [key: string]: never; }>; + + +export type GetTransactionCurrenciesQuery = { __typename?: 'Query', transactioncurrencies?: Array<{ __typename?: 'transactioncurrency', isocurrencycode?: string | null, transactioncurrencyid?: any | null } | null> | null }; + export type GetOpportunityByLeadQueryVariables = Exact<{ leadid: Scalars['Uuid']; }>; @@ -247,3 +287,17 @@ export type GetQuoteUrlQueryVariables = Exact<{ export type GetQuoteUrlQuery = { __typename?: 'Query', entity?: { __typename?: 'quote', link?: string | null } | null }; + +export type GetCurrencyChangesQueryVariables = Exact<{ + currentDate?: InputMaybe; +}>; + + +export type GetCurrencyChangesQuery = { __typename?: 'Query', evo_currencychanges?: Array<{ __typename?: 'evo_currencychange', evo_currencychange?: any | null, evo_ref_transactioncurrency?: any | null } | null> | null }; + +export type GetCurrencyIsoCodeQueryVariables = Exact<{ + id: Scalars['Uuid']; +}>; + + +export type GetCurrencyIsoCodeQuery = { __typename?: 'Query', transactioncurrency?: { __typename?: 'transactioncurrency', isocurrencycode?: string | null } | null }; diff --git a/mocks/handlers.js b/mocks/handlers.js index 29de392..c55e705 100644 --- a/mocks/handlers.js +++ b/mocks/handlers.js @@ -1,4 +1,5 @@ import { rest } from 'msw'; +import { random } from 'radash'; const users = { akalinina: { @@ -25,4 +26,12 @@ export const handlers = [ rest.get('http://auth_service/user', (req, res, ctx) => { return res(ctx.json(users.vchikalkin)); }), + rest.post('/api/core/fingap', (req, res, ctx) => { + return res( + ctx.json({ + sum: random(100000, 200000), + premium: random(1000, 10000), + }) + ); + }), ]; diff --git a/next.config.js b/next.config.js index 5b1a338..a05c537 100644 --- a/next.config.js +++ b/next.config.js @@ -28,6 +28,10 @@ const nextConfig = { source: process.env.NEXT_PUBLIC_URL_GET_USER_PROXY, destination: process.env.NEXT_PUBLIC_URL_GET_USER_DIRECT, }, + { + source: process.env.NEXT_PUBLIC_URL_CORE_FINGAP_PROXY, + destination: process.env.NEXT_PUBLIC_URL_CORE_FINGAP_DIRECT, + }, ]; }, }; diff --git a/package.json b/package.json index 259395d..39ed6a6 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,6 @@ "antd": "^4.21.3", "axios": "^0.27.2", "dayjs": "^1.11.2", - "graphql": "^16.6.0", "less": "^4.1.3", "less-loader": "^11.0.0", "mobx": "^6.5.0", diff --git a/pages/index.jsx b/pages/index.jsx index 5fecf1e..fc5ad4a 100644 --- a/pages/index.jsx +++ b/pages/index.jsx @@ -1,6 +1,6 @@ /* eslint-disable object-curly-newline */ import { useApolloClient } from '@apollo/client'; -import { dehydrate, QueryClient } from '@tanstack/react-query'; +import { dehydrate, QueryClient, useQueryClient } from '@tanstack/react-query'; import { getUser } from 'api/user/query'; import initializeApollo from 'apollo/client'; import * as Calculation from 'Components/Calculation'; @@ -41,10 +41,11 @@ const Grid = styled(Box)` function Home() { const store = useStore(); const apolloClient = useApolloClient(); + const queryClient = useQueryClient(); useEffect(() => { getData(apolloClient, store); - injectDefaultReactions(store, apolloClient); + injectDefaultReactions(store, apolloClient, queryClient); }, []); return ( diff --git a/process/calculate/reactions/validation.ts b/process/calculate/reactions/validation.ts index f3b3989..e6ed9f7 100644 --- a/process/calculate/reactions/validation.ts +++ b/process/calculate/reactions/validation.ts @@ -9,8 +9,9 @@ export default function validationReactions(store: RootStore, apolloClient: Apol const hasElementsErrors = $calculation.$validation.hasErrors; const hasPaymentsErrors = $tables.payments.validation.hasErrors; const hasInsuranceErrors = $tables.insurance.validation.hasErrors; + const hasFingapErrors = $tables.fingap.validation.hasErrors; - return hasElementsErrors || hasPaymentsErrors || hasInsuranceErrors; + return hasElementsErrors || hasPaymentsErrors || hasInsuranceErrors || hasFingapErrors; }, (hasErrors) => { if (hasErrors) { diff --git a/process/fingap/reactions/common.ts b/process/fingap/reactions/common.ts new file mode 100644 index 0000000..acb1451 --- /dev/null +++ b/process/fingap/reactions/common.ts @@ -0,0 +1,227 @@ +/* eslint-disable implicit-arrow-linebreak */ +/* eslint-disable unicorn/consistent-function-scoping */ +/* eslint-disable @typescript-eslint/naming-convention */ +import type { ApolloClient } from '@apollo/client'; +import { gql } from '@apollo/client'; +import type { QueryClient, QueryFunctionContext } from '@tanstack/react-query'; +import { calculateFinGAP } from 'api/core/query'; +import type { RequestFinGAP } from 'api/core/types'; +import type { Risk } from 'Components/Calculation/Form/Insurance/FinGAPTable/types'; +import dayjs from 'dayjs'; +import utc from 'dayjs/plugin/utc'; +import type * as CRMTypes from 'graphql/crm.types'; +import { comparer, reaction, toJS } from 'mobx'; +import type RootStore from 'stores/root'; + +dayjs.extend(utc); + +export default function commonReactions( + store: RootStore, + apolloClient: ApolloClient, + queryClient: QueryClient +) { + const { $calculation, $tables } = store; + // Расчет итоговой суммы ФинГАП и запись в таблицу страхования + reaction( + () => $tables.fingap.totalSum, + (totalSum) => { + $tables.insurance.setRowValues('fingap', { + insCost: totalSum, + }); + } + ); + + /** +Реакция на изменение Страховой компании у ФинГАП и Срока лизинга: + +Если Страхованя компания = Не выбрано, то + +Плательщик insuredFinGAP = ЛП (100 000 000) и закрыто для редактирования, +Стоимость за первый период inscostFinGAP = 0 +Срок страхования insTermFinGAP = 12 мес (100 000 000) и закрыто для редактирования + +иначе + +Плательщик insuredFinGAP = открыто для редактирования, +Стоимость за первый период inscostFinGAP = 0 +Срок страхования insTermFinGAP = Если срок лизинга tbxLeasingPeriod < 13, +то указываем Срок страхования insTermFinGAP = 12 мес +и закрываем для редактирования, иначе открыто для редактирования + */ + reaction( + () => { + const finGAPInsuranceCompany = $tables.insurance.getRowValue('fingap', 'insuranceCompany'); + const leasingPeriod = $calculation.getElementValue('tbxLeasingPeriod'); + + return { + finGAPInsuranceCompany, + leasingPeriod, + }; + }, + ({ finGAPInsuranceCompany, leasingPeriod }) => { + if (!finGAPInsuranceCompany) { + $tables.insurance.setRowValues('fingap', { + insured: 100_000_000, + insCost: 0, + insTerm: 100_000_000, + }); + + $tables.insurance.setRowStatuses('fingap', { + insured: 'Disabled', + insTerm: 'Disabled', + }); + } else { + $tables.insurance.setRowValues('fingap', { + insured: 100_000_000, + insCost: 0, + insTerm: leasingPeriod < 13 ? 100_000_000 : undefined, + }); + + $tables.insurance.setRowStatuses('fingap', { + insured: 'Default', + insTerm: leasingPeriod < 13 ? 'Disabled' : 'Default', + }); + } + }, + { + equals: comparer.shallow, + } + ); + + // Очищаем таблицу ФинГАП, если не выбрана страховая компания + reaction( + () => $tables.insurance.getRowValue('fingap', 'insuranceCompany'), + (finGAPInsuranceCompany) => { + if (!finGAPInsuranceCompany) { + $tables.fingap.clear(); + } + } + ); + + const QUERY_GET_FINGAP_ADDPRODUCT_TYPES = gql` + query GetFinGAPAddProductTypes($currentDate: DateTime) { + evo_addproduct_types( + statecode: 0 + evo_datefrom_param: { lte: $currentDate } + evo_dateto_param: { gte: $currentDate } + evo_product_type: 100000006 + ) { + evo_addproduct_typeid + evo_name + evo_type_calc_cerebellum + evo_cost_service_provider_withoutnds + evo_addproduct_types { + evo_addproduct_typeid + } + } + } + `; + + // Заполнение таблицы рисков ФинГАП + Запрос расчета финГАП в мозжечок + + reaction( + () => { + const finGAPInsuranceCompany = $tables.insurance.getRowValue('fingap', 'insuranceCompany'); + const paymentsValues = toJS($tables.payments.values); + const plPriceRub = $calculation.$values.getValue('plPriceRub'); + const discountRub = $calculation.$values.getValue('discountRub'); + const firstPaymentRub = $calculation.getElementValue('tbxFirstPaymentRub'); + const leasingPeriod = $calculation.getElementValue('tbxLeasingPeriod'); + + return { + finGAPInsuranceCompany, + paymentsValues, + plPriceRub, + discountRub, + firstPaymentRub, + leasingPeriod, + }; + }, + async ({ + finGAPInsuranceCompany, + paymentsValues, + plPriceRub, + discountRub, + firstPaymentRub, + leasingPeriod, + }) => { + if ($tables.fingap.validation.hasErrors) return; + if (!finGAPInsuranceCompany) return; + + const { + data: { evo_addproduct_types }, + } = await apolloClient.query< + CRMTypes.GetFinGapAddProductTypesQuery, + CRMTypes.GetFinGapAddProductTypesQueryVariables + >({ + query: QUERY_GET_FINGAP_ADDPRODUCT_TYPES, + variables: { + currentDate: dayjs().utc().format('YYYY-MM-DD'), + }, + }); + + const risks = evo_addproduct_types?.map( + // prettier-ignore + (evo_addproduct_type) => ({ + key: evo_addproduct_type?.evo_addproduct_typeid, + riskId: evo_addproduct_type?.evo_addproduct_typeid, + riskName: evo_addproduct_type?.evo_name, + calcType: evo_addproduct_type?.evo_type_calc_cerebellum, + premiumPerc: evo_addproduct_type?.evo_cost_service_provider_withoutnds, + sum: 0, + premium: 0, + keys: evo_addproduct_type?.evo_addproduct_types?.map((k) => k?.evo_addproduct_typeid), + } as Risk) + ); + + if (!risks) return; + + $tables.fingap.setRisks(risks); + + function getFingapRequestDataFromRisk(risk: Risk): RequestFinGAP { + return { + calcType: risk.calcType, + payments: paymentsValues.map((payment) => ({ + percentPayment: payment, + })), + values: { + plPrice: plPriceRub, + discount: discountRub, + firstPayment: firstPaymentRub, + leasingPeriod, + premiumPerc: risk.premiumPerc || 0, + }, + }; + } + + function makeRequestGetFinGAP(request: RequestFinGAP) { + const queryCalculateFinGAP = ({ signal }: QueryFunctionContext) => + calculateFinGAP(request, signal); + + return queryClient.fetchQuery( + ['calculate', 'fingap', request.calcType], + queryCalculateFinGAP + ); + } + + Promise.all( + risks + .map((risk) => getFingapRequestDataFromRisk(risk)) + .map((data) => makeRequestGetFinGAP(data)) + ).then((results) => { + const newRisks = risks.map((risk, i) => ({ + ...risk, + sum: results.at(i)?.data.sum || 0, + premium: results.at(i)?.data.premium || 0, + })); + + $tables.fingap.setRisks(newRisks); + }); + }, + { + // Important: delay prohibits multiple reaction invocation + equals: comparer.structural, + delay: 100, + } + ); +} diff --git a/process/fingap/reactions/index.js b/process/fingap/reactions/index.js new file mode 100644 index 0000000..cc8d68a --- /dev/null +++ b/process/fingap/reactions/index.js @@ -0,0 +1,2 @@ +export { default as common } from './common'; +export { default as validation } from './validation'; diff --git a/process/fingap/reactions/validation.ts b/process/fingap/reactions/validation.ts new file mode 100644 index 0000000..aa76f91 --- /dev/null +++ b/process/fingap/reactions/validation.ts @@ -0,0 +1,37 @@ +import type { ApolloClient } from '@apollo/client'; +import type { QueryClient } from '@tanstack/react-query'; +import { reaction } from 'mobx'; +import type RootStore from 'stores/root'; + +export default function validationReactions( + store: RootStore, + apolloClient: ApolloClient, + queryClient: QueryClient +) { + const { $tables } = store; + + const errorText = 'Неверно заполнены платежи'; + let removeError: () => void; + + reaction( + () => { + const hasPaymentsErrors = $tables.payments.validation.hasErrors; + const finGAPInsuranceCompany = $tables.insurance.getRowValue('fingap', 'insuranceCompany'); + + return { + hasPaymentsErrors, + finGAPInsuranceCompany, + }; + }, + ({ hasPaymentsErrors, finGAPInsuranceCompany }) => { + if (finGAPInsuranceCompany && hasPaymentsErrors) { + removeError = $tables.fingap.validation.addError(errorText); + } else { + removeError(); + } + }, + { + fireImmediately: true, + } + ); +} diff --git a/process/init/inject-reactions/default.js b/process/init/inject-reactions/default.js index 317c339..40b4245 100644 --- a/process/init/inject-reactions/default.js +++ b/process/init/inject-reactions/default.js @@ -1,12 +1,19 @@ import * as agentsReactions from '../../agents/reactions'; import * as calculateReactions from '../../calculate/reactions'; +import * as fingapReactions from '../../fingap/reactions'; import * as leadOpportunityReactions from '../../lead-opportunity/reactions'; import paymentsReactions from '../../payments/reactions'; +import * as priceReactions from '../../price/reactions'; +import setInitialValuesReactions from '../set-values/reactions'; -export default function injectDefaultReactions(store, apolloClient) { - leadOpportunityReactions.common(store, apolloClient); - leadOpportunityReactions.urls(store, apolloClient); - paymentsReactions(store, apolloClient); - calculateReactions.validation(store, apolloClient); - agentsReactions.common(store, apolloClient); +export default function injectDefaultReactions(store, apolloClient, queryClient) { + leadOpportunityReactions.common(store, apolloClient, queryClient); + leadOpportunityReactions.urls(store, apolloClient, queryClient); + paymentsReactions(store, apolloClient, queryClient); + calculateReactions.validation(store, apolloClient, queryClient); + agentsReactions.common(store, apolloClient, queryClient); + priceReactions.computed(store, apolloClient, queryClient); + fingapReactions.common(store, apolloClient, queryClient); + fingapReactions.validation(store, apolloClient, queryClient); + setInitialValuesReactions(store, apolloClient, queryClient); } diff --git a/process/init/set-values/reactions.ts b/process/init/set-values/reactions.ts new file mode 100644 index 0000000..83d04de --- /dev/null +++ b/process/init/set-values/reactions.ts @@ -0,0 +1,44 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import type { ApolloClient } from '@apollo/client'; +import { gql } from '@apollo/client'; +import type { QueryClient } from '@tanstack/react-query'; +import type { GetTransactionCurrenciesQuery } from 'graphql/crm.types'; +import { when } from 'mobx'; +import type RootStore from 'stores/root'; + +export default function setInitialValuesReactions( + store: RootStore, + apolloClient: ApolloClient, + queryClient: QueryClient +) { + const QUERY_GET_TRANSACTION_CURRENCIES = gql` + query GetTransactionCurrencies { + transactioncurrencies { + isocurrencycode + transactioncurrencyid + } + } + `; + + const { $calculation } = store; + + when( + () => $calculation.$options.getOptions('selectSupplierCurrency').length > 0, + async () => { + const { + data: { transactioncurrencies }, + } = await apolloClient.query({ + query: QUERY_GET_TRANSACTION_CURRENCIES, + }); + + const transactioncurrency_rub = transactioncurrencies?.find( + (x) => x?.isocurrencycode === 'RUB' + ); + + $calculation.setElementValue( + 'selectSupplierCurrency', + transactioncurrency_rub?.transactioncurrencyid + ); + } + ); +} diff --git a/process/payments/reactions.ts b/process/payments/reactions.ts index 2848c71..c950d1f 100644 --- a/process/payments/reactions.ts +++ b/process/payments/reactions.ts @@ -30,7 +30,7 @@ export default function paymentsReactions(store: RootStore, apolloClient: Apollo /** * Проверяем платежи на 0 */ - const errorText = 'Значения не должны быть равны 0'; + const errorText = 'Значения должны быть больше 0'; let removeError: () => void; reaction( diff --git a/process/price/reactions/computed.ts b/process/price/reactions/computed.ts new file mode 100644 index 0000000..d05d088 --- /dev/null +++ b/process/price/reactions/computed.ts @@ -0,0 +1,94 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import type { ApolloClient } from '@apollo/client'; +import { gql } from '@apollo/client'; +import dayjs from 'dayjs'; +import utc from 'dayjs/plugin/utc'; +import type * as CRMTypes from 'graphql/crm.types'; +import { autorun } from 'mobx'; +import type RootStore from 'stores/root'; + +dayjs.extend(utc); + +export default function computedReactions(store: RootStore, apolloClient: ApolloClient) { + const QUERY_GET_EVO_CURRENCY_CHANGES = gql` + query GetCurrencyChanges($currentDate: DateTime) { + evo_currencychanges(statecode: 0, evo_coursedate_param: { eq: $currentDate }) { + evo_currencychange + evo_ref_transactioncurrency + } + } + `; + + const QUERY_GET_CURRENCY_ISOCODE = gql` + query GetCurrencyISOCode($id: Uuid!) { + transactioncurrency(transactioncurrencyid: $id) { + isocurrencycode + } + } + `; + + const { $calculation } = store; + + autorun( + async () => { + const supplierCurrencyId = $calculation.getElementValue('selectSupplierCurrency'); + const leaseObjectPrice = $calculation.getElementValue('tbxLeaseObjectPrice'); + const supplierDiscountRub = $calculation.getElementValue('tbxSupplierDiscountRub'); + + if (!supplierCurrencyId) { + $calculation.$values.setValue('plPriceRub', leaseObjectPrice); + $calculation.$values.setValue('discountRub', supplierDiscountRub); + + return; + } + + const { + data: { transactioncurrency }, + } = await apolloClient.query< + CRMTypes.GetCurrencyIsoCodeQuery, + CRMTypes.GetCurrencyIsoCodeQueryVariables + >({ + query: QUERY_GET_CURRENCY_ISOCODE, + variables: { + id: supplierCurrencyId, + }, + }); + + if (transactioncurrency?.isocurrencycode === 'RUB') { + $calculation.$values.setValue('plPriceRub', leaseObjectPrice); + $calculation.$values.setValue('discountRub', supplierDiscountRub); + + return; + } + + const { + data: { evo_currencychanges }, + } = await apolloClient.query< + CRMTypes.GetCurrencyChangesQuery, + CRMTypes.GetCurrencyChangesQueryVariables + >({ + query: QUERY_GET_EVO_CURRENCY_CHANGES, + variables: { + currentDate: dayjs().utc().format('YYYY-MM-DD'), + }, + }); + + const evo_currencychange = evo_currencychanges?.find( + (x) => x?.evo_ref_transactioncurrency === supplierCurrencyId + ); + + $calculation.$values.setValue( + 'plPriceRub', + leaseObjectPrice * (evo_currencychange?.evo_currencychange || 0) + ); + + $calculation.$values.setValue( + 'discountRub', + supplierDiscountRub * (evo_currencychange?.evo_currencychange || 0) + ); + }, + { + delay: 100, + } + ); +} diff --git a/process/price/reactions/index.js b/process/price/reactions/index.js new file mode 100644 index 0000000..d5e79ce --- /dev/null +++ b/process/price/reactions/index.js @@ -0,0 +1,2 @@ +/* eslint-disable import/prefer-default-export */ +export { default as computed } from './computed'; diff --git a/stores/calculation/values/types.ts b/stores/calculation/values/types.ts index e1af1a1..1bb332a 100644 --- a/stores/calculation/values/types.ts +++ b/stores/calculation/values/types.ts @@ -135,6 +135,8 @@ export type CalculationValues = { registrationDescription: string | null; depreciationGroup: string | null; subsidySum: number; + plPriceRub: number; + discountRub: number; }; export type Values = keyof CalculationValues; diff --git a/stores/tables/fingap/index.ts b/stores/tables/fingap/index.ts index 8910a79..857adc3 100644 --- a/stores/tables/fingap/index.ts +++ b/stores/tables/fingap/index.ts @@ -2,9 +2,11 @@ import type * as FinGAP from 'Components/Calculation/Form/Insurance/FinGAPTable/ import type { IObservableArray } from 'mobx'; import { makeAutoObservable, observable } from 'mobx'; import type RootStore from 'stores/root'; +import Validation from '../validation'; export default class FinGAPTable { root: RootStore; + validation: Validation; risks: IObservableArray; selectedKeys: Set; @@ -13,6 +15,11 @@ export default class FinGAPTable { this.risks = observable([]); makeAutoObservable(this); + this.validation = new Validation({ + err_key: 'ERR_FINGAP_TABLE', + err_title: 'Таблица рисков Safe Finance', + }); + this.root = rootStore; } diff --git a/stores/tables/insurance/index.ts b/stores/tables/insurance/index.ts index 1c7792b..5695445 100644 --- a/stores/tables/insurance/index.ts +++ b/stores/tables/insurance/index.ts @@ -55,7 +55,7 @@ export default class InsuranceTable { return this.options[key]; } - setRowOptions = (key: Insurance.Keys, rowOptions: Insurance.RowOptions) => { + setRowOptions = (key: Insurance.Keys, rowOptions: Partial) => { this.options[key] = { ...this.options[key], ...rowOptions }; }; @@ -63,7 +63,7 @@ export default class InsuranceTable { return this.statuses[key]; } - setRowStatuses = (key: Insurance.Keys, rowStatuses: Insurance.RowStatuses) => { + setRowStatuses = (key: Insurance.Keys, rowStatuses: Partial) => { this.statuses[key] = { ...this.statuses[key], ...rowStatuses }; }; diff --git a/yarn.lock b/yarn.lock index 13f1e2a..ed514fc 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5371,11 +5371,6 @@ graphql@^16.3.0: resolved "https://registry.yarnpkg.com/graphql/-/graphql-16.3.0.tgz#a91e24d10babf9e60c706919bb182b53ccdffc05" integrity sha512-xm+ANmA16BzCT5pLjuXySbQVFwH3oJctUVdy81w1sV0vBU0KgDdBGtxQOUd5zqOBk/JayAFeG8Dlmeq74rjm/A== -graphql@^16.6.0: - version "16.6.0" - resolved "https://registry.yarnpkg.com/graphql/-/graphql-16.6.0.tgz#c2dcffa4649db149f6282af726c8c83f1c7c5fdb" - integrity sha512-KPIBPDlW7NxrbT/eh4qPXz5FiFdL5UbaA0XUNz2Rp3Z3hqBSkbj0GVjwFDztsWVauZUWsbKHgMg++sk8UX0bkw== - has-ansi@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91"