Skip to content

Commit

Permalink
feat: refactored to fit with summary endpt
Browse files Browse the repository at this point in the history
- also refactored tests accordingly
  • Loading branch information
ilee2u committed Dec 3, 2024
1 parent 4cdc186 commit 5c3b5cf
Show file tree
Hide file tree
Showing 11 changed files with 261 additions and 296 deletions.
21 changes: 2 additions & 19 deletions src/data/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,7 @@ async function fetchChatResponse(courseId, messageList, unitId, customQueryParam
return data;
}

async function fetchLearningAssistantEnabled(courseId) {
const url = new URL(`${getConfig().CHAT_RESPONSE_URL}/${courseId}/enabled`);

const { data } = await getAuthenticatedHttpClient().get(url.href);
return data;
}

async function fetchLearningAssistantMessageHistory(courseId) {
const url = new URL(`${getConfig().CHAT_RESPONSE_URL}/${courseId}/history`);

const { data } = await getAuthenticatedHttpClient().get(url.href);
return data;
}

async function fetchLearningAssistantAuditTrial(courseId) {
// TODO: Insert correct URL once get endpoint is implemented.
async function fetchLearningAssistantSummary(courseId) {
const url = new URL(`${getConfig().CHAT_RESPONSE_URL}/${courseId}/summary`);

const { data } = await getAuthenticatedHttpClient().get(url.href);
Expand All @@ -47,7 +32,5 @@ async function fetchLearningAssistantAuditTrial(courseId) {

export {
fetchChatResponse,
fetchLearningAssistantAuditTrial,
fetchLearningAssistantEnabled,
fetchLearningAssistantMessageHistory,
fetchLearningAssistantSummary,
};
47 changes: 27 additions & 20 deletions src/data/api.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable no-import-assign */
import * as auth from '@edx/frontend-platform/auth';

import { fetchLearningAssistantMessageHistory } from './api';
import { fetchLearningAssistantSummary } from './api';

jest.mock('@edx/frontend-platform/auth');

Expand All @@ -16,38 +16,45 @@ describe('API', () => {
jest.restoreAllMocks();
});

describe('fetchLearningAssistantMessageHistory()', () => {
const fakeCourseId = 'course-v1:edx+test+23';
const apiPayload = [
{
role: 'user',
content: 'Marco',
timestamp: '2024-11-04T19:05:07.403363Z',
describe('fetchLearningAssistantSummary()', () => {
const courseId = 'course-v1:edx+test+23';
const apiPayload = {
enabled: true,
message_history: [
{
role: 'user',
content: 'Marco',
timestamp: '2024-11-04T19:05:07.403363Z',
},
{
role: 'assistant',
content: 'Polo',
timestamp: '2024-11-04T19:05:21.357636Z',
},
],
audit_trial: {
start_date: '2024-12-02T14:59:16.148236Z',
expiration_date: '9999-12-16T14:59:16.148236Z',
},
{
role: 'assistant',
content: 'Polo',
timestamp: '2024-11-04T19:05:21.357636Z',
},
];
};

const fakeGet = jest.fn(async () => ({
const mockGet = jest.fn(async () => ({
data: apiPayload,
catch: () => {},
catch: () => { },
}));

beforeEach(() => {
auth.getAuthenticatedHttpClient = jest.fn(() => ({
get: fakeGet,
get: mockGet,
}));
});

it('should call the endpoint and process the results', async () => {
const response = await fetchLearningAssistantMessageHistory(fakeCourseId);
const response = await fetchLearningAssistantSummary(courseId);

expect(response).toEqual(apiPayload);
expect(fakeGet).toHaveBeenCalledTimes(1);
expect(fakeGet).toHaveBeenCalledWith(`${CHAT_RESPONSE_URL}/${fakeCourseId}/history`);
expect(mockGet).toHaveBeenCalledTimes(1);
expect(mockGet).toHaveBeenCalledWith(`${CHAT_RESPONSE_URL}/${courseId}/summary`);
});
});
});
2 changes: 0 additions & 2 deletions src/data/slice.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,6 @@ export const learningAssistantSlice = createSlice({
},
setAuditTrial: (state, { payload }) => {
state.auditTrial = payload;
// state.auditTrial.startDate = payload.start_date;
// state.auditTrial.expirationDate = payload.expiration_date;
},
},
});
Expand Down
83 changes: 34 additions & 49 deletions src/data/thunks.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ import { getAuthenticatedUser } from '@edx/frontend-platform/auth';
import trackChatBotMessageOptimizely from '../utils/optimizelyExperiment';
import {
fetchChatResponse,
fetchLearningAssistantMessageHistory,
fetchLearningAssistantEnabled,
fetchLearningAssistantAuditTrial,
fetchLearningAssistantSummary,
} from './api';
import {
setCurrentMessage,
Expand Down Expand Up @@ -79,33 +77,6 @@ export function getChatResponse(courseId, unitId, promptExperimentVariationKey =
};
}

export function getLearningAssistantMessageHistory(courseId) {
return async (dispatch) => {
dispatch(setApiIsLoading(true));

try {
const rawMessageList = await fetchLearningAssistantMessageHistory(courseId);

if (rawMessageList.length) {
const messageList = rawMessageList
.map(({ timestamp, ...msg }) => ({
...msg,
timestamp: new Date(timestamp), // Parse ISO time to Date()
}));

dispatch(setMessageList({ messageList }));

// If it has chat history, then we assume the user already aknowledged.
dispatch(setDisclosureAcknowledged(true));
}
} catch (e) {
// If fetching the messages fail, we just won't show it.
}

dispatch(setApiIsLoading(false));
};
}

export function updateCurrentMessage(content) {
return (dispatch) => {
dispatch(setCurrentMessage({ currentMessage: content }));
Expand All @@ -130,32 +101,46 @@ export function updateSidebarIsOpen(isOpen) {
};
}

export function getIsEnabled(courseId) {
export function getLearningAssistantSummary(courseId) {
return async (dispatch) => {
dispatch(setApiIsLoading(true));

try {
const data = await fetchLearningAssistantEnabled(courseId);
const data = await fetchLearningAssistantSummary(courseId);

// Enabled
dispatch(setIsEnabled(data.enabled));
} catch (error) {
dispatch(setApiError());
}
};
}

export function getAuditTrial(courseId) {
return async (dispatch) => {
try {
const data = await fetchLearningAssistantAuditTrial(courseId);
console.log("DATA:", data)
console.log("data.start_date:", data.start_date)
console.log("data.expiration_date:", data.expiration_date)
// If returned data is not empty
if (Object.keys(data).length !== 0) { // eslint-disable-line no-undef
console.log("SETTING!")
// TODO: FIGURE OUT how to sync the data from Michael's PR into this MFEs state...
dispatch(setAuditTrial(data));
// Message History
const rawMessageList = data.message_history;

// If returned message history data is not empty
if (rawMessageList.length) {
const messageList = rawMessageList
.map(({ timestamp, ...msg }) => ({
...msg,
// NOTE to self: can't store Date() objects in store: https://github.com/reduxjs/redux-toolkit/issues/456
timestamp: new Date(timestamp).toString(), // Parse ISO time to Date()
}));

dispatch(setMessageList({ messageList }));

// If it has chat history, then we assume the user already aknowledged.
dispatch(setDisclosureAcknowledged(true));
}

// Audit Trial
const auditTrial = data.audit_trial;

// If returned audit trial data is not empty
if (Object.keys(auditTrial).length !== 0) { // eslint-disable-line no-undef
dispatch(setAuditTrial(auditTrial));
}
} catch (error) {
// NOTE: When used to not show if fetching the messages failed
// But we do know since this endpoint is combined.
dispatch(setApiError());
}
dispatch(setApiIsLoading(false));
};
}
Loading

0 comments on commit 5c3b5cf

Please sign in to comment.