asb_cloud_front/src/components/factory.ts
2021-08-18 10:35:05 +05:00

143 lines
4.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Dispatch, SetStateAction } from "react"
import notify from "./notify"
export const RegExpIsFloat = /^[-+]?\d+\.?\d?$/
/*
other - объект с дополнительными свойствами колонки
поддерживаются все базовые свойства из описания https://ant.design/components/table/#Column
плю дополнительные для колонок EditableTable:
editable - редактируемая колонка, bool
input - react компонента редактора (<Input/>, <InputNumber/>, <DatePicker/>...)
isRequired - значение может быть пустым,
formItemClass - css класс для <FormItem/>, если требуется
formItemRules - массив правил валидации значений https://ant.design/components/form/#Rule,
initialValue - дефолтное значение при добавлении новой строки
*/
export const makeColumn = (title:string, key:string, other?:any) => ({
title: title,
key: key,
dataIndex: key,
...other,
})
export const makeColumnsPlanFact = (title:string, key:string|string[], columsOther?:any|any[], gruopOther?:any) =>
{
let keyPlanLocal = key
let keyFactLocal = key
if(key instanceof Array){
keyPlanLocal = key[0]
keyFactLocal = key[1]
}else{
keyPlanLocal = key + 'Plan'
keyFactLocal = key + 'Fact'
}
let columsOtherLoacl :any[2]
if(columsOther instanceof Array)
columsOtherLoacl = [columsOther[0], columsOther[1]]
else
columsOtherLoacl = [columsOther, columsOther]
return {
title: title,
...gruopOther,
children: [
makeColumn('план', keyPlanLocal, columsOtherLoacl[0]),
makeColumn('факт', keyFactLocal, columsOtherLoacl[1]),
]
}
}
type PaginationContainer = {
skip?: number;
take?: number;
count?: number;
items?: any[] | null;
}
type asyncFunction = (...args:any) => Promise<any|void>;
export const makePaginationObject = (paginationContainer:PaginationContainer, ...other:any) => {
let page = 1 + Math.floor((paginationContainer.skip??0) /(paginationContainer.take??1));
return {
...other,
pageSize: paginationContainer.take,
total: paginationContainer.count ?? paginationContainer.items?.length ?? 0,
current: page,
}
}
export const invokeWebApiWrapper = async (func: Function, setShowLoader: Dispatch<SetStateAction<boolean>>, errorNotifyText: string) => {
if(setShowLoader)
setShowLoader(true)
try{
func()
} catch (ex) {
if(process.env.NODE_ENV === 'development')
console.log(ex)
if(errorNotifyText)
notify(errorNotifyText, 'error')
} finally{
if(setShowLoader)
setShowLoader(false)
}
}
export const invokeWebApiWrapperAsync = async (funcAsync: asyncFunction, setShowLoader: Dispatch<SetStateAction<boolean>>, errorNotifyText: string) => {
if(setShowLoader)
setShowLoader(true)
try{
await funcAsync()
} catch (ex) {
if(process.env.NODE_ENV === 'development')
console.log(ex)
if(errorNotifyText)
notify(errorNotifyText, 'error')
} finally{
if(setShowLoader)
setShowLoader(false)
}
}
export const download = async (url:string, fileName?:string) => {
const response = await fetch(url, {
headers: {
Authorization: 'Bearer ' + localStorage['token']
},
method: 'Get'
})
const requestFileName = decodeURI(fileName
??response.headers
.get('content-disposition')
?.split(';')
.splice(-1)[0]
.split("'")
.splice(-1)[0]
?? url.replace('\\','/')
.split('/')
.splice(-1)[0]
?? 'file')
const blob = await response.blob()
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function (e) {
let a = document.createElement('a');
a.href = (e.target?.result?.toString() ?? '');
a.download = requestFileName;
document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
a.click();
a.remove();
};
}
export const upload = async (url:string, formData: FormData) => {
await fetch(url, {
headers: {
Authorization: 'Bearer ' + localStorage['token']
},
method: 'Post',
body: formData,
})
}