mirror of https://github.com/nocodb/nocodb
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
412 lines
12 KiB
412 lines
12 KiB
2 years ago
|
import type { Api, ColumnType, FormType, GalleryType, PaginatedType, TableType, ViewType } from 'nocodb-sdk'
|
||
2 years ago
|
import type { ComputedRef, Ref } from 'vue'
|
||
2 years ago
|
import { message } from 'ant-design-vue'
|
||
2 years ago
|
import { useI18n } from 'vue-i18n'
|
||
2 years ago
|
import { useNuxtApp } from '#app'
|
||
2 years ago
|
import {
|
||
|
IsPublicInj,
|
||
|
NOCO,
|
||
|
extractPkFromRow,
|
||
|
extractSdkResponseErrorMsg,
|
||
2 years ago
|
getHTMLEncodedText,
|
||
2 years ago
|
useApi,
|
||
2 years ago
|
useProject,
|
||
|
useUIPermission,
|
||
|
} from '#imports'
|
||
2 years ago
|
|
||
2 years ago
|
const formatData = (list: Record<string, any>[]) =>
|
||
2 years ago
|
list.map((row) => ({
|
||
|
row: { ...row },
|
||
|
oldRow: { ...row },
|
||
2 years ago
|
rowMeta: {},
|
||
|
}))
|
||
2 years ago
|
|
||
2 years ago
|
export interface Row {
|
||
2 years ago
|
row: Record<string, any>
|
||
|
oldRow: Record<string, any>
|
||
2 years ago
|
rowMeta: {
|
||
|
new?: boolean
|
||
2 years ago
|
selected?: boolean
|
||
2 years ago
|
commentCount?: number
|
||
|
}
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
export function useViewData(
|
||
2 years ago
|
meta: Ref<TableType> | ComputedRef<TableType> | undefined,
|
||
2 years ago
|
viewMeta: Ref<ViewType & { id: string }> | ComputedRef<ViewType & { id: string }> | undefined,
|
||
2 years ago
|
where?: ComputedRef<string | undefined>,
|
||
2 years ago
|
) {
|
||
2 years ago
|
if (!meta) {
|
||
|
throw new Error('Table meta is not available')
|
||
|
}
|
||
|
|
||
2 years ago
|
const { t } = useI18n()
|
||
2 years ago
|
const { api, isLoading, error } = useApi()
|
||
2 years ago
|
const _paginationData = ref<PaginatedType>({ page: 1, pageSize: 25 })
|
||
2 years ago
|
const aggCommentCount = ref<{ row_id: string; count: number }[]>([])
|
||
2 years ago
|
const galleryData = ref<GalleryType>()
|
||
|
const formColumnData = ref<FormType>()
|
||
|
// todo: missing properties on FormType (success_msg, show_blank_form,
|
||
|
const formViewData = ref<FormType & { success_msg?: string; show_blank_form?: boolean }>()
|
||
2 years ago
|
const formattedData = ref<Row[]>([])
|
||
2 years ago
|
|
||
2 years ago
|
const isPublic = inject(IsPublicInj, ref(false))
|
||
2 years ago
|
const { project, isSharedBase } = useProject()
|
||
2 years ago
|
const { fetchSharedViewData, paginationData: sharedPaginationData } = useSharedView()
|
||
2 years ago
|
const { $api } = useNuxtApp()
|
||
2 years ago
|
const { sorts, nestedFilters } = useSmartsheetStoreOrThrow()
|
||
2 years ago
|
const { isUIAllowed } = useUIPermission()
|
||
2 years ago
|
|
||
|
const paginationData = computed({
|
||
|
get: () => (isPublic.value ? sharedPaginationData.value : _paginationData.value),
|
||
|
set: (value) => {
|
||
|
if (isPublic.value) {
|
||
|
sharedPaginationData.value = value
|
||
|
} else {
|
||
|
_paginationData.value = value
|
||
|
}
|
||
|
},
|
||
|
})
|
||
2 years ago
|
|
||
2 years ago
|
const selectedAllRecords = computed({
|
||
|
get() {
|
||
2 years ago
|
return !!formattedData.value.length && formattedData.value.every((row: Row) => row.rowMeta.selected)
|
||
2 years ago
|
},
|
||
2 years ago
|
set(selected: boolean) {
|
||
|
formattedData.value.forEach((row: Row) => (row.rowMeta.selected = selected))
|
||
2 years ago
|
},
|
||
|
})
|
||
|
|
||
2 years ago
|
const queryParams = computed(() => ({
|
||
|
offset: (paginationData.value?.page ?? 0) - 1,
|
||
|
limit: paginationData.value?.pageSize ?? 25,
|
||
|
where: where?.value ?? '',
|
||
|
}))
|
||
|
|
||
|
function addEmptyRow(addAfter = formattedData.value.length) {
|
||
|
formattedData.value.splice(addAfter, 0, {
|
||
|
row: {},
|
||
|
oldRow: {},
|
||
|
rowMeta: { new: true },
|
||
|
})
|
||
|
|
||
|
return formattedData.value[addAfter]
|
||
|
}
|
||
|
|
||
|
function removeLastEmptyRow() {
|
||
|
const lastRow = formattedData.value[formattedData.value.length - 1]
|
||
|
|
||
|
if (lastRow.rowMeta.new) {
|
||
|
formattedData.value.pop()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
async function syncCount() {
|
||
2 years ago
|
const { count } = await $api.dbViewRow.count(
|
||
|
NOCO,
|
||
|
project?.value?.title as string,
|
||
|
meta?.value?.id as string,
|
||
|
viewMeta?.value?.id as string,
|
||
|
)
|
||
|
paginationData.value.totalRows = count
|
||
|
}
|
||
|
|
||
2 years ago
|
async function syncPagination() {
|
||
|
// total records in the current table
|
||
|
const count = paginationData.value?.totalRows ?? Infinity
|
||
|
// the number of rows in a page
|
||
|
const size = paginationData.value?.pageSize ?? 25
|
||
|
// the current page number
|
||
|
const currentPage = paginationData.value?.page ?? 1
|
||
|
// the maximum possible page given the current count and the size
|
||
|
const mxPage = Math.ceil(count / size)
|
||
|
// calculate targetPage where 1 <= targetPage <= mxPage
|
||
|
const targetPage = Math.max(1, Math.min(mxPage, currentPage))
|
||
|
// if the current page is greater than targetPage,
|
||
|
// then the page should be changed instead of showing an empty page
|
||
|
// e.g. deleting all records in the last page N should return N - 1 page
|
||
|
if (currentPage > targetPage) {
|
||
|
// change to target page and load data of that page
|
||
|
changePage?.(targetPage)
|
||
|
} else {
|
||
|
// the current page is same as target page
|
||
|
// reload it to avoid empty row in this page
|
||
|
await loadData({
|
||
|
offset: (targetPage - 1) * size,
|
||
|
where: where?.value,
|
||
|
} as any)
|
||
|
}
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
/** load row comments count */
|
||
2 years ago
|
async function loadAggCommentsCount() {
|
||
2 years ago
|
if (isPublic.value || isSharedBase.value) return
|
||
2 years ago
|
|
||
|
const ids = formattedData.value
|
||
|
?.filter(({ rowMeta: { new: isNew } }) => !isNew)
|
||
|
?.map(({ row }) => {
|
||
|
return extractPkFromRow(row, meta?.value?.columns as ColumnType[])
|
||
|
})
|
||
|
|
||
2 years ago
|
if (!ids?.length || ids?.some((id) => !id)) return
|
||
2 years ago
|
|
||
|
aggCommentCount.value = await $api.utils.commentCount({
|
||
|
ids,
|
||
2 years ago
|
fk_model_id: meta?.value.id as string,
|
||
2 years ago
|
})
|
||
|
|
||
|
for (const row of formattedData.value) {
|
||
|
const id = extractPkFromRow(row.row, meta?.value?.columns as ColumnType[])
|
||
2 years ago
|
row.rowMeta.commentCount = aggCommentCount.value?.find((c: Record<string, any>) => c.row_id === id)?.count || 0
|
||
2 years ago
|
}
|
||
|
}
|
||
|
|
||
2 years ago
|
async function loadData(params: Parameters<Api<any>['dbViewRow']['list']>[4] = {}) {
|
||
2 years ago
|
if ((!project?.value?.id || !meta?.value?.id || !viewMeta?.value?.id) && !isPublic.value) return
|
||
|
const response = !isPublic.value
|
||
2 years ago
|
? await api.dbViewRow.list('noco', project.value.id!, meta!.value.id!, viewMeta!.value.id, {
|
||
2 years ago
|
...params,
|
||
|
...(isUIAllowed('sortSync') ? {} : { sortArrJson: JSON.stringify(sorts.value) }),
|
||
|
...(isUIAllowed('filterSync') ? {} : { filterArrJson: JSON.stringify(nestedFilters.value) }),
|
||
|
where: where?.value,
|
||
|
})
|
||
2 years ago
|
: await fetchSharedViewData()
|
||
|
formattedData.value = formatData(response.list)
|
||
|
paginationData.value = response.pageInfo
|
||
|
await loadAggCommentsCount()
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
2 years ago
|
async function loadGalleryData() {
|
||
2 years ago
|
if (!viewMeta?.value?.id) return
|
||
|
|
||
|
galleryData.value = await $api.dbView.galleryRead(viewMeta.value.id)
|
||
|
}
|
||
|
|
||
2 years ago
|
async function insertRow(row: Record<string, any>, rowIndex = formattedData.value?.length) {
|
||
2 years ago
|
try {
|
||
|
const insertObj = meta?.value?.columns?.reduce((o: any, col) => {
|
||
|
if (!col.ai && row?.[col.title as string] !== null) {
|
||
|
o[col.title as string] = row?.[col.title as string]
|
||
|
}
|
||
|
return o
|
||
|
}, {})
|
||
2 years ago
|
|
||
2 years ago
|
const insertedData = await $api.dbViewRow.create(
|
||
|
NOCO,
|
||
|
project?.value.id as string,
|
||
|
meta?.value.id as string,
|
||
|
viewMeta?.value?.id as string,
|
||
|
insertObj,
|
||
|
)
|
||
|
|
||
|
formattedData.value?.splice(rowIndex ?? 0, 1, {
|
||
|
row: insertedData,
|
||
|
rowMeta: {},
|
||
|
oldRow: { ...insertedData },
|
||
|
})
|
||
2 years ago
|
|
||
|
await syncCount()
|
||
2 years ago
|
return insertedData
|
||
2 years ago
|
} catch (error: any) {
|
||
2 years ago
|
message.error(await extractSdkResponseErrorMsg(error))
|
||
2 years ago
|
}
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
async function updateRowProperty(toUpdate: Row, property: string) {
|
||
2 years ago
|
try {
|
||
2 years ago
|
const id = extractPkFromRow(toUpdate.row, meta?.value.columns as ColumnType[])
|
||
2 years ago
|
|
||
2 years ago
|
const updatedRowData = await $api.dbViewRow.update(
|
||
2 years ago
|
NOCO,
|
||
|
project?.value.id as string,
|
||
|
meta?.value.id as string,
|
||
|
viewMeta?.value?.id as string,
|
||
|
id,
|
||
|
{
|
||
2 years ago
|
[property]: toUpdate.row[property],
|
||
2 years ago
|
},
|
||
|
// todo:
|
||
|
// {
|
||
|
// query: { ignoreWebhook: !saved }
|
||
|
// }
|
||
|
)
|
||
2 years ago
|
// audit
|
||
|
$api.utils
|
||
|
.auditRowUpdate(id, {
|
||
|
fk_model_id: meta?.value.id as string,
|
||
|
column_name: property,
|
||
|
row_id: id,
|
||
2 years ago
|
value: getHTMLEncodedText(toUpdate.row[property]),
|
||
|
prev_value: getHTMLEncodedText(toUpdate.oldRow[property]),
|
||
2 years ago
|
})
|
||
2 years ago
|
.then(() => {})
|
||
2 years ago
|
|
||
2 years ago
|
/** update row data(to sync formula and other related columns) */
|
||
2 years ago
|
Object.assign(toUpdate.row, updatedRowData)
|
||
|
Object.assign(toUpdate.oldRow, updatedRowData)
|
||
2 years ago
|
} catch (e: any) {
|
||
2 years ago
|
message.error(`${t('msg.error.rowUpdateFailed')} ${await extractSdkResponseErrorMsg(e)}`)
|
||
2 years ago
|
}
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
2 years ago
|
async function updateOrSaveRow(row: Row, property: string) {
|
||
2 years ago
|
if (row.rowMeta.new) {
|
||
|
await insertRow(row.row, formattedData.value.indexOf(row))
|
||
|
} else {
|
||
2 years ago
|
await updateRowProperty(row, property)
|
||
2 years ago
|
}
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
|
async function changePage(page: number) {
|
||
2 years ago
|
paginationData.value.page = page
|
||
2 years ago
|
await loadData({ offset: (page - 1) * (paginationData.value.pageSize || 25), where: where?.value } as any)
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
async function deleteRowById(id: string) {
|
||
2 years ago
|
if (!id) {
|
||
2 years ago
|
throw new Error("Delete not allowed for table which doesn't have primary Key")
|
||
2 years ago
|
}
|
||
|
|
||
|
const res: any = await $api.dbViewRow.delete(
|
||
|
'noco',
|
||
|
project.value.id as string,
|
||
|
meta?.value.id as string,
|
||
|
viewMeta?.value.id as string,
|
||
|
id,
|
||
|
)
|
||
|
|
||
|
if (res.message) {
|
||
2 years ago
|
message.info(
|
||
|
`Row delete failed: ${h('div', {
|
||
2 years ago
|
innerHTML: `<div style="padding:10px 4px">Unable to delete row with ID ${id} because of the following:
|
||
2 years ago
|
<br><br>${res.message.join('<br>')}<br><br>
|
||
|
Clear the data first & try again</div>`,
|
||
|
})}`,
|
||
|
)
|
||
2 years ago
|
return false
|
||
|
}
|
||
|
return true
|
||
|
}
|
||
|
|
||
2 years ago
|
async function deleteRow(rowIndex: number) {
|
||
2 years ago
|
try {
|
||
|
const row = formattedData.value[rowIndex]
|
||
2 years ago
|
if (!row.rowMeta.new) {
|
||
2 years ago
|
const id = meta?.value?.columns
|
||
|
?.filter((c) => c.pk)
|
||
|
.map((c) => row.row[c.title as any])
|
||
|
.join('___')
|
||
|
|
||
|
const deleted = await deleteRowById(id as string)
|
||
|
if (!deleted) {
|
||
|
return
|
||
|
}
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
formattedData.value.splice(rowIndex, 1)
|
||
2 years ago
|
|
||
|
await syncCount()
|
||
2 years ago
|
} catch (e: any) {
|
||
2 years ago
|
message.error(`${t('msg.error.deleteRowFailed')}: ${await extractSdkResponseErrorMsg(e)}`)
|
||
2 years ago
|
}
|
||
|
}
|
||
|
|
||
2 years ago
|
async function deleteSelectedRows() {
|
||
2 years ago
|
let row = formattedData.value.length
|
||
|
while (row--) {
|
||
|
try {
|
||
2 years ago
|
const { row: rowObj, rowMeta } = formattedData.value[row] as Record<string, any>
|
||
2 years ago
|
if (!rowMeta.selected) {
|
||
|
continue
|
||
|
}
|
||
|
if (!rowMeta.new) {
|
||
|
const id = meta?.value?.columns
|
||
|
?.filter((c) => c.pk)
|
||
|
.map((c) => rowObj[c.title as string])
|
||
|
.join('___')
|
||
|
|
||
|
const successfulDeletion = await deleteRowById(id as string)
|
||
|
if (!successfulDeletion) {
|
||
|
continue
|
||
|
}
|
||
|
}
|
||
|
formattedData.value.splice(row, 1)
|
||
|
} catch (e: any) {
|
||
2 years ago
|
return message.error(`${t('msg.error.deleteRowFailed')}: ${await extractSdkResponseErrorMsg(e)}`)
|
||
2 years ago
|
}
|
||
|
}
|
||
2 years ago
|
|
||
|
await syncCount()
|
||
2 years ago
|
await syncPagination()
|
||
|
}
|
||
|
|
||
2 years ago
|
async function loadFormView() {
|
||
2 years ago
|
if (!viewMeta?.value?.id) return
|
||
|
try {
|
||
2 years ago
|
const { columns, ...view } = (await $api.dbView.formRead(viewMeta.value.id)) as Record<string, any>
|
||
2 years ago
|
|
||
|
const fieldById = columns.reduce(
|
||
|
(o: Record<string, any>, f: Record<string, any>) => ({
|
||
|
...o,
|
||
|
[f.fk_column_id]: f,
|
||
|
}),
|
||
|
{},
|
||
|
)
|
||
|
|
||
|
let order = 1
|
||
|
|
||
2 years ago
|
formViewData.value = view
|
||
|
|
||
|
formColumnData.value = meta?.value?.columns
|
||
2 years ago
|
?.map((c: Record<string, any>) => ({
|
||
|
...c,
|
||
|
fk_column_id: c.id,
|
||
|
fk_view_id: viewMeta.value.id,
|
||
|
...(fieldById[c.id] ? fieldById[c.id] : {}),
|
||
|
order: (fieldById[c.id] && fieldById[c.id].order) || order++,
|
||
|
id: fieldById[c.id] && fieldById[c.id].id,
|
||
|
}))
|
||
|
.sort((a: Record<string, any>, b: Record<string, any>) => a.order - b.order) as Record<string, any>
|
||
2 years ago
|
} catch (e: any) {
|
||
2 years ago
|
return message.error(`${t('msg.error.setFormDataFailed')}: ${await extractSdkResponseErrorMsg(e)}`)
|
||
2 years ago
|
}
|
||
|
}
|
||
|
|
||
2 years ago
|
async function updateFormView(view: FormType | undefined) {
|
||
2 years ago
|
try {
|
||
|
if (!viewMeta?.value?.id || !view) return
|
||
|
await $api.dbView.formUpdate(viewMeta.value.id, view)
|
||
|
} catch (e: any) {
|
||
2 years ago
|
return message.error(`${t('msg.error.formViewUpdateFailed')}: ${await extractSdkResponseErrorMsg(e)}`)
|
||
2 years ago
|
}
|
||
|
}
|
||
|
|
||
2 years ago
|
return {
|
||
2 years ago
|
error,
|
||
2 years ago
|
isLoading,
|
||
2 years ago
|
loadData,
|
||
|
paginationData,
|
||
2 years ago
|
queryParams,
|
||
2 years ago
|
formattedData,
|
||
|
insertRow,
|
||
|
updateRowProperty,
|
||
|
changePage,
|
||
2 years ago
|
addEmptyRow,
|
||
|
deleteRow,
|
||
|
deleteSelectedRows,
|
||
2 years ago
|
updateOrSaveRow,
|
||
2 years ago
|
selectedAllRecords,
|
||
2 years ago
|
syncCount,
|
||
2 years ago
|
syncPagination,
|
||
2 years ago
|
galleryData,
|
||
|
loadGalleryData,
|
||
2 years ago
|
loadFormView,
|
||
|
formColumnData,
|
||
|
formViewData,
|
||
2 years ago
|
updateFormView,
|
||
2 years ago
|
aggCommentCount,
|
||
|
loadAggCommentsCount,
|
||
2 years ago
|
removeLastEmptyRow,
|
||
2 years ago
|
}
|
||
2 years ago
|
}
|