Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Demo button upgrades #564

Merged
merged 5 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export default function ProvidersSelect({ providers, practitioners, handleSubmit
practitionerIDToName[practitioner.id] = formatHumanName(practitioner.name[0]);
}
});

return (
<Autocomplete
id="providers"
Expand Down
47 changes: 38 additions & 9 deletions packages/telemed-ehr/app/src/helpers/create-sample-appointments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { DateTime } from 'luxon';
import { FhirClient, SearchParam } from '@zapehr/sdk';
import { PersonSex } from '../../../app/src/types/types';
import { Patient, Practitioner } from 'fhir/r4';
import { getSelectors } from '../shared/store/getSelectors';
import { useTrackingBoardStore } from '../telemed';
import { allLicensesForPractitioner, User } from 'ehr-utils';
import useOttehrUser from '../hooks/useOttehrUser';

type UserType = 'Patient' | 'Parent/Guardian';

Expand Down Expand Up @@ -43,6 +47,7 @@ export const createSampleAppointments = async (
fhirClient: FhirClient | undefined,
authToken: string,
phoneNumber: string,
user: User | undefined,
): Promise<void> => {
try {
if (!fhirClient) {
Expand All @@ -58,7 +63,7 @@ export const createSampleAppointments = async (

for (let i = 0; i < 10; i++) {
const visitService = appointmentTypes[i % 2];
const randomPatientInfo = await generateRandomPatientInfo(fhirClient, visitService, phoneNumber);
const randomPatientInfo = await generateRandomPatientInfo(fhirClient, visitService, user, phoneNumber);
const inputBody = JSON.stringify(randomPatientInfo);

const response = await fetch(`${intakeZambdaUrl}/zambda/${createAppointmentZambdaId}/execute`, {
Expand All @@ -83,18 +88,22 @@ export const createSampleAppointments = async (
const generateRandomPatientInfo = async (
fhirClient: FhirClient,
visitService: 'in-person' | 'telemedicine',
user: User | undefined,
phoneNumber?: string,
): Promise<CreateAppointmentParams> => {
const firstNames = ['Alice', 'Bob', 'Charlie', 'Diana', 'Ethan', 'Fatima', 'Gabriel', 'Hannah', 'Ibrahim', 'Jake'];
const lastNames = ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown', 'Clark', 'Davis', 'Elliott', 'Foster', 'Garcia'];
const sexes: PersonSex[] = [PersonSex.Male, PersonSex.Female, PersonSex.Intersex];

const searchParams: SearchParam[] = [{ name: 'status', value: 'active' }];
const availableLocations: any[] = await fhirClient?.searchResources({

const allOffices: any[] = await fhirClient?.searchResources({
resourceType: 'Location',
searchParams: searchParams,
searchParams: [{ name: '_count', value: '1000' }],
});

const activeOffices = allOffices.filter((item) => item.status === 'active');

const practitionersTemp: Practitioner[] = await fhirClient.searchResources({
resourceType: 'Practitioner',
searchParams: [
Expand All @@ -110,11 +119,26 @@ const generateRandomPatientInfo = async (
.minus({ years: 7 + Math.floor(Math.random() * 16) })
.toISODate();
const randomSex = sexes[Math.floor(Math.random() * sexes.length)];
const randomLocationIndex = Math.floor(Math.random() * availableLocations.length);
const randomLocationId = availableLocations[randomLocationIndex].id;
const randomLocationIndex = Math.floor(Math.random() * activeOffices.length);
const randomLocationId = activeOffices[randomLocationIndex].id;
const randomProviderId = practitionersTemp[Math.floor(Math.random() * practitionersTemp.length)].id;

const selectedLocationID = localStorage.getItem('selectedLocationID');
const selectedInPersonLocationID = localStorage.getItem('selectedLocationID');
const selectedState = localStorage.getItem('selectedState');

const availableStates =
user?.profileResource &&
allLicensesForPractitioner(user.profileResource).map((item) => {
return item.state;
});

const randomState = availableStates?.[Math.floor(Math.random() * availableStates.length)] || '';

const locationId = getLocationIdFromState(selectedState || randomState, allOffices);

const isLocationActive = activeOffices.some((office) => office.id === locationId);

const telemedLocationId = isLocationActive ? locationId : randomLocationId;

if (visitService === 'telemedicine') {
return {
Expand All @@ -127,14 +151,14 @@ const generateRandomPatientInfo = async (
email: randomEmail,
emailUser: 'Patient',
},
scheduleType: 'provider',
scheduleType: 'location',
visitType: 'now',
visitService: visitService,
providerID: randomProviderId,
timezone: 'UTC',
isDemo: true,
phoneNumber: phoneNumber,
locationID: randomLocationId,
locationID: telemedLocationId,
};
}

Expand All @@ -155,9 +179,14 @@ const generateRandomPatientInfo = async (
scheduleType: 'location',
visitType: 'now',
visitService: visitService,
locationID: selectedLocationID || randomLocationId,
locationID: selectedInPersonLocationID || randomLocationId,
timezone: 'UTC',
isDemo: true,
phoneNumber: phoneNumber,
};
};

const getLocationIdFromState = (state: string, allLocations: any[]): string | undefined => {
const location = allLocations.find((item) => item.address?.state === state);
return location?.id;
};
2 changes: 0 additions & 2 deletions packages/telemed-ehr/app/src/hooks/useOttehrUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,6 @@ export default function useOttehrUser(): OttehrUser | undefined {
if (resourceType && resourceId && resourceType === 'Practitioner') {
const practitioner = await client.readResource<Practitioner>({ resourceType, resourceId });
useOttehrUserStore.setState({ profile: practitioner });
console.log('practitioner', practitioner);
}
_profileLoadingState = LoadingState.idle;
} catch (e) {
Expand Down Expand Up @@ -347,7 +346,6 @@ const useGetProfile = () => {
if (resourceType && resourceId && resourceType === 'Practitioner') {
const practitioner = await fhirClient?.readResource<Practitioner>({ resourceType, resourceId });
useOttehrUserStore.setState({ profile: practitioner });
console.log('practitioner', practitioner);
}
} catch (e) {
console.error(`error fetching user's fhir profile: ${JSON.stringify(e)}`);
Expand Down
2 changes: 1 addition & 1 deletion packages/telemed-ehr/app/src/pages/Appointments.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ function AppointmentsBody(props: AppointmentsBodyProps): ReactElement {
updateAppointments={updateAppointments}
setEditingComment={setEditingComment}
/>
<CreateDemoVisits />
<CreateDemoVisits schedulePage="in-person" />
</>
</PageContainer>
</form>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ import { useAuth0 } from '@auth0/auth0-react';
import { otherColors } from '../../../CustomThemeProvider';
import { LoadingButton } from '@mui/lab';
import { Box } from '@mui/system';
import useOttehrUser from '../../../hooks/useOttehrUser';

const CreateDemoVisits = (): ReactElement => {
interface CreateDemoVisitsProps {
schedulePage?: 'telemedicine' | 'in-person';
}

const CreateDemoVisits = ({ schedulePage }: CreateDemoVisitsProps): ReactElement => {
const [phoneNumber, setPhoneNumber] = useState('');
const [inputError, setInputError] = useState(false);
const [loading, setLoading] = useState(false);
Expand All @@ -24,6 +29,7 @@ const CreateDemoVisits = (): ReactElement => {
});
const { fhirClient } = useApiClients();
const { getAccessTokenSilently } = useAuth0();
const user = useOttehrUser();

const handleCreateSampleAppointments = async (
event: React.MouseEvent<HTMLButtonElement> | React.FormEvent<HTMLFormElement>,
Expand All @@ -40,12 +46,13 @@ const CreateDemoVisits = (): ReactElement => {
setLoading(true);
setInputError(false);
const authToken = await getAccessTokenSilently();
const response = await createSampleAppointments(fhirClient, authToken, formattedPhoneNumber);
const response = await createSampleAppointments(fhirClient, authToken, formattedPhoneNumber, user);
setSnackbar({
open: true,
message: 'Appointments created successfully!',
severity: 'success',
});
return response;
} catch (error) {
setSnackbar({
open: true,
Expand Down Expand Up @@ -98,6 +105,10 @@ const CreateDemoVisits = (): ReactElement => {
<Typography variant="h6" color="primary.main">
Lack of test data? Create demo visits
</Typography>
{/* <Typography variant="body2" color="text.secondary">
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you want this comment here?

Please select {schedulePage === 'telemedicine' ? 'a state ' : 'an office '}
from above dropdown <br /> and enter a phone number to create visits for this user
</Typography> */}
<Typography variant="body2" color="text.secondary">
Please enter a phone number to create visits for this user
</Typography>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ export function StateSelect(): ReactElement {
const { availableStates, state } = getSelectors(useTrackingBoardStore, ['availableStates', 'state']);
const options = [EMPTY_STATE, ...availableStates.map((state) => ({ label: state, value: state }))];

const randomState = availableStates[Math.floor(Math.random() * availableStates.length)];

const handleStateChange = (_e: any, { value }: { label: string | null; value: string | null }): void => {
localStorage.setItem('selectedState', value || '');
useTrackingBoardStore.setState((prevState) => ({ ...prevState, state: value }));
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,10 @@ export const TrackingBoardFilters: FC<{ tab: ApptTab }> = (props) => {
const useDate = tab === ApptTab.complete;
const useUnsigned = tab === ApptTab['not-signed'];
const handleProviderChange = (_e: any, value: string[]): void => {
console.log(10, value);
setProviders(value);
useTrackingBoardStore.setState({ providers: value });
};
const handleGroupChange = (_e: any, value: string[]): void => {
console.log(10, value);
setGroups(value);
useTrackingBoardStore.setState({ groups: value });
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ export function TrackingBoardTable({ tab }: AppointmentTableProps): ReactElement
return {};
}
return filteredAppointments.reduce<Record<string, TelemedAppointmentInformation[]>>((accumulator, appointment) => {
if (appointment.location.locationID) {
if (!accumulator[appointment.location.locationID]) {
accumulator[appointment.location.locationID] = [];
if (appointment.location.state) {
if (!accumulator[appointment.location.state]) {
accumulator[appointment.location.state] = [];
}
accumulator[appointment.location.locationID].push(appointment);
accumulator[appointment.location.state].push(appointment);
return accumulator;
} else if (appointment.provider) {
if (!accumulator[appointment.provider.join(',')]) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export function TrackingBoardTabs(): ReactElement {
<TrackingBoardTable tab={value} />
</TabPanel>
</Paper>
<CreateDemoVisits />
<CreateDemoVisits schedulePage="telemedicine" />
</TabContext>
</Box>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export function TrackingBoardPage(): ReactElement {
useEffect(() => {
const availableStates =
user?.profileResource && allLicensesForPractitioner(user.profileResource).map((item) => item.state);
console.log(availableStates, 'availableStates');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you want this console log here?


if (availableStates) {
useTrackingBoardStore.setState({ availableStates });
Expand Down
2 changes: 2 additions & 0 deletions packages/telemed-ehr/app/src/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ export const AllStates = [

export type StateType = (typeof AllStates extends readonly (infer TElementType)[] ? TElementType : never)['value'];

export const AllStatesValues: StateType[] = AllStates.map(({ value }) => value);

export const AllStatesToNames: {
[value in StateType]: string;
} = {
Expand Down
4 changes: 0 additions & 4 deletions packages/telemed-ehr/zambdas/src/get-appointments/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,6 @@ export const index = async (input: ZambdaInput): Promise<APIGatewayProxyResult>
});
const [activeEncounters, searchResultsForSelectedDate] = await Promise.all([encounterSearch, appointmentSearch]);
console.timeEnd('get_active_encounters + get_appointment_data');
// console.log(searchResultsForSelectedDate);
// console.log(appointmentSearchParams);
// console.log(1, searchResultsForSelectedDate);
const encounterIds: string[] = [];

const tempAppointmentDates = activeEncounters
Expand Down Expand Up @@ -419,7 +416,6 @@ export const index = async (input: ZambdaInput): Promise<APIGatewayProxyResult>
console.time('structure_appointment_data');
let appointments: Appointment[] = [];
if (visitType?.length > 0) {
console.log(1, allAppointments.length);
appointments = allAppointments?.filter((appointment) => {
return visitType?.includes(appointment.appointmentType?.text || '');
});
Expand Down
1 change: 0 additions & 1 deletion packages/telemed-intake/zambdas/src/demo/example.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ export async function getUser(
await page.waitForTimeout(3000);
expect(await page.getByText('Code is invalid').isVisible()).toBeFalsy();
await page.waitForTimeout(500);
console.log(1, token);
return token;
}

Expand Down
9 changes: 0 additions & 9 deletions packages/telemed-intake/zambdas/src/get-schedule/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,6 @@ async function getSchedule(
currentDayTemp = currentDayTemp.plus({ days: 1 });
}
});
console.log(1, slots);
return {
message: 'Successful reply',
// reminder to fix item adress
Expand Down Expand Up @@ -397,13 +396,6 @@ export const distributeTimeSlots = (
currentAppointments: Appointment[],
slotLength: number,
): string[] => {
// console.log(1, startTime, capacity, openingTime, closingTime);
// const minutesToDistributeInHour = Math.min(
// 60,
// startTime.diff(openingTime, 'minutes').minutes,
// startTime.diff(closingTime, 'minutes').minutes
// );

// adjust startTime if minutes are not 00 to get an accurate minutesToDistributeInHour
const adjustedStart: DateTime = startTime.minute !== 0 ? startTime.minus({ minutes: startTime.minute }) : startTime;

Expand All @@ -430,7 +422,6 @@ export const distributeTimeSlots = (
const tempRoundedTime = tempTime.set({ minute: tempUpdatedRoundedMinute, second: 0, millisecond: 0 });
tempTime = tempTime.plus({ minutes: minutesPerSlot });
const timesSlotIndex = tempRoundedTime.toISO() || '';
// console.log(1, tempRoundedTime.toISO());

// Appointments are bookable an hour away from the current time
if (tempRoundedTime < DateTime.now().setZone('UTC').plus({ hours: 1 })) {
Expand Down
2 changes: 0 additions & 2 deletions packages/urgent-care-intake/app/src/api/zapehrApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,6 @@ class API {
if (GET_PRESIGNED_FILE_URL == null || REACT_APP_IS_LOCAL == null) {
throw new Error('get presigned file url environment variable could not be loaded');
}
console.log(1);
const response = await zambdaClient?.invokePublicZambda({
zambdaId: GET_PRESIGNED_FILE_URL,
payload: {
Expand All @@ -320,7 +319,6 @@ class API {
fileFormat,
},
});
console.log(1);

const jsonToUse = chooseJson(response, REACT_APP_IS_LOCAL);
return jsonToUse;
Expand Down
2 changes: 0 additions & 2 deletions packages/urgent-care-intake/zambdas/src/shared/dateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ export const distributeTimeSlots = (
closingTime: DateTime,
currentAppointments: Appointment[],
): string[] => {
// console.log(1, startTime, capacity, openingTime, closingTime);
const ROUND_MINUTES = 15;

// const minutesToDistributeInHour = Math.min(
Expand Down Expand Up @@ -114,7 +113,6 @@ export const distributeTimeSlots = (
const tempRoundedTime = tempTime.set({ minute: tempUpdatedRoundedMinute, second: 0, millisecond: 0 });
tempTime = tempTime.plus({ minutes: minutesPerSlot });
const timesSlotIndex = tempRoundedTime.toISO() || '';
// console.log(1, tempRoundedTime.toISO());

// Appointments are bookable an hour away from the current time
if (tempRoundedTime < DateTime.now().setZone('UTC').plus({ hours: 1 })) {
Expand Down
Loading