Skip to content

Commit 16aa3a0

Browse files
Get/Delete ChatMessage based on startDateTime / endDateTime (#3867)
* Get ChatMessage based on startDateTime / endDateTime - supplements existing startDate / endDate fields * Proper query handling for between case * Return 0 result rather than error * lint fix * update start date and end date query --------- Co-authored-by: Henry <[email protected]>
1 parent aab493c commit 16aa3a0

File tree

8 files changed

+100
-90
lines changed

8 files changed

+100
-90
lines changed

packages/server/src/controllers/chat-messages/index.ts

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ import { Request, Response, NextFunction } from 'express'
22
import { ChatMessageRatingType, ChatType, IReactFlowObject } from '../../Interface'
33
import chatflowsService from '../../services/chatflows'
44
import chatMessagesService from '../../services/chat-messages'
5-
import { aMonthAgo, clearSessionMemory, setDateToStartOrEndOfDay } from '../../utils'
5+
import { aMonthAgo, clearSessionMemory } from '../../utils'
66
import { getRunningExpressApp } from '../../utils/getRunningExpressApp'
7-
import { Between, FindOptionsWhere } from 'typeorm'
7+
import { Between, DeleteResult, FindOptionsWhere } from 'typeorm'
88
import { ChatMessage } from '../../database/entities/ChatMessage'
99
import { InternalFlowiseError } from '../../errors/internalFlowiseError'
1010
import { StatusCodes } from 'http-status-codes'
@@ -167,21 +167,21 @@ const removeAllChatMessages = async (req: Request, res: Response, next: NextFunc
167167
if (!chatId) {
168168
const isFeedback = feedbackTypeFilters?.length ? true : false
169169
const hardDelete = req.query?.hardDelete as boolean | undefined
170-
const messages = await utilGetChatMessage(
170+
const messages = await utilGetChatMessage({
171171
chatflowid,
172-
_chatType as ChatType | undefined,
173-
undefined,
174-
undefined,
175-
undefined,
176-
undefined,
172+
chatType: _chatType as ChatType | undefined,
177173
startDate,
178174
endDate,
179-
undefined,
180-
isFeedback,
181-
feedbackTypeFilters
182-
)
175+
feedback: isFeedback,
176+
feedbackTypes: feedbackTypeFilters
177+
})
183178
const messageIds = messages.map((message) => message.id)
184179

180+
if (messages.length === 0) {
181+
const result: DeleteResult = { raw: [], affected: 0 }
182+
return res.json(result)
183+
}
184+
185185
// Categorize by chatId_memoryType_sessionId
186186
const chatIdMap = new Map<string, ChatMessage[]>()
187187
messages.forEach((message) => {
@@ -238,8 +238,8 @@ const removeAllChatMessages = async (req: Request, res: Response, next: NextFunc
238238
if (sessionId) deleteOptions.sessionId = sessionId
239239
if (_chatType) deleteOptions.chatType = _chatType
240240
if (startDate && endDate) {
241-
const fromDate = setDateToStartOrEndOfDay(startDate, 'start')
242-
const toDate = setDateToStartOrEndOfDay(endDate, 'end')
241+
const fromDate = new Date(startDate)
242+
const toDate = new Date(endDate)
243243
deleteOptions.createdDate = Between(fromDate ?? aMonthAgo(), toDate ?? new Date())
244244
}
245245
const apiResponse = await chatMessagesService.removeAllChatMessages(chatId, chatflowid, deleteOptions)

packages/server/src/services/chat-messages/index.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,9 @@ const getAllChatMessages = async (
3939
feedbackTypes?: ChatMessageRatingType[]
4040
): Promise<ChatMessage[]> => {
4141
try {
42-
const dbResponse = await utilGetChatMessage(
43-
chatflowId,
44-
chatTypeFilter,
42+
const dbResponse = await utilGetChatMessage({
43+
chatflowid: chatflowId,
44+
chatType: chatTypeFilter,
4545
sortOrder,
4646
chatId,
4747
memoryType,
@@ -51,7 +51,7 @@ const getAllChatMessages = async (
5151
messageId,
5252
feedback,
5353
feedbackTypes
54-
)
54+
})
5555
return dbResponse
5656
} catch (error) {
5757
throw new InternalFlowiseError(
@@ -76,9 +76,9 @@ const getAllInternalChatMessages = async (
7676
feedbackTypes?: ChatMessageRatingType[]
7777
): Promise<ChatMessage[]> => {
7878
try {
79-
const dbResponse = await utilGetChatMessage(
80-
chatflowId,
81-
chatTypeFilter,
79+
const dbResponse = await utilGetChatMessage({
80+
chatflowid: chatflowId,
81+
chatType: chatTypeFilter,
8282
sortOrder,
8383
chatId,
8484
memoryType,
@@ -88,7 +88,7 @@ const getAllInternalChatMessages = async (
8888
messageId,
8989
feedback,
9090
feedbackTypes
91-
)
91+
})
9292
return dbResponse
9393
} catch (error) {
9494
throw new InternalFlowiseError(

packages/server/src/services/stats/index.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,15 @@ const getChatflowStats = async (
1717
feedbackTypes?: ChatMessageRatingType[]
1818
): Promise<any> => {
1919
try {
20-
const chatmessages = (await utilGetChatMessage(
20+
const chatmessages = (await utilGetChatMessage({
2121
chatflowid,
22-
chatTypeFilter,
23-
undefined,
24-
undefined,
25-
undefined,
26-
undefined,
22+
chatType: chatTypeFilter,
2723
startDate,
2824
endDate,
2925
messageId,
3026
feedback,
3127
feedbackTypes
32-
)) as Array<ChatMessage & { feedback?: ChatMessageFeedback }>
28+
})) as Array<ChatMessage & { feedback?: ChatMessageFeedback }>
3329
const totalMessages = chatmessages.length
3430
const totalFeedback = chatmessages.filter((message) => message?.feedback).length
3531
const positiveFeedback = chatmessages.filter((message) => message?.feedback?.rating === 'THUMBS_UP').length

packages/server/src/services/upsert-history/index.ts

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { MoreThanOrEqual, LessThanOrEqual } from 'typeorm'
1+
import { MoreThanOrEqual, LessThanOrEqual, Between } from 'typeorm'
22
import { StatusCodes } from 'http-status-codes'
33
import { getRunningExpressApp } from '../../utils/getRunningExpressApp'
44
import { UpsertHistory } from '../../database/entities/UpsertHistory'
@@ -14,26 +14,20 @@ const getAllUpsertHistory = async (
1414
try {
1515
const appServer = getRunningExpressApp()
1616

17-
const setDateToStartOrEndOfDay = (dateTimeStr: string, setHours: 'start' | 'end') => {
18-
const date = new Date(dateTimeStr)
19-
if (isNaN(date.getTime())) {
20-
return undefined
17+
let createdDateQuery
18+
if (startDate || endDate) {
19+
if (startDate && endDate) {
20+
createdDateQuery = Between(new Date(startDate), new Date(endDate))
21+
} else if (startDate) {
22+
createdDateQuery = MoreThanOrEqual(new Date(startDate))
23+
} else if (endDate) {
24+
createdDateQuery = LessThanOrEqual(new Date(endDate))
2125
}
22-
setHours === 'start' ? date.setHours(0, 0, 0, 0) : date.setHours(23, 59, 59, 999)
23-
return date
2426
}
25-
26-
let fromDate
27-
if (startDate) fromDate = setDateToStartOrEndOfDay(startDate, 'start')
28-
29-
let toDate
30-
if (endDate) toDate = setDateToStartOrEndOfDay(endDate, 'end')
31-
3227
let upsertHistory = await appServer.AppDataSource.getRepository(UpsertHistory).find({
3328
where: {
3429
chatflowid,
35-
...(fromDate && { date: MoreThanOrEqual(fromDate) }),
36-
...(toDate && { date: LessThanOrEqual(toDate) })
30+
date: createdDateQuery
3731
},
3832
order: {
3933
date: sortOrder === 'DESC' ? 'DESC' : 'ASC'

packages/server/src/utils/getChatMessage.ts

Lines changed: 47 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import { MoreThanOrEqual, LessThanOrEqual } from 'typeorm'
1+
import { MoreThanOrEqual, LessThanOrEqual, Between } from 'typeorm'
22
import { ChatMessageRatingType, ChatType } from '../Interface'
33
import { ChatMessage } from '../database/entities/ChatMessage'
44
import { ChatMessageFeedback } from '../database/entities/ChatMessageFeedback'
55
import { getRunningExpressApp } from '../utils/getRunningExpressApp'
6-
import { aMonthAgo, setDateToStartOrEndOfDay } from '.'
6+
import { aMonthAgo } from '.'
77

88
/**
99
* Method that get chat messages.
@@ -18,26 +18,34 @@ import { aMonthAgo, setDateToStartOrEndOfDay } from '.'
1818
* @param {boolean} feedback
1919
* @param {ChatMessageRatingType[]} feedbackTypes
2020
*/
21-
export const utilGetChatMessage = async (
22-
chatflowid: string,
23-
chatType: ChatType | undefined,
24-
sortOrder: string = 'ASC',
25-
chatId?: string,
26-
memoryType?: string,
27-
sessionId?: string,
28-
startDate?: string,
29-
endDate?: string,
30-
messageId?: string,
31-
feedback?: boolean,
21+
interface GetChatMessageParams {
22+
chatflowid: string
23+
chatType?: ChatType
24+
sortOrder?: string
25+
chatId?: string
26+
memoryType?: string
27+
sessionId?: string
28+
startDate?: string
29+
endDate?: string
30+
messageId?: string
31+
feedback?: boolean
3232
feedbackTypes?: ChatMessageRatingType[]
33-
): Promise<ChatMessage[]> => {
34-
const appServer = getRunningExpressApp()
35-
36-
let fromDate
37-
if (startDate) fromDate = setDateToStartOrEndOfDay(startDate, 'start')
33+
}
3834

39-
let toDate
40-
if (endDate) toDate = setDateToStartOrEndOfDay(endDate, 'end')
35+
export const utilGetChatMessage = async ({
36+
chatflowid,
37+
chatType,
38+
sortOrder = 'ASC',
39+
chatId,
40+
memoryType,
41+
sessionId,
42+
startDate,
43+
endDate,
44+
messageId,
45+
feedback,
46+
feedbackTypes
47+
}: GetChatMessageParams): Promise<ChatMessage[]> => {
48+
const appServer = getRunningExpressApp()
4149

4250
if (feedback) {
4351
const query = await appServer.AppDataSource.getRepository(ChatMessage).createQueryBuilder('chat_message')
@@ -62,10 +70,13 @@ export const utilGetChatMessage = async (
6270
}
6371

6472
// set date range
65-
query.andWhere('chat_message.createdDate BETWEEN :fromDate AND :toDate', {
66-
fromDate: fromDate ?? aMonthAgo(),
67-
toDate: toDate ?? new Date()
68-
})
73+
if (startDate) {
74+
query.andWhere('chat_message.createdDate >= :startDateTime', { startDateTime: startDate ? new Date(startDate) : aMonthAgo() })
75+
}
76+
if (endDate) {
77+
query.andWhere('chat_message.createdDate <= :endDateTime', { endDateTime: endDate ? new Date(endDate) : new Date() })
78+
}
79+
6980
// sort
7081
query.orderBy('chat_message.createdDate', sortOrder === 'DESC' ? 'DESC' : 'ASC')
7182

@@ -89,15 +100,25 @@ export const utilGetChatMessage = async (
89100
return messages
90101
}
91102

103+
let createdDateQuery
104+
if (startDate || endDate) {
105+
if (startDate && endDate) {
106+
createdDateQuery = Between(new Date(startDate), new Date(endDate))
107+
} else if (startDate) {
108+
createdDateQuery = MoreThanOrEqual(new Date(startDate))
109+
} else if (endDate) {
110+
createdDateQuery = LessThanOrEqual(new Date(endDate))
111+
}
112+
}
113+
92114
return await appServer.AppDataSource.getRepository(ChatMessage).find({
93115
where: {
94116
chatflowid,
95117
chatType,
96118
chatId,
97119
memoryType: memoryType ?? undefined,
98120
sessionId: sessionId ?? undefined,
99-
...(fromDate && { createdDate: MoreThanOrEqual(fromDate) }),
100-
...(toDate && { createdDate: LessThanOrEqual(toDate) }),
121+
createdDate: createdDateQuery,
101122
id: messageId ?? undefined
102123
},
103124
order: {

packages/server/src/utils/index.ts

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1745,15 +1745,6 @@ export const convertToValidFilename = (word: string) => {
17451745
.toLowerCase()
17461746
}
17471747

1748-
export const setDateToStartOrEndOfDay = (dateTimeStr: string, setHours: 'start' | 'end') => {
1749-
const date = new Date(dateTimeStr)
1750-
if (isNaN(date.getTime())) {
1751-
return undefined
1752-
}
1753-
setHours === 'start' ? date.setHours(0, 0, 0, 0) : date.setHours(23, 59, 59, 999)
1754-
return date
1755-
}
1756-
17571748
export const aMonthAgo = () => {
17581749
const date = new Date()
17591750
date.setMonth(new Date().getMonth() - 1)

packages/ui/src/ui-component/dialog/ViewMessagesDialog.jsx

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -167,28 +167,32 @@ const ViewMessagesDialog = ({ show, dialogProps, onCancel }) => {
167167
let storagePath = ''
168168

169169
const onStartDateSelected = (date) => {
170-
setStartDate(date)
170+
const updatedDate = new Date(date)
171+
updatedDate.setHours(0, 0, 0, 0)
172+
setStartDate(updatedDate)
171173
getChatmessageApi.request(dialogProps.chatflow.id, {
172-
startDate: date,
174+
startDate: updatedDate,
173175
endDate: endDate,
174176
chatType: chatTypeFilter.length ? chatTypeFilter : undefined
175177
})
176178
getStatsApi.request(dialogProps.chatflow.id, {
177-
startDate: date,
179+
startDate: updatedDate,
178180
endDate: endDate,
179181
chatType: chatTypeFilter.length ? chatTypeFilter : undefined
180182
})
181183
}
182184

183185
const onEndDateSelected = (date) => {
184-
setEndDate(date)
186+
const updatedDate = new Date(date)
187+
updatedDate.setHours(23, 59, 59, 999)
188+
setEndDate(updatedDate)
185189
getChatmessageApi.request(dialogProps.chatflow.id, {
186-
endDate: date,
190+
endDate: updatedDate,
187191
startDate: startDate,
188192
chatType: chatTypeFilter.length ? chatTypeFilter : undefined
189193
})
190194
getStatsApi.request(dialogProps.chatflow.id, {
191-
endDate: date,
195+
endDate: updatedDate,
192196
startDate: startDate,
193197
chatType: chatTypeFilter.length ? chatTypeFilter : undefined
194198
})

packages/ui/src/views/vectorstore/UpsertHistoryDialog.jsx

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -211,17 +211,21 @@ const UpsertHistoryDialog = ({ show, dialogProps, onCancel }) => {
211211
}
212212

213213
const onStartDateSelected = (date) => {
214-
setStartDate(date)
214+
const updatedDate = new Date(date)
215+
updatedDate.setHours(0, 0, 0, 0)
216+
setStartDate(updatedDate)
215217
getUpsertHistoryApi.request(dialogProps.chatflow.id, {
216-
startDate: date,
218+
startDate: updatedDate,
217219
endDate: endDate
218220
})
219221
}
220222

221223
const onEndDateSelected = (date) => {
222-
setEndDate(date)
224+
const updatedDate = new Date(date)
225+
updatedDate.setHours(23, 59, 59, 999)
226+
setEndDate(updatedDate)
223227
getUpsertHistoryApi.request(dialogProps.chatflow.id, {
224-
endDate: date,
228+
endDate: updatedDate,
225229
startDate: startDate
226230
})
227231
}

0 commit comments

Comments
 (0)