多维表格
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.

772 lines
26 KiB

import type { ComputedRef, Ref } from 'vue'
import { type Api, type CalendarType, type ColumnType, type PaginatedType, type TableType, type ViewType } from 'nocodb-sdk'
import dayjs from 'dayjs'
import { addDays, addMonths, addYears, extractPkFromRow, extractSdkResponseErrorMsg, rowPkData } from '~/utils'
import { IsPublicInj, type Row, ref, storeToRefs, useBase, useInjectionState, useUndoRedo } from '#imports'
const formatData = (list: Record<string, any>[]) =>
9 months ago
list.map(
(row) =>
({
row: { ...row },
oldRow: { ...row },
rowMeta: {},
} as Row),
)
const [useProvideCalendarViewStore, useCalendarViewStore] = useInjectionState(
9 months ago
(
meta: Ref<((CalendarType & { id: string }) | TableType) | undefined>,
9 months ago
viewMeta: Ref<(ViewType | CalendarType | undefined) & { id: string }> | ComputedRef<(ViewType & { id: string }) | undefined>,
shared = false,
where?: ComputedRef<string | undefined>,
) => {
if (!meta) {
throw new Error('Table meta is not available')
}
9 months ago
const pageDate = ref<Date>(new Date())
const { isUIAllowed } = useRoles()
const displayField = ref<ColumnType>()
const activeCalendarView = ref<'month' | 'year' | 'day' | 'week'>()
const searchQuery = reactive({
value: '',
field: '',
})
9 months ago
const selectedDate = ref<Date>(new Date())
const selectedTime = ref<Date | null>(null)
const selectedMonth = ref<Date>(new Date())
const isCalendarDataLoading = ref<boolean>(false)
9 months ago
const selectedDateRange = ref<{
start: Date | null
end: Date | null
}>({
start: dayjs(selectedDate.value).startOf('week').toDate(), // This will be the previous Monday
end: dayjs(selectedDate.value).startOf('week').add(6, 'day').toDate(), // This will be the following Sunday
})
const defaultPageSize = 25
9 months ago
const formattedData = ref<Row[]>([])
const formattedSideBarData = ref<Row[]>([])
const isSidebarLoading = ref<boolean>(false)
const sideBarFilterOption = ref<string>(activeCalendarView.value ?? 'allRecords')
9 months ago
const { api } = useApi()
9 months ago
const { base } = storeToRefs(useBase())
9 months ago
const { $api } = useNuxtApp()
const { t } = useI18n()
const { addUndo, clone, defineViewScope } = useUndoRedo()
9 months ago
const isPublic = ref(shared) || inject(IsPublicInj, ref(false))
9 months ago
const { sorts, nestedFilters } = useSmartsheetStoreOrThrow()
9 months ago
const { sharedView, fetchSharedViewData } = useSharedView()
9 months ago
const calendarMetaData = ref<CalendarType>({})
9 months ago
const paginationData = ref<PaginatedType>({ page: 1, pageSize: defaultPageSize })
9 months ago
const queryParams = computed(() => ({
limit: paginationData.value.pageSize ?? defaultPageSize,
where: where?.value ?? '',
}))
const calendarRange = ref<
Array<{
fk_from_col: ColumnType | null
fk_to_col: ColumnType | null
}>
>([])
const calDataType = computed(() => {
if (!calendarRange.value || !calendarRange.value[0]) return null
9 months ago
return calendarRange.value[0]!.fk_from_col!.uidt
})
const sideBarFilter = computed(() => {
let combinedFilters: any = []
if (sideBarFilterOption.value === 'allRecords') {
combinedFilters = []
} else if (sideBarFilterOption.value === 'withoutDates') {
calendarRange.value.forEach((range) => {
const fromCol = range.fk_from_col
const toCol = range.fk_to_col
if (!fromCol) return
const filters = []
if (fromCol) {
filters.push({
fk_column_id: fromCol.id,
logical_op: 'or',
comparison_op: 'blank',
})
}
if (toCol) {
filters.push({
fk_column_id: toCol.id,
logical_op: 'or',
comparison_op: 'blank',
})
}
// Combine the filters for this range with the overall filter array
combinedFilters = [...combinedFilters, ...filters]
})
// Wrap the combined filters in a group
combinedFilters = [
{
is_group: true,
logical_op: 'or',
children: combinedFilters,
},
]
} else if (
sideBarFilterOption.value === 'week' ||
sideBarFilterOption.value === 'month' ||
sideBarFilterOption.value === 'day' ||
sideBarFilterOption.value === 'year' ||
sideBarFilterOption.value === 'selectedDate'
) {
let fromDate: string | null | dayjs.Dayjs = null
let toDate: string | null | dayjs.Dayjs = null
switch (sideBarFilterOption.value) {
case 'day':
fromDate = dayjs(selectedDate.value).startOf('day')
toDate = dayjs(selectedDate.value).endOf('day')
break
case 'week':
fromDate = dayjs(selectedDateRange.value.start).startOf('day')
toDate = dayjs(selectedDateRange.value.end).endOf('day')
break
case 'month': {
const startOfMonth = dayjs(selectedMonth.value).startOf('month')
const endOfMonth = dayjs(selectedMonth.value).endOf('month')
const daysToDisplay = Math.max(endOfMonth.diff(startOfMonth, 'day') + 1, 35)
fromDate = startOfMonth.subtract((startOfMonth.day() + 7) % 7, 'day').add(1, 'day')
toDate = fromDate.add(daysToDisplay, 'day').endOf('day')
break
}
case 'year':
fromDate = dayjs(selectedDate.value).startOf('year')
toDate = dayjs(selectedDate.value).endOf('year')
break
case 'selectedDate':
fromDate = dayjs(selectedDate.value).startOf('day')
toDate = dayjs(selectedDate.value).endOf('day')
break
}
fromDate = dayjs(fromDate).format('YYYY-MM-DD HH:mm:ssZ')
toDate = dayjs(toDate).format('YYYY-MM-DD HH:mm:ssZ')
calendarRange.value.forEach((range) => {
const fromCol = range.fk_from_col
const toCol = range.fk_to_col
let rangeFilter: any = []
if (fromCol && toCol) {
rangeFilter = [
{
is_group: true,
logical_op: 'and',
children: [
{
is_group: true,
logical_op: 'or',
children: [
{
is_group: true,
logical_op: 'and',
children: [
{
fk_column_id: fromCol.id,
comparison_op: 'lte',
comparison_sub_op: 'exactDate',
value: toDate,
},
{
fk_column_id: toCol.id,
comparison_op: 'gte',
comparison_sub_op: 'exactDate',
value: fromDate,
},
],
},
{
// Exact match check
is_group: true,
logical_op: 'or',
children: [
{
fk_column_id: fromCol.id,
comparison_op: 'eq',
logical_op: 'or',
comparison_sub_op: 'exactDate',
value: fromDate,
},
{
fk_column_id: toCol.id,
comparison_op: 'eq',
logical_op: 'or',
comparison_sub_op: 'exactDate',
value: toDate,
},
],
},
],
},
],
},
]
} else if (fromCol) {
rangeFilter = [
{
fk_column_id: fromCol.id,
comparison_op: 'btw',
comparison_sub_op: 'exactDate',
value: `${fromDate},${toDate}`,
},
]
}
if (rangeFilter.length > 0) {
combinedFilters.push({
is_group: true,
logical_op: 'or',
children: rangeFilter,
})
}
})
}
if (displayField.value && searchQuery.value) {
if (combinedFilters.length > 0) {
combinedFilters = [
{
is_group: true,
logical_op: 'and',
children: [
...combinedFilters,
{
fk_column_id: displayField.value.id,
comparison_op: 'like',
value: searchQuery.value,
},
],
},
]
} else {
combinedFilters.push({
fk_column_id: displayField.value.id,
comparison_op: 'like',
value: searchQuery.value,
})
}
}
return combinedFilters
})
async function loadMoreSidebarData(params: Parameters<Api<any>['dbViewRow']['list']>[4] = {}) {
if ((!base?.value?.id || !meta.value?.id || !viewMeta.value?.id) && !isPublic.value) return
if (isSidebarLoading.value) return
try {
const response = !isPublic.value
? await api.dbViewRow.list('noco', base.value.id!, meta.value!.id!, viewMeta.value!.id, {
...params,
offset: params.offset,
...{},
...{},
...(isUIAllowed('filterSync')
? { filterArrJson: JSON.stringify([...sideBarFilter.value]) }
: { filterArrJson: JSON.stringify([nestedFilters.value, ...sideBarFilter.value]) }),
})
: await fetchSharedViewData({
...params,
sortsArr: sorts.value,
filtersArr: sideBarFilter.value,
offset: params.offset,
where: where?.value ?? '',
})
formattedSideBarData.value = [...formattedSideBarData.value, ...formatData(response!.list)]
} catch (e) {
console.log(e)
}
}
const filterJSON = computed(() => {
const combinedFilters: any = {
is_group: true,
logical_op: 'and',
children: [],
}
let fromDate: dayjs.Dayjs | null | string = null
let toDate: dayjs.Dayjs | null | string = null
switch (activeCalendarView.value) {
case 'week':
fromDate = dayjs(selectedDateRange.value.start).startOf('day')
toDate = dayjs(selectedDateRange.value.end).endOf('day')
break
case 'month': {
const startOfMonth = dayjs(selectedMonth.value).startOf('month')
const endOfMonth = dayjs(selectedMonth.value).endOf('month')
const daysToDisplay = Math.max(endOfMonth.diff(startOfMonth, 'day') + 1, 35)
fromDate = startOfMonth.subtract((startOfMonth.day() + 7) % 7, 'day')
toDate = fromDate.add(daysToDisplay, 'day')
break
}
case 'year':
fromDate = dayjs(selectedDate.value).startOf('year')
toDate = dayjs(selectedDate.value).endOf('year')
break
case 'day':
fromDate = dayjs(selectedDate.value).startOf('day')
toDate = dayjs(selectedDate.value).endOf('day')
break
}
fromDate = dayjs(fromDate).format('YYYY-MM-DD HH:mm:ssZ')
toDate = dayjs(toDate).format('YYYY-MM-DD HH:mm:ssZ')
calendarRange.value.forEach((range) => {
const fromCol = range.fk_from_col
const toCol = range.fk_to_col
let rangeFilter: any = []
if (fromCol && toCol) {
rangeFilter = [
{
is_group: true,
logical_op: 'and',
children: [
{
is_group: true,
logical_op: 'or',
children: [
{
is_group: true,
logical_op: 'and',
children: [
{
fk_column_id: fromCol.id,
comparison_op: 'lte',
comparison_sub_op: 'exactDate',
value: toDate,
},
{
fk_column_id: toCol.id,
comparison_op: 'gte',
comparison_sub_op: 'exactDate',
value: fromDate,
},
],
},
{
// Exact match check
is_group: true,
logical_op: 'or',
children: [
{
fk_column_id: fromCol.id,
comparison_op: 'eq',
logical_op: 'or',
comparison_sub_op: 'exactDate',
value: fromDate,
},
{
fk_column_id: toCol.id,
comparison_op: 'eq',
logical_op: 'or',
comparison_sub_op: 'exactDate',
value: toDate,
},
],
},
],
},
],
},
]
} else if (fromCol) {
rangeFilter = [
{
fk_column_id: fromCol.id,
comparison_op: 'btw',
comparison_sub_op: 'exactDate',
value: `${fromDate},${toDate}`,
},
]
}
if (rangeFilter.length > 0) {
combinedFilters.children.push({
is_group: true,
logical_op: 'or',
children: rangeFilter,
})
}
})
return combinedFilters.children.length > 0 ? [combinedFilters] : []
})
// Set of Dates that have data
const activeDates = computed(() => {
if (!formattedData.value || !calendarRange.value) return []
const dates = new Set<Date>()
calendarRange.value.forEach((range) => {
formattedData.value.forEach((row) => {
const start = row.row[range.fk_from_col?.title ?? '']
let end
if (range.fk_to_col) {
end = row.row[range.fk_to_col.title ?? '']
}
if (start && end) {
const startDate = dayjs(start)
let endDate = dayjs(end)
let currentDate = startDate
// We have to check whether the start is after the end date, if so, loop through the end date
if (startDate.isAfter(endDate)) {
endDate = startDate
currentDate = endDate
}
while (currentDate.isSameOrBefore(endDate)) {
dates.add(currentDate.toDate())
currentDate = currentDate.add(1, 'day')
}
} else if (start) {
dates.add(new Date(start))
}
})
})
return Array.from(dates)
})
const changeCalendarView = async (view: 'month' | 'year' | 'day' | 'week') => {
try {
activeCalendarView.value = view
await updateCalendarMeta({
meta: {
...(typeof calendarMetaData.value.meta === 'string'
? JSON.parse(calendarMetaData.value.meta)
: calendarMetaData.value.meta),
active_view: view,
},
})
if (activeCalendarView.value === 'week') {
selectedTime.value = null
}
} catch (e) {
message.error('Error changing calendar view')
console.log(e)
}
9 months ago
}
9 months ago
async function loadCalendarMeta() {
if (!viewMeta?.value?.id || !meta?.value?.columns) return
const res = isPublic.value ? (sharedView.value?.view as CalendarType) : await $api.dbView.calendarRead(viewMeta.value.id)
calendarMetaData.value = res
const calMeta = typeof res.meta === 'string' ? JSON.parse(res.meta) : res.meta
activeCalendarView.value = calMeta?.active_view
if (!activeCalendarView.value) activeCalendarView.value = 'month'
calendarRange.value = res?.calendar_range!.map((range: any) => {
return {
fk_from_col: meta.value?.columns!.find((col) => col.id === range.fk_from_column_id),
fk_to_col: range.fk_to_column_id ? meta.value?.columns!.find((col) => col.id === range.fk_to_column_id) : null,
}
}) as any
displayField.value = meta.value.columns.find((col) => col.pv)
9 months ago
}
async function loadCalendarData() {
if ((!base?.value?.id || !meta.value?.id || !viewMeta.value?.id || !filterJSON.value) && !isPublic?.value) return
isCalendarDataLoading.value = true
9 months ago
const res = !isPublic.value
? await api.dbViewRow.list('noco', base.value.id!, meta.value!.id!, viewMeta.value!.id!, {
...queryParams.value,
...(isUIAllowed('filterSync')
? { filterArrJson: JSON.stringify([...filterJSON.value]) }
: { filterArrJson: JSON.stringify([nestedFilters.value, ...filterJSON.value]) }),
where: where?.value ?? '',
9 months ago
})
: await fetchSharedViewData({ sortsArr: sorts.value, filtersArr: filterJSON.value })
9 months ago
formattedData.value = formatData(res!.list)
isCalendarDataLoading.value = false
9 months ago
}
async function updateCalendarMeta(updateObj: Partial<CalendarType>) {
if (!viewMeta?.value?.id || !isUIAllowed('dataEdit') || isPublic.value) return
try {
await $api.dbView.calendarUpdate(viewMeta.value.id, updateObj)
calendarMetaData.value = {
...calendarMetaData.value,
...updateObj,
}
} catch (e) {
message.error('Error updating changes')
console.log(e)
}
9 months ago
}
function findRowInState(rowData: Record<string, any>) {
const pk: Record<string, string> = rowPkData(rowData, meta?.value?.columns as ColumnType[])
for (const row of formattedData.value) {
if (Object.keys(pk).every((k) => pk[k] === row.row[k])) {
return row
}
}
}
const paginateCalendarView = async (action: 'next' | 'prev') => {
9 months ago
switch (activeCalendarView.value) {
case 'month':
selectedMonth.value = action === 'next' ? addMonths(selectedMonth.value, 1) : addMonths(selectedMonth.value, -1)
// selectedDate.value = action === 'next' ? addMonths(selectedDate.value, 1) : addMonths(selectedDate.value, -1)
pageDate.value = action === 'next' ? addMonths(pageDate.value, 1) : addMonths(pageDate.value, -1)
9 months ago
if (pageDate.value.getFullYear() !== selectedDate.value.getFullYear()) {
pageDate.value = selectedDate.value
}
break
case 'year':
selectedDate.value = action === 'next' ? addYears(selectedDate.value, 1) : addYears(selectedDate.value, -1)
if (pageDate.value.getFullYear() !== selectedDate.value.getFullYear()) {
pageDate.value = selectedDate.value
}
break
case 'day':
selectedDate.value = action === 'next' ? addDays(selectedDate.value, 1) : addDays(selectedDate.value, -1)
if (pageDate.value.getFullYear() !== selectedDate.value.getFullYear()) {
pageDate.value = selectedDate.value
} else if (pageDate.value.getMonth() !== selectedDate.value.getMonth()) {
pageDate.value = selectedDate.value
}
break
case 'week':
selectedDateRange.value =
action === 'next'
? {
start: addDays(selectedDateRange.value.start!, 7),
end: addDays(selectedDateRange.value.end!, 7),
}
: {
start: addDays(selectedDateRange.value.start!, -7),
end: addDays(selectedDateRange.value.end!, -7),
}
if (pageDate.value.getMonth() !== selectedDateRange.value.end?.getMonth()) {
pageDate.value = selectedDateRange.value.start!
}
9 months ago
break
}
}
const loadSidebarData = async () => {
if (!base?.value?.id || !meta.value?.id || !viewMeta.value?.id) return
isSidebarLoading.value = true
const res = !isPublic.value
? await api.dbViewRow.list('noco', base.value.id!, meta.value!.id!, viewMeta.value.id, {
...queryParams.value,
...{},
...{},
...{ filterArrJson: JSON.stringify([...sideBarFilter.value]) },
})
: await fetchSharedViewData({ sortsArr: sorts.value, filtersArr: filterJSON.value })
formattedSideBarData.value = formatData(res!.list)
isSidebarLoading.value = false
}
9 months ago
async function updateRowProperty(toUpdate: Row, property: string[], undo = false) {
try {
const id = extractPkFromRow(toUpdate.row, meta?.value?.columns as ColumnType[])
9 months ago
const updateObj = property.reduce(
(
acc: {
[x: string]: string
},
curr,
) => {
acc[curr] = toUpdate.row[curr]
return acc
},
{},
)
const updatedRowData = await $api.dbViewRow.update(
NOCO,
base?.value.id as string,
meta.value?.id as string,
viewMeta?.value?.id as string,
id,
updateObj,
{
query: { ignoreWebhook: !undo },
},
// todo:
// {
// query: { ignoreWebhook: !saved }
// }
)
if (!undo) {
addUndo({
redo: {
fn: async (toUpdate: Row, property: string[]) => {
const updatedRow = await updateRowProperty(toUpdate, property, true)
const row = findRowInState(toUpdate.row)
if (row) {
Object.assign(row.row, updatedRow)
}
Object.assign(row.oldRow, updatedRow)
},
args: [clone(toUpdate), property],
},
undo: {
fn: async (toUpdate: Row, property: string[]) => {
const updatedData = await updateRowProperty(
{ row: toUpdate.oldRow, oldRow: toUpdate.row, rowMeta: toUpdate.rowMeta },
property,
true,
)
const row = findRowInState(toUpdate.row)
if (row) {
Object.assign(row.row, updatedData)
}
Object.assign(row!.oldRow, updatedData)
},
args: [clone(toUpdate), property],
},
scope: defineViewScope({ view: viewMeta.value as ViewType }),
})
Object.assign(toUpdate.row, updatedRowData)
Object.assign(toUpdate.oldRow, updatedRowData)
}
return updatedRowData
} catch (e: any) {
message.error(`${t('msg.error.rowUpdateFailed')} ${await extractSdkResponseErrorMsg(e)}`)
}
}
watch(selectedDate, async () => {
if (activeCalendarView.value === 'month' || activeCalendarView.value === 'week') {
await loadSidebarData()
} else {
await Promise.all([loadCalendarData(), loadSidebarData()])
}
})
watch(selectedMonth, async () => {
if (activeCalendarView.value !== 'month') return
await Promise.all([loadCalendarData(), loadSidebarData()])
})
watch(selectedDateRange, async () => {
if (activeCalendarView.value !== 'week') return
await Promise.all([loadCalendarData(), loadSidebarData()])
})
9 months ago
watch(activeCalendarView, async (value, oldValue) => {
if (oldValue === 'week') {
pageDate.value = selectedDate.value
selectedDate.value = selectedDateRange.value.start!
selectedMonth.value = selectedDateRange.value.start!
} else if (oldValue === 'month') {
selectedDate.value = selectedMonth.value
pageDate.value = selectedDate.value
selectedDateRange.value = {
start: dayjs(selectedDate.value).startOf('week').toDate(),
end: dayjs(selectedDate.value).endOf('week').toDate(),
}
} else if (oldValue === 'day') {
pageDate.value = selectedDate.value
selectedMonth.value = selectedDate.value
selectedDateRange.value = {
start: dayjs(selectedDate.value).startOf('week').toDate(),
end: dayjs(selectedDate.value).endOf('week').toDate(),
}
} else if (oldValue === 'year') {
selectedMonth.value = selectedDate.value
pageDate.value = selectedDate.value
selectedDateRange.value = {
start: dayjs(selectedDate.value).startOf('week').toDate(),
end: dayjs(selectedDate.value).endOf('week').toDate(),
}
}
sideBarFilterOption.value = activeCalendarView.value ?? 'allRecords'
await Promise.all([loadCalendarData(), loadSidebarData()])
})
watch(sideBarFilterOption, async () => {
await loadSidebarData()
})
watch(searchQuery, async () => {
await loadSidebarData()
})
9 months ago
return {
formattedSideBarData,
loadMoreSidebarData,
loadSidebarData,
displayField,
sideBarFilterOption,
searchQuery,
activeDates,
isCalendarDataLoading,
9 months ago
changeCalendarView,
calDataType,
loadCalendarMeta,
calendarRange,
loadCalendarData,
formattedData,
isSidebarLoading,
selectedTime,
9 months ago
updateCalendarMeta,
calendarMetaData,
updateRowProperty,
9 months ago
activeCalendarView,
pageDate,
paginationData,
selectedDate,
selectedMonth,
9 months ago
selectedDateRange,
paginateCalendarView,
}
},
)
export { useProvideCalendarViewStore }
export function useCalendarViewStoreOrThrow() {
9 months ago
const calendarViewStore = useCalendarViewStore()
9 months ago
if (calendarViewStore == null) throw new Error('Please call `useProvideCalendarViewStore` on the appropriate parent component')
9 months ago
return calendarViewStore
}