All files / app/src/features/measure/ui/measure-save-modal measure-save-modal.tsx

1.14% Statements 2/175
100% Branches 0/0
0% Functions 0/1
1.14% Lines 2/175

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 2201x                                                               1x                                                                                                                                                                                                                                                                                                                                                                                      
import { FC, useState } from 'react'
import { Button, Input, Modal } from '@tmk/ui-kit'
import cn from 'classnames'
import { Form, notify, SelectWithQuery, useTranslate } from '@/shared/lib'
import { useAtomValue } from 'jotai'
import {
  getMeasureFilters,
  MeasureCollectionResponse,
  MeasureFilter,
  measureFiltersAtom,
  measureFormValuesAtom,
  measureSaveValidationSchema,
  uploadMeasureFile,
  useCreateMeasure,
} from '@/features/measure'
import { Nullable } from '@/shared/@types'
import { Controller, FieldValues } from 'react-hook-form'
import { useDepositsCollection } from '@/entities/deposit'
import { useWellsCollection } from '@/entities/well'
import { useBushesById } from '@/entities/bush'
import { ulid } from 'ulid'
import { getIdFromIRI, removeEmptyFilters, trimToRussianError } from '@/shared/helpers'
import { LockPriceEnum } from '@/entities/pipe'
import router from 'next/router'
 
export interface MeasureSaveModalProps {
  isOpen: boolean
  onClose: () => void
  calculatedMeasure?: Nullable<MeasureCollectionResponse>
  changeListenMode: (mode: boolean) => void
}
 
export const MeasureSaveModal: FC<MeasureSaveModalProps> = ({
  isOpen,
  onClose,
  calculatedMeasure,
  changeListenMode,
}) => {
  const { t } = useTranslate(['accounting-object', 'common'])
  const [isLoading, setIsLoading] = useState(false)
 
  const { mutateAsync } = useCreateMeasure({
    onSuccess: () => {
      changeListenMode(false)
      notify(t('Measure saved successfully'))
      onClose()
      setTimeout(() => {
        router.push('/profile/measures')
      }, 0)
    },
    onError: error => {
      setIsLoading(false)
      const errorMessage = trimToRussianError(error?.response?.data)
      notify(errorMessage ? errorMessage : t('Measure saving error'), {
        status: 'error',
      })
    },
  })
  const filterValue = useAtomValue(measureFiltersAtom)
 
  const formValues = useAtomValue(measureFormValuesAtom)
  const sortament = calculatedMeasure?.['hydra:member']?.[0]
 
  const submitHandler = async (data: FieldValues) => {
    setIsLoading(true)
    const file = await uploadMeasureFile({
      id: calculatedMeasure?.['hydra:member']?.map(pipe => getIdFromIRI(pipe['@id'])) || [],
    })
    const isTonOverride = formValues.priceTypeOverride === LockPriceEnum.TON
    await mutateAsync({
      data: {
        id: ulid(),
        date: new Date().toISOString(),
        pipes: calculatedMeasure?.['hydra:member']?.map(pipe => pipe['@id']) || [],
        actualPrice: calculatedMeasure?.actualPrice,
        actualPriceCurrency: calculatedMeasure?.actualPriceCurrency,
        calculatedPrice: calculatedMeasure?.calculatedPrice,
        calculatedPriceCurrency: calculatedMeasure?.calculatedPriceCurrency,
        actualLength: parseFloat(calculatedMeasure?.actualLength?.toString() as string),
        actualLengthWithMakeUpLoss: parseFloat(calculatedMeasure?.actualLengthWithMakeUpLoss?.toString() as string),
        actualWeight: parseFloat(calculatedMeasure?.actualWeight?.toString() as string),
        connection: formValues.connection,
        diameter: formValues.diameter,
        side: formValues.side,
        strengthGroup: formValues.strengthGroup,
        isPriceIndicated: calculatedMeasure?.isPriceIndicated,
        isSameMakeUpLoss: calculatedMeasure?.isSameMakeUpLoss,
        ...data,
        overrideCurrency: formValues.overrideCurrency,
        measureType: formValues.measureType,
        file: file.data?.['@id'],
        filters: removeEmptyFilters(getMeasureFilters(filterValue)) as Record<string, MeasureFilter>,
        requiredLength: parseFloat(formValues?.requiredLength),
        requiredItemsCount: parseFloat(formValues?.requiredItemsCount),
        ...(formValues?.overrideMakeUpLengthLoss && {
          overrideMakeUpLengthLoss: parseFloat(formValues?.overrideMakeUpLengthLoss),
        }),
        ...(formValues?.overrideMakeUpLengthLossNotation && {
          overrideMakeUpLengthLossNotation: formValues?.overrideMakeUpLengthLossNotation,
        }),
        ...(isTonOverride && formValues.priceOverride && { overridePriceTon: parseFloat(formValues?.priceOverride) }),
        ...(!isTonOverride &&
          formValues.priceOverride && { overridePriceLength: parseFloat(formValues?.priceOverride) }),
      },
    })
    setIsLoading(false)
  }
 
  return (
    <Modal
      withCloseButton
      maskClosable
      type='sidebar'
      isOpen={isOpen}
      onClose={onClose}
      overlayClassName='backdrop-blur-none bg-opacity-30'
    >
      <div className={cn('w-fit flex flex-col  gap-y-2.5 min-w-[400px] max-w-[500px]')}>
        <div className='flex flex-col gap-y-2.5 text-center'>
          <h1>{t('Save measure')}</h1>
          <span className='text-main-regular'>
            {t('If you are sure that you want to save the results of the measure, fill in the characteristics')}
          </span>
        </div>
        <Form
          // @ts-expect-error
          validationSchema={measureSaveValidationSchema(t)}
          onSubmit={async data => {
            await submitHandler(data)
          }}
        >
          {({ control, watch }) => (
            <div className='flex flex-col gap-y-2.5 w-full'>
              <div className='flex flex-col bg-gray-secondary p-5 gap-y-2.5 w-full rounded-base'>
                <h2>{t(formValues?.accountingObjectType)}</h2>
                <h2 className='text-main'>
                  ⌀ {sortament?.diameter?.value} - {sortament?.side?.value} - {sortament?.strengthGroup?.name} -{' '}
                  {sortament?.connection?.name}
                </h2>
                <div className='flex flex-col gap-y-2.5'>
                  <Controller
                    name='name'
                    control={control}
                    render={({ field, fieldState: { error } }) => (
                      <Input label={t('Measure name') + ' *'} error={error} {...field} />
                    )}
                  />
                  <Controller
                    name='deposit'
                    control={control}
                    render={({ field, fieldState: { error } }) => (
                      <SelectWithQuery
                        withOptionAddition
                        source='deposits'
                        label={t('Deposit')}
                        useQuery={useDepositsCollection}
                        error={error}
                        {...field}
                      />
                    )}
                  />
                  <Controller
                    name='bush'
                    control={control}
                    render={({ field, fieldState: { error } }) => (
                      <SelectWithQuery
                        label={t('bush')}
                        useQuery={useBushesById}
                        labelKey='number'
                        dependentEntityType='id'
                        dependentEntities={{
                          deposit: watch('deposit'),
                        }}
                        withOptionAddition
                        source='bushes'
                        error={error}
                        {...field}
                      />
                    )}
                  />
                  <Controller
                    name='well'
                    control={control}
                    render={({ field, fieldState: { error } }) => (
                      <SelectWithQuery
                        label={t('Well number')}
                        useQuery={useWellsCollection}
                        labelKey='number'
                        dependentEntityType='filter'
                        dependentEntities={{
                          ...(watch('deposit') && { deposit: watch('deposit') }),
                          ...(watch('bush')
                            ? { bush: watch('bush') || undefined }
                            : watch('deposit') && { 'exists[bush]': false }),
                        }}
                        withOptionAddition
                        source='wells'
                        error={error}
                        {...field}
                      />
                    )}
                  />
                </div>
              </div>
              <div className='flex items-center gap-x-2.5 justify-center mt-2.5'>
                <Button variant='outlined' color='secondary' disabled={isLoading} onClick={() => onClose()}>
                  <h2>{t('common:Cancel')}</h2>
                </Button>
                <Button type='submit' loading={isLoading}>
                  <h2>{t('common:Execute')}</h2>
                </Button>
              </div>
            </div>
          )}
        </Form>
      </div>
    </Modal>
  )
}