Skip to content

Commit

Permalink
Merge pull request #588 from masslight/revert-564-aykhan/demo-button-…
Browse files Browse the repository at this point in the history
…upgrades

Revert "Demo button upgrades"
  • Loading branch information
AykhanAhmadli authored Nov 14, 2024
2 parents 01243d6 + f9ab76a commit 5ce62dc
Show file tree
Hide file tree
Showing 15 changed files with 39 additions and 59 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export default function ProvidersSelect({ providers, practitioners, handleSubmit
practitionerIDToName[practitioner.id] = formatHumanName(practitioner.name[0]);
}
});

return (
<Autocomplete
id="providers"
Expand Down
47 changes: 9 additions & 38 deletions packages/telemed-ehr/app/src/helpers/create-sample-appointments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@ 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 @@ -47,7 +43,6 @@ export const createSampleAppointments = async (
fhirClient: FhirClient | undefined,
authToken: string,
phoneNumber: string,
user: User | undefined,
): Promise<void> => {
try {
if (!fhirClient) {
Expand All @@ -63,7 +58,7 @@ export const createSampleAppointments = async (

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

const response = await fetch(`${intakeZambdaUrl}/zambda/${createAppointmentZambdaId}/execute`, {
Expand All @@ -88,22 +83,18 @@ 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 allOffices: any[] = await fhirClient?.searchResources({
const availableLocations: any[] = await fhirClient?.searchResources({
resourceType: 'Location',
searchParams: [{ name: '_count', value: '1000' }],
searchParams: searchParams,
});

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

const practitionersTemp: Practitioner[] = await fhirClient.searchResources({
resourceType: 'Practitioner',
searchParams: [
Expand All @@ -119,26 +110,11 @@ 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() * activeOffices.length);
const randomLocationId = activeOffices[randomLocationIndex].id;
const randomLocationIndex = Math.floor(Math.random() * availableLocations.length);
const randomLocationId = availableLocations[randomLocationIndex].id;
const randomProviderId = practitionersTemp[Math.floor(Math.random() * practitionersTemp.length)].id;

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;
const selectedLocationID = localStorage.getItem('selectedLocationID');

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

Expand All @@ -179,14 +155,9 @@ const generateRandomPatientInfo = async (
scheduleType: 'location',
visitType: 'now',
visitService: visitService,
locationID: selectedInPersonLocationID || randomLocationId,
locationID: selectedLocationID || 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: 2 additions & 0 deletions packages/telemed-ehr/app/src/hooks/useOttehrUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ 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 @@ -346,6 +347,7 @@ 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 schedulePage="in-person" />
<CreateDemoVisits />
</>
</PageContainer>
</form>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,8 @@ 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';

interface CreateDemoVisitsProps {
schedulePage?: 'telemedicine' | 'in-person';
}

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

const handleCreateSampleAppointments = async (
event: React.MouseEvent<HTMLButtonElement> | React.FormEvent<HTMLFormElement>,
Expand All @@ -46,13 +40,12 @@ const CreateDemoVisits = ({ schedulePage }: CreateDemoVisitsProps): ReactElement
setLoading(true);
setInputError(false);
const authToken = await getAccessTokenSilently();
const response = await createSampleAppointments(fhirClient, authToken, formattedPhoneNumber, user);
const response = await createSampleAppointments(fhirClient, authToken, formattedPhoneNumber);
setSnackbar({
open: true,
message: 'Appointments created successfully!',
severity: 'success',
});
return response;
} catch (error) {
setSnackbar({
open: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ 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,10 +85,12 @@ 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.state) {
if (!accumulator[appointment.location.state]) {
accumulator[appointment.location.state] = [];
if (appointment.location.locationID) {
if (!accumulator[appointment.location.locationID]) {
accumulator[appointment.location.locationID] = [];
}
accumulator[appointment.location.state].push(appointment);
accumulator[appointment.location.locationID].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 schedulePage="telemedicine" />
<CreateDemoVisits />
</TabContext>
</Box>
);
Expand Down
2 changes: 0 additions & 2 deletions packages/telemed-ehr/app/src/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,6 @@ 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: 4 additions & 0 deletions packages/telemed-ehr/zambdas/src/get-appointments/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,9 @@ 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 @@ -416,6 +419,7 @@ 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: 1 addition & 0 deletions packages/telemed-intake/zambdas/src/demo/example.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ 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: 9 additions & 0 deletions packages/telemed-intake/zambdas/src/get-schedule/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,7 @@ 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 @@ -396,6 +397,13 @@ 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 @@ -422,6 +430,7 @@ 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: 2 additions & 0 deletions packages/urgent-care-intake/app/src/api/zapehrApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ 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 @@ -319,6 +320,7 @@ class API {
fileFormat,
},
});
console.log(1);

const jsonToUse = chooseJson(response, REACT_APP_IS_LOCAL);
return jsonToUse;
Expand Down
2 changes: 2 additions & 0 deletions packages/urgent-care-intake/zambdas/src/shared/dateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ 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 @@ -113,6 +114,7 @@ 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

0 comments on commit 5ce62dc

Please sign in to comment.