All files / app/src/features/import/ui/import-mutation-form import-mutation-form.tsx

35.26% Statements 85/241
71.42% Branches 5/7
11.76% Functions 2/17
35.26% Lines 85/241

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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 3081x                                                                                     1x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 3x     3x         3x 3x 3x 3x 3x 3x 3x 3x             3x 3x 3x 3x             3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x   3x 1x 1x 1x 3x   3x 3x 3x 3x   3x 3x 3x 3x   3x   3x 1x 1x   1x 1x           1x       1x             1x     1x 1x   1x 1x                               1x         1x   1x                                                                                                               1x                                             1x   1x 1x 1x 1x                                                                         1x 1x 1x 1x 1x 1x 1x 1x   1x   1x 3x 3x   3x  
import { FC, useState } from 'react'
import { Form, FormMode, notify, useTranslate } from '@/shared/lib'
import { Button } from '@tmk/ui-kit'
import { useCancelModal, useWillUnmount } from '@/shared/hooks'
import { useRouter } from 'next/router'
import {
  AccountingObjectImport,
  CharacteristicAccountingObjectImport,
  ContractImportBlock,
  DocumentsBlock,
  getDefaultImportFormValues,
  IMPORT_PAGE,
  importCreateValidationSchema,
  LinksBlockImport,
  MarkingBlock,
  UploadImportFile,
} from '@/features/import'
import { EmptyData } from '@/shared/ui'
import OutlinedEmptyIcon from '@/shared/assets/icons/common/outlined-empty.svg'
import {
  importErrorsAtom,
  ImportSingle,
  importUploadedFile,
  isDirtyImportSortaments,
  isNewFileUploadedAtom,
  isValidatedImportAtom,
  useCreateImport,
  useFinishImport,
  useMutateImport,
  useMutateXLSX,
  useSingleImport,
} from '@/entities/accounting-object-import'
import { useAtom, useAtomValue } from 'jotai'
import { useUpdateAtom } from 'jotai/utils'
import { normalizeObjectForIri } from '@/shared/helpers'
import { useCreateImportDocument } from '@/entities/documents'
import { FileModel } from '@/shared/@types'
import { ulid } from 'ulid'
import { useUsersCollection } from '@/entities/user'
 
interface ImportMutationFormProps {
  mode: FormMode
}
export const ImportMutationForm: FC<ImportMutationFormProps> = ({ mode }) => {
  const { t } = useTranslate(['accounting-object', 'common'])
  const router = useRouter()
  const [isCreateMode, setIsCreateMode] = useState(mode === FormMode.Create)
  const setImportsError = useUpdateAtom(importErrorsAtom)
  const setIsValidatedImport = useUpdateAtom(isValidatedImportAtom)
  const [isNewFile, setIsFileNew] = useAtom(isNewFileUploadedAtom)
  const [uploadedFile, setUploadedFile] = useAtom(importUploadedFile)
  const [isDirtySortaments, setIsDirtySortaments] = useAtom(isDirtyImportSortaments)
  const [importId, setImportId] = useState<string>((router.query.id as string) || '')
 
  const { mutate: finishImport, isLoading: isLoadingFinish } = useFinishImport({
    onSuccess: () => {
      router.push(IMPORT_PAGE)
    },
    onError: () => {
      notify(t('Failed to import'), {
        status: 'error',
      })
    },
  })
  const { data: importCount, refetch } = useSingleImport(importId, {
    key: [importId, 'import-count'],
    enabled: !!importId,
  })
  const { data: userCollection } = useUsersCollection()
  const { mutateAsync: mutateAsyncImport, isLoading: isLoadingMutate } = useMutateImport({
    onSuccess: data => {
      if (data.violation) {
        setImportsError(data.violation)
      } else {
        setImportsError([])
      }
    },
  })
  const { data } = useSingleImport(importId, {
    enabled: !!importId && !isCreateMode,
    onSuccess: data => {
      if (data?.violation) setImportsError(data?.violation)
      if (data?.file) {
        setUploadedFile(data.file)
      }
      setIsValidatedImport(true)
    },
    key: [importId, 'edit-import'],
  })
  const importsErrors = useAtomValue(importErrorsAtom)
 
  const { CancelModal, openModal } = useCancelModal({
    modalData: {
      title: t('common:Undo_Changes'),
      description: t('common:The_actions_performed_and_the_data_filled_in_cannot_be_restored'),
      acceptAction: t('common:Accept'),
      declineAction: t('common:Back'),
    },
  })
 
  useWillUnmount(() => {
    setUploadedFile(null)
    setIsValidatedImport(false)
    setImportsError([])
  })
 
  return (
    <>
      <CancelModal />
      <Form<ImportSingle>
        // @ts-expect-error
        formParams={{
          ...(isCreateMode && { defaultValues: getDefaultImportFormValues() }),
          values: data,
        }}
        // @ts-expect-error
        validationSchema={importCreateValidationSchema(t)}
      >
        {({ watch, formState, trigger, getValues }) => {
          const isObjectTypeSelected = watch('accountingObjectType')
          const { isDirty } = formState
          // eslint-disable-next-line
          const { mutate, mutateAsync, isLoading } = useMutateXLSX({
            onError: error => {
              if (error?.response?.data?.violations) {
                setImportsError(error?.response?.data?.violations)
              }
              refetch()
            },
            onSuccess: async () => {
              setIsDirtySortaments(false)
              refetch()
            },
            onSettled: () => {
              setIsValidatedImport(true)
              setIsFileNew(false)
              if (isCreateMode) {
                setIsCreateMode(false)
              }
            },
          })
          // TODO: нужно вынести это в компоненту
          // eslint-disable-next-line
          const { mutate: createImportDocument } = useCreateImportDocument()
          const documents = watch('documents') as FileModel[]
          // eslint-disable-next-line
          const { mutate: createImport, isLoading: isLoadingImport } = useCreateImport({
            onSuccess: async data => {
              documents?.forEach(file => {
                createImportDocument({
                  accountingObjectImport: `/accounting_object_imports/${data.id}`,
                  file: `/files/${file.id}`,
                  id: ulid(),
                })
              })
              setImportId(data?.id)
              await mutateAsync({
                id: data.id,
                data: {
                  file: `/files/${uploadedFile?.id}`,
                },
              })
            },
            onError: () => {
              notify(t('Failed to create import'), {
                status: 'error',
              })
            },
          })
 
          const saveImport = async (formData: ImportSingle) => {
            const isValid = await trigger()
 
            if (!userCollection?.['hydra:member']?.[0]?.['@id']) {
              notify(t('Failed to import user is not found'), { status: 'error' })
              return
            }
 
            if (isValid) {
              if (!data) {
                createImport({
                  ...formData,
                  ...{
                    makeUpLengthLoss: +((formData as ImportSingle)?.makeUpLengthLoss || 0),
                    muftOuterDiameter: formData?.muftOuterDiameter
                      ? +((formData as ImportSingle)?.muftOuterDiameter as number)
                      : null,
                  },
                  // TODO:  Пока не будет добавлена авторизация
                  initiator: userCollection
                    ? userCollection?.['hydra:member']?.[0]?.['@id']
                    : '/users/018D59CC-BE61-8E80-0B31-18DAE9B799E8',
                })
              } else {
                if (!uploadedFile) {
                  notify(t('common:File_must_be_uploaded'), { status: 'error' })
                  return
                }
                if (!isNewFile || isDirtySortaments) {
                  await mutateAsyncImport({
                    id: data?.id,
                    data: {
                      ...normalizeObjectForIri(formData),
                      makeUpLengthLoss: parseFloat(formData.makeUpLengthLoss ? `${formData.makeUpLengthLoss}` : ''),
                      muftOuterDiameter: formData?.muftOuterDiameter
                        ? +((formData as ImportSingle)?.muftOuterDiameter as number)
                        : null,
                    } as ImportSingle,
                  })
                }
                if (isNewFile || isDirtySortaments) {
                  mutate({
                    id: data.id,
                    data: {
                      file: `/files/${uploadedFile?.id}`,
                    },
                  })
                }
              }
            } else {
              notify(t('common:Fill_required_fields'), {
                status: 'error',
              })
            }
          }
 
          const completeImport = async (formData: ImportSingle) => {
            const isValid = await trigger()
            if (isValid) {
              const importData = await mutateAsyncImport({
                id: importId,
                data: {
                  ...normalizeObjectForIri(formData),
                  makeUpLengthLoss: parseFloat(formData.makeUpLengthLoss ? `${formData.makeUpLengthLoss}` : ''),
                } as ImportSingle,
              })
              if (importData.violation) {
                setImportsError(importData.violation)
              } else {
                finishImport({
                  id: importId,
                })
              }
            } else {
              notify(t('common:Fill_required_fields'), {
                status: 'error',
              })
            }
          }
          const isValidateLoading = isLoadingImport || isLoadingMutate || isLoading
 
          return (
            <div className='flex flex-col gap-y-2.5'>
              <AccountingObjectImport />
              {isObjectTypeSelected ? (
                <>
                  <ContractImportBlock />
                  <CharacteristicAccountingObjectImport />
                  <MarkingBlock />
                  <UploadImportFile
                    saveImport={() => saveImport(getValues())}
                    isValidateLoading={isValidateLoading}
                    importData={importCount}
                  />
                  <DocumentsBlock importId={importId} />
                  <LinksBlockImport />
                  <div className='flex items-center justify-end gap-x-2.5 px-5 py-4'>
                    <Button
                      variant='outlined'
                      color='secondary'
                      onClick={() => (isDirty ? openModal(() => router.push(IMPORT_PAGE)) : router.push(IMPORT_PAGE))}
                    >
                      <h2>{t('common:Cancel')}</h2>
                    </Button>
                    <Button
                      disabled={!uploadedFile}
                      onClick={() => saveImport(getValues())}
                      loading={isValidateLoading}
                    >
                      <h2>{t('common:Save')}</h2>
                    </Button>
                    <Button
                      onClick={() => completeImport(getValues())}
                      disabled={!!importsErrors?.length || isNewFile || !uploadedFile || isCreateMode}
                      loading={isLoadingMutate || isLoadingFinish}
                    >
                      <h2>{t('common:Importing')}</h2>
                    </Button>
                  </div>
                </>
              ) : (
                <EmptyData
                  className='max-w-[600px] mt-48 text-center'
                  icon={<OutlinedEmptyIcon className='fill-gray stroke-gray' />}
                  title={t('Select the accounting object')}
                  subTitle={t(
                    'Select an accounting object from the existing ones to start filling in the characteristics of the uploaded objects or create a new one using the Other button'
                  )}
                />
              )}
            </div>
          )
        }}
      </Form>
    </>
  )
}