Advertisement
Maikl5700

Untitled

Aug 10th, 2020
1,771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState, useEffect } from 'react'
  2. import { DialogTitle, DialogContent, DialogContentText, TextField, CircularProgress } from '@material-ui/core'
  3. import { userStore, dialog } from 'stores'
  4. import fetch from 'fetch/fetchFactory'
  5. import { Company } from 'stores/Classes';
  6. import { createNofication } from 'dialogs/utils';
  7.  
  8. import { DialogActionsDefault } from 'components';
  9.  
  10.  
  11. export const settings = {
  12.   helperText: ['Введите название'],
  13.   textFieldesLabels: ['Название', 'Имя поля бонусов'],
  14.   getTitle: update => update
  15.     ? "Редактировать компанию "
  16.     : "Новая компания",
  17.   getText: update => update
  18.     ? "Для изменения компании введите название и нажмите сохранить"
  19.     : "Для создания компании заполните поля и нажмите создать"
  20. }
  21.  
  22.  
  23. const CompanyCreateUpdateDialog: React.FC<{ index?: number, update?: boolean }> = ({ index, update }) => {
  24.  
  25.   const [state, setState] = useState({
  26.     companyName: '',
  27.     commissionFieldName: '',
  28.     // error
  29.     companyNameError: false,
  30.     // default
  31.     updated: false,
  32.     submitLoading: false
  33.   })
  34.  
  35.  
  36.   //################ UPDATE BLOCK #######################################################
  37.   let company: Company
  38.   if (update) company = userStore.companies[index!]
  39.   useEffect(() => {
  40.     if (update) {
  41.       fetch({
  42.         getUrl: () => `/company/${company.id}`,
  43.         storeMutation: (res: any) => {
  44.           setState({
  45.             ...state,
  46.             companyName: res.name,
  47.             commissionFieldName: res.commission.name || '',
  48.             updated: true
  49.           })
  50.         }
  51.       })
  52.     }
  53.   }, [])
  54.   //#####################################################################################
  55.  
  56.   const allowSubmit = () => {
  57.     if (!state.companyName.length) {
  58.       setState({ ...state, companyNameError: true })
  59.       return false
  60.     }
  61.     return true
  62.   }
  63.  
  64.   const handleSave = () => {
  65.     if (allowSubmit()) {
  66.       setState({ ...state, submitLoading: true })
  67.       fetch({
  68.         getUrl: () => update ? `/company/${company.id}` : '/company',
  69.         getParams: () => ({
  70.           name: state.companyName,
  71.           commissionFieldName: state.commissionFieldName
  72.         }),
  73.         storeMutation: async () => {
  74.           await userStore.getUserCompanies()
  75.           userStore.setState({ loadedRowsMap: [] })
  76.           dialog.close()
  77.           createNofication(
  78.             update
  79.               ? `Компания ${company.name} успешно изменена`
  80.               : `Компания ${state.companyName} успешно создана`,
  81.             'success')
  82.         },
  83.         method: update ? 'put' : 'post',
  84.         onError: err => {
  85.           console.error(err)
  86.           dialog.close()
  87.           createNofication(`У вас нет прав на изменение компании ${update ? company.name : state.companyName}.`, 'error')
  88.         }
  89.       })
  90.     }
  91.   }
  92.  
  93.   const { getText, getTitle, textFieldesLabels, helperText } = settings
  94.  
  95.   return (
  96.     <>
  97.       {(update && !state.updated) && <div className="dialog_loading"><CircularProgress /></div>}
  98.      
  99.       <DialogTitle id="form-dialog-title">
  100.         {getTitle(update)}
  101.         {update && <span className="dialog_header_name">{state.companyName}</span>}
  102.       </DialogTitle>
  103.       <DialogContent>
  104.         <DialogContentText>
  105.           {getText(update)}
  106.         </DialogContentText>
  107.         <TextField
  108.          onChange={(e) => { setState({ ...state, companyName: e.target.value, companyNameError: false }) }}
  109.           error={state.companyNameError}
  110.           helperText={state.companyNameError && helperText}
  111.           autoFocus
  112.           margin="dense"
  113.           label={textFieldesLabels[0]}
  114.           value={state.companyName}
  115.           fullWidth
  116.         />
  117.         <TextField
  118.          onChange={(e) => { setState({ ...state, commissionFieldName: e.target.value }) }}
  119.           margin="dense"
  120.           label={textFieldesLabels[1]}
  121.           value={state.commissionFieldName}
  122.           fullWidth
  123.         />
  124.       </DialogContent>
  125.       <DialogActionsDefault
  126.         onClick={handleSave}
  127.         loading={state.submitLoading}
  128.         buttonText={update ? "Сохранить" : "Создать"}
  129.       />
  130.     </>
  131.   )
  132. }
  133.  
  134.  
  135. export default CompanyCreateUpdateDialog
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement