CF2-33: Фикс загрузки файлов и меню категорий

This commit is contained in:
KharchenkoVV 2021-07-26 15:21:35 +05:00
parent 4355930277
commit 5f8738d1bf
11 changed files with 124 additions and 72 deletions

View File

@ -9,27 +9,9 @@ import LoaderPortal from './LoaderPortal'
import locale from "antd/lib/locale/ru_RU" import locale from "antd/lib/locale/ru_RU"
import moment from 'moment' import moment from 'moment'
const pageSize = 26 const pageSize = 12
const {RangePicker} = DatePicker; const {RangePicker} = DatePicker;
const columns = [
{
title: 'Документ',
key: 'document',
dataIndex: 'name',
},
{
title: 'Дата загрузки',
key: 'uploadDate',
dataIndex: 'uploadDate',
render: (item) => moment.utc(item).local().format('DD MMM YYYY, HH:mm:ss')
},
{
title: 'Ф.И.О.',
key: 'userName',
dataIndex: 'userName',
}
];
export default function Documents({selectedFileCategory}) { export default function Documents({selectedFileCategory}) {
let {id} = useParams() let {id} = useParams()
@ -39,10 +21,71 @@ export default function Documents({selectedFileCategory}) {
const [pagination, setPagination] = useState(null) const [pagination, setPagination] = useState(null)
const [files, setFiles] = useState([]) const [files, setFiles] = useState([])
const [selectedFiles, setSelectedFiles] = useState([]) const [selectedFiles, setSelectedFiles] = useState([])
const [isTableUpdating, setTableUpdating] = useState(false)
const [loader, setLoader] = useState(false) const [loader, setLoader] = useState(false)
const [form] = Form.useForm();
const handleFileNameCLick = async (event, row) => {
const element = event.target
if(!element.href.length) {
try {
setLoader(true)
await fetch(`/api/files/${id}/${row.id}`, {
headers: {
Authorization: 'Bearer ' + localStorage['token']
}
})
.then(async (response) => {
const blob = await response.blob();
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function (e) {
element.href = e.target.result
element.click()
};
setLoader(false)
});
} catch (error) {
notify(`Не удалось скачать файл ${row}`, 'error')
console.log(error)
}
}
}
const columns = [
{
title: 'Документ',
key: 'document',
dataIndex: 'name',
render: (name, row) =>
<a onClick={ev => handleFileNameCLick(ev, row)} download={name}>{name}</a>
},
{
title: 'Дата загрузки',
key: 'uploadDate',
dataIndex: 'uploadDate',
render: (item) => moment.utc(item).local().format('DD MMM YYYY, HH:mm:ss')
},
{
title: 'Ф.И.О.',
key: 'userName',
dataIndex: 'userName',
}
];
const submitFileFormProps = { const submitFileFormProps = {
progress: {
strokeColor: {
'0%': '#108ee9',
'100%': '#87d068',
},
strokeWidth: 3,
format: percent => `${parseFloat(percent.toFixed(2))}%`,
},
onChange({ file, fileList }) { onChange({ file, fileList }) {
if (file.status !== 'uploading') { if (file.status !== 'uploading') {
setSelectedFiles(fileList) setSelectedFiles(fileList)
@ -54,11 +97,12 @@ export default function Documents({selectedFileCategory}) {
setRange(range) setRange(range)
} }
const onFinish = (values) => { const onFinish = (values, form) => {
var fileList = values.fileInput.fileList var fileList = values.fileInput.fileList
if (fileList.length > 0) if (fileList.length > 0)
{ {
setLoader(true)
const formData = new FormData(); const formData = new FormData();
fileList.forEach(val => { fileList.forEach(val => {
@ -73,7 +117,9 @@ export default function Documents({selectedFileCategory}) {
body: formData body: formData
}) })
.then(async (response) => { .then(async (response) => {
// refresh component to upload new files в зависимоть useEffect какую-то переменную, чтоб дергался снова запрос на всю инфу о файлах setLoader(false)
form.resetFields()
setTableUpdating(true)
}); });
} }
} }
@ -93,7 +139,7 @@ export default function Documents({selectedFileCategory}) {
begin = range[0].toISOString() begin = range[0].toISOString()
end = range[1].toISOString() end = range[1].toISOString()
} }
console.log(id)
await FileService.getFilesInfo( await FileService.getFilesInfo(
`${id}`, `${id}`,
(page - 1) * pageSize, (page - 1) * pageSize,
@ -114,37 +160,40 @@ export default function Documents({selectedFileCategory}) {
total: paginatedFiles?.count, total: paginatedFiles?.count,
current: Math.floor(paginatedFiles?.skip / pageSize), current: Math.floor(paginatedFiles?.skip / pageSize),
}) })
setTableUpdating(false)
setLoader(false)
} }
) )
} catch (ex) { } catch (ex) {
notify(`Не удалось загрузить файлы по скважине "${id}"`, 'error') notify(`Не удалось загрузить файлы по скважине "${id}"`, 'error')
console.log(ex) console.log(ex)
} }
setLoader(false)
} }
GetDocuments() GetDocuments()
}, [id, selectedFileCategory, range]) }, [id, range, selectedFileCategory, isTableUpdating])
return ( return (
<div> <div>
<MenuDocuments/> <MenuDocuments/>
<div className='filter-group'> <div className='filter-group'>
<h3 className='filter-group-heading'>Фильтр документов:</h3> <h3 className='filter-group-heading'>Фильтр документов:</h3>
<ConfigProvider locale={locale}> <ConfigProvider locale={locale}>
<RangePicker <RangePicker
showTime showTime
onChange={onChangeRange} onChange={onChangeRange}
/> />
</ConfigProvider> </ConfigProvider>
</div> </div>
<LoaderPortal show={loader}></LoaderPortal> <LoaderPortal show={loader}></LoaderPortal>
<div>&nbsp;</div> <div>&nbsp;</div>
<Form <Form
name="DocumentsUploadForm" form={form}
onFinish={onFinish} name="DocumentsUploadForm"
onFinishFailed={onFinishFailed} onFinish={(values) => onFinish(values, form)}
> onFinishFailed={onFinishFailed}
<div style={{display: 'flex'}}> style={{width: '300px'}}
>
<Form.Item <Form.Item
name="fileInput" name="fileInput"
rules={[{ required: true, message: 'Выберите файл' }]} rules={[{ required: true, message: 'Выберите файл' }]}
@ -158,13 +207,11 @@ export default function Documents({selectedFileCategory}) {
type="primary" type="primary"
htmlType="submit" htmlType="submit"
disabled={selectedFiles.length === 0} disabled={selectedFiles.length === 0}
style={{marginLeft: '10px'}}
> >
Отправить Отправить
</Button> </Button>
</Form.Item> </Form.Item>
</div> </Form>
</Form>
<div>&nbsp;</div> <div>&nbsp;</div>
<Table <Table
columns={columns} columns={columns}

View File

@ -1,15 +1,25 @@
import {Menu} from "antd"; import {Menu} from "antd";
import {FolderOutlined} from "@ant-design/icons"; import {FolderOutlined} from "@ant-design/icons";
import {Link} from "react-router-dom"; import {Link} from "react-router-dom";
import {useState} from "react"
export default function MenuDocuments() { export default function MenuDocuments() {
const [selectedItem, setSelectedItem] = useState(1)
const handleClick = e => {
setSelectedItem({ current: e.key });
};
return( return(
<> <>
<Menu <Menu
mode="horizontal" mode="horizontal"
selectable={true} selectable={true}
className="well_menu" className="well_menu"
onClick={handleClick}
selectedKeys={[selectedItem]}
> >
<Menu.Item key="1" icon={<FolderOutlined/>}> <Menu.Item key="1" icon={<FolderOutlined/>}>
<Link to='fluidService'>Растворный сервис</Link> <Link to='fluidService'>Растворный сервис</Link>

View File

@ -1,8 +1,8 @@
import Documents from "../components/Documents" import Documents from "../components/Documents"
export default function Cementing(id) { export default function Cementing({selectedFileCategory}) {
return( return(
<Documents selectedFileCategory={id} /> <Documents selectedFileCategory={selectedFileCategory} />
) )
} }

View File

@ -1,8 +1,8 @@
import Documents from "../components/Documents" import Documents from "../components/Documents"
export default function DocumentsForWell(id) { export default function DocumentsForWell({selectedFileCategory}) {
return( return(
<Documents selectedFileCategory={id} /> <Documents selectedFileCategory={selectedFileCategory} />
) )
} }

View File

@ -1,8 +1,8 @@
import Documents from "../components/Documents" import Documents from "../components/Documents"
export default function FluidService(id) { export default function FluidService({selectedFileCategory}) {
return( return(
<Documents selectedFileCategory={id} /> <Documents selectedFileCategory={selectedFileCategory} />
) )
} }

View File

@ -1,8 +1,8 @@
import Documents from "../components/Documents" import Documents from "../components/Documents"
export default function Gti(id) { export default function Gti({selectedFileCategory}) {
return( return(
<Documents selectedFileCategory={id} /> <Documents selectedFileCategory={selectedFileCategory} />
) )
} }

View File

@ -1,8 +1,8 @@
import Documents from "../components/Documents" import Documents from "../components/Documents"
export default function Master(id) { export default function Master({selectedFileCategory}) {
return( return(
<Documents selectedFileCategory={id} /> <Documents selectedFileCategory={selectedFileCategory} />
) )
} }

View File

@ -1,8 +1,8 @@
import Documents from "../components/Documents" import Documents from "../components/Documents"
export default function Nnb(id) { export default function Nnb({selectedFileCategory}) {
return( return(
<Documents selectedFileCategory={id} /> <Documents selectedFileCategory={selectedFileCategory} />
) )
} }

View File

@ -1,8 +1,8 @@
import Documents from "../components/Documents" import Documents from "../components/Documents"
export default function Supervisor(id) { export default function Supervisor({selectedFileCategory}) {
return( return(
<Documents selectedFileCategory={id} /> <Documents selectedFileCategory={selectedFileCategory} />
) )
} }

View File

@ -113,22 +113,22 @@ export default function Well() {
<FluidService selectedFileCategory={1}/> <FluidService selectedFileCategory={1}/>
</Route> </Route>
<Route path="/well/:id/cementing"> <Route path="/well/:id/cementing">
<Cementing id={2}/> <Cementing selectedFileCategory={2}/>
</Route> </Route>
<Route path="/well/:id/nnb"> <Route path="/well/:id/nnb">
<Nnb id={3}/> <Nnb selectedFileCategory={3}/>
</Route> </Route>
<Route path="/well/:id/gti"> <Route path="/well/:id/gti">
<Gti id={4}/> <Gti selectedFileCategory={4}/>
</Route> </Route>
<Route path="/well/:id/documentsForWell"> <Route path="/well/:id/documentsForWell">
<DocumentForWell id={5}/> <DocumentForWell selectedFileCategory={5}/>
</Route> </Route>
<Route path="/well/:id/supervisor"> <Route path="/well/:id/supervisor">
<Supervisor id={6}/> <Supervisor selectedFileCategory={6}/>
</Route> </Route>
<Route path="/well/:id/master"> <Route path="/well/:id/master">
<Master id={7}/> <Master selectedFileCategory={7}/>
</Route> </Route>
<Route path="/well/:id/lastData"> <Route path="/well/:id/lastData">
<LastData/> <LastData/>

View File

@ -69,22 +69,17 @@ end?: string,
/** /**
* Возвращает файл с диска на сервере * Возвращает файл с диска на сервере
* @param wellId id скважины * @param wellId id скважины
* @param fileName
* @param fileId id запрашиваемого файла * @param fileId id запрашиваемого файла
* @returns string Success * @returns string Success
* @throws ApiError * @throws ApiError
*/ */
public static async getFile( public static async getFile(
wellId: number, wellId: number,
fileName: string, fileId: number,
fileId?: number,
): Promise<string> { ): Promise<string> {
const result = await __request({ const result = await __request({
method: 'GET', method: 'GET',
path: `/api/files/${wellId}/${fileName}`, path: `/api/files/${wellId}/${fileId}`,
query: {
'fileId': fileId,
},
}); });
return result.body; return result.body;
} }