Skip to content

Instantly share code, notes, and snippets.

@dpmango
Created March 23, 2023 15:15
Show Gist options
  • Save dpmango/647e55e7f11fbfcb2f0b2356ab2b5cad to your computer and use it in GitHub Desktop.
Save dpmango/647e55e7f11fbfcb2f0b2356ab2b5cad to your computer and use it in GitHub Desktop.
// получение данных по модулю
// TODO - возможно лучше продублировать moduleId во всех запросах
const getModuleDataset = async ({
ModuleId,
PageNumber,
PageSize,
}: IGetModuleDatasetRequest) => {
const request = {
ModuleId: ModuleId || currentModuleId.value,
PageNumber: PageNumber || moduleDatasetMeta.value.page,
PageSize: PageSize || moduleDatasetMeta.value.limit,
SortProperty: moduleDatasetMeta.value.sort.id,
SortMode: moduleDatasetMeta.value.sort.dir === 'ASC' ? 0 : 1,
Filter: filterToApiDto.value,
}
// запрос
moduleDatasetFetching.value = true
const { data, error } = await GetJsDataList(request)
moduleDatasetFetching.value = false
if (data) {
const PERF_LOG = performance.now()
const { Rows, TotalCount } = data
const covertDtoToCollumn = [] as ITableRow[]
const snapshotHeadCollumns = [] as ITableCellHead[]
const currentModuleData = findModuleById(currentModuleId.value)
const userModule = authStore.getUserModule(ModuleId || currentModuleId.value)
const userModuleCollumns = userModule?.CurrentColumns
const hasUserModulerCollumns =
Array.isArray(userModuleCollumns) && userModuleCollumns.length
// маппинг данных апи в обьекты интерфейса ITable (AtomTable)
Rows.forEach((row, idx) => {
const mappedCells = row.Cells.map((cell, idxx) => {
// дефолтные колонки модуля по совпаденю Columns[].ColumnId
const dataCollumn = currentModuleData?.Columns
? currentModuleData?.Columns.find((x) => x.Id === cell.ColumnId)
: null
// пользовательские колонки
const userCollumn = userModuleCollumns?.length
? userModuleCollumns.find((x) => x.Id === cell.ColumnId)
: null
// базовый обьект содержит значения из листа данных и найстройки отображения
let cellReturnable = {
value: cell.Value,
type: cell.CellType,
presentation: {
background: cell.BackColor === '#FFFFFF' ? '' : cell.BackColor,
text: cell.TextColor || '',
},
} as ITableCell
// конвертация флагов
if (cell.CellType === 3 && cell.Value) {
cellReturnable.value = JSON.parse(cell.Value)
}
const returnWithID = (Id: string) => {
cellReturnable = {
...cellReturnable,
id: Id,
}
}
const returnNoting = () => {
cellReturnable = {
...cellReturnable,
id: '000x000',
}
}
const addSnapshot = (data: any) => {
snapshotHeadCollumns.push({
...cellReturnable,
presentation: null,
...data,
})
}
// условия отображения колонок и их настройки
if (userCollumn) {
// проритетно использовать колонки из настроек авторизации
returnWithID(userCollumn.Id)
} else if (hasUserModulerCollumns) {
// если есть колонки модуля (не [] или null), но нет колонки -
// = нет прав доступа
returnNoting()
} else if (dataCollumn?.IsUsage) {
// иначе использовать дефолтные настройки
returnWithID(dataCollumn.Id)
} else {
returnNoting()
}
// Создание снапшота колонок таблицы в отдельный компактный обьект стора
if (idx === 0 && (userCollumn || dataCollumn)) {
if (userCollumn) {
const { Id, Position, Title, Width } = userCollumn
const sort = {
sort: dataCollumn?.SortProperty || null,
sortDir: dataCollumn?.SortedDirection === 1 ? 'DESC' : 'ASC',
}
addSnapshot({
label: Title,
width: Width * 1.3,
...sort,
})
} else if (dataCollumn && !hasUserModulerCollumns) {
const { Title, Width, SortProperty, SortedDirection, IsUsage } = dataCollumn
if (IsUsage)
addSnapshot({
label: Title,
sort: SortProperty,
sortDir: SortedDirection === 0 ? 'ASC' : 'DESC',
width: Width * 1.3,
})
}
}
// возврат из цикла
return cellReturnable
})
covertDtoToCollumn.push({
id: row.Id,
title: row.Title,
color: row.Color,
cells: mappedCells.filter((x) => x.id !== '000x000'),
})
})
// установка стора
moduleDataset.value = covertDtoToCollumn
moduleDatasetSnapshot.value = snapshotHeadCollumns
const newMeta = {
...moduleDatasetMeta.value,
page: request.PageNumber,
count: TotalCount,
limit: request.PageSize,
}
// находит по id (колонки) дефолтную сортировку и ставит поле SortProperty
const defaultSortColId = userModule?.SortedColumn || currentModuleData?.DefaultSortColumn
let defaultSortDir: any = [0, 1].includes(userModule?.SortedDirection as number)
if (!defaultSortDir) {
defaultSortDir = currentModuleData?.DefaultSortDirection
}
if (defaultSortColId && !moduleDatasetMeta.value.sort.id) {
const columnMatchForSort = snapshotHeadCollumns.find((x) => x.id === defaultSortColId)
if (columnMatchForSort) {
newMeta.sort = {
id: columnMatchForSort.sort || null,
dir: defaultSortDir === 0 ? 'ASC' : 'DESC',
}
}
}
moduleDatasetMeta.value = {
...newMeta,
}
PerformanceLog(PERF_LOG, 'setModulesDataset')
}
// обработка ошибок
if (error) {
// toast.error(error.message)
ui.setModal({
name: 'notification',
params: {
type: 'error',
title: 'Ошибка при загрузке модуля',
description:
'Возможно он еще не подключен. Попробуйте позднее или обратитесь в техническую поддержку',
},
})
resetDataset()
}
return data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment