Skip to content

Commit

Permalink
MPDX-8351 Add UseLocalizedConstants() hook (#1145)
Browse files Browse the repository at this point in the history
* Change PGA filter to use lowercase contact statuses

* Consolidate converting old Cru statuses

* Move getContactStatusesByPhase

* Add useLocalizedContacts() hook and replace getLocalizedStatus

* Add useAPIConstants hook to the test setup and remove mocks from tests

* Add useCallback

* Refetch constants when the language changes

* Add check before refetching and remove saving to local storage in preferences

* update useLocalStorage
  • Loading branch information
caleballdrin authored Oct 21, 2024
1 parent 86d678b commit 1180b32
Show file tree
Hide file tree
Showing 82 changed files with 547 additions and 1,014 deletions.
14 changes: 14 additions & 0 deletions __tests__/util/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,17 @@ import 'isomorphic-fetch';
import { Settings } from 'luxon';
import { type useSession } from 'next-auth/react';
import { session } from '__tests__/fixtures/session';
import {
LoadConstantsDocument,
LoadConstantsQuery,
} from 'src/components/Constants/LoadConstants.generated';
import { loadConstantsMockData } from 'src/components/Constants/LoadConstantsMock';
import { useApiConstants } from 'src/components/Constants/UseApiConstants';
import { toHaveGraphqlOperation } from '../extensions/toHaveGraphqlOperation';
import { gqlMock } from './graphqlMocking';
import matchMediaMock from './matchMediaMock';

jest.mock('src/components/Constants/UseApiConstants');
jest.mock('next-auth/react', () => {
return {
getSession: jest.fn().mockResolvedValue(session),
Expand All @@ -21,6 +29,12 @@ jest.mock('next-auth/react', () => {
};
});

(useApiConstants as jest.MockedFn<typeof useApiConstants>).mockReturnValue(
gqlMock<LoadConstantsQuery>(LoadConstantsDocument, {
mocks: loadConstantsMockData,
}).constant,
);

expect.extend({
toHaveGraphqlOperation,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ const StickyBox = styled(Box)(() => ({
const ContactFlowSetupPage: React.FC = () => {
const { t } = useTranslation();
const accountListId = useAccountListId();
const { statusMap, contactStatuses } = useContactPartnershipStatuses();
const { statusMap, getContactStatusesByPhase } =
useContactPartnershipStatuses();
const { enqueueSnackbar } = useSnackbar();
const [flowOptions, setFlowOptions] = useState<FlowOption[]>([]);
const resetColumnsMessage = t(
Expand All @@ -47,7 +48,7 @@ const ContactFlowSetupPage: React.FC = () => {

useEffect(() => {
if (!userOptions.length) {
setFlowOptions(getDefaultFlowOptions(t, contactStatuses));
setFlowOptions(getDefaultFlowOptions(t, getContactStatusesByPhase));
} else {
setFlowOptions(userOptions);
}
Expand Down
10 changes: 0 additions & 10 deletions pages/accountLists/[accountListId]/tools/import/csv.page.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,18 @@ import { ThemeProvider } from '@mui/material/styles';
import { render, waitFor } from '@testing-library/react';
import TestRouter from '__tests__/util/TestRouter';
import TestWrapper from '__tests__/util/TestWrapper';
import { useApiConstants } from 'src/components/Constants/UseApiConstants';
import { CsvImportViewStepEnum } from 'src/components/Tool/Import/Csv/CsvImportContext';
import { get } from 'src/components/Tool/Import/Csv/csvImportService';
import { useAccountListId } from 'src/hooks/useAccountListId';
import theme from 'src/theme';
import CsvHome from './csv.page';

jest.mock('src/hooks/useAccountListId');
jest.mock('src/components/Constants/UseApiConstants');
jest.mock('src/components/Tool/Import/Csv/csvImportService');

const accountListId = 'accountListId';
const csvFileId = 'csvFileId';

const constants = {
sendAppeals: [
{ id: true, value: 'Yes' },
{ id: false, value: 'No' },
],
};

const buildRouter = (tab) => {
return {
isReady: true,
Expand All @@ -49,7 +40,6 @@ const renderCsvHome = (router) =>
describe('CSV wrapper page', () => {
beforeEach(() => {
(useAccountListId as jest.Mock).mockReturnValue(accountListId);
(useApiConstants as jest.Mock).mockReturnValue(constants);
(get as jest.Mock).mockReturnValue(Promise.resolve({ id: 'from-get' }));
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { SnackbarProvider } from 'notistack';
import { I18nextProvider } from 'react-i18next';
import TestRouter from '__tests__/util/TestRouter';
import { GqlMockedProvider } from '__tests__/util/graphqlMocking';
import { loadConstantsMockData } from 'src/components/Constants/LoadConstantsMock';
import { GetContactDuplicatesQuery } from 'src/components/Tool/MergeContacts/GetContactDuplicates.generated';
import { getContactDuplicatesMocks } from 'src/components/Tool/MergeContacts/MergeContactsMock';
import i18n from 'src/lib/i18n';
Expand Down Expand Up @@ -48,7 +47,6 @@ const Components = () => (
}>
mocks={{
...getContactDuplicatesMocks,
LoadConstants: loadConstantsMockData,
}}
>
<I18nextProvider i18n={i18n}>
Expand Down
57 changes: 1 addition & 56 deletions pages/api/Schema/reports/fourteenMonth/datahandler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { convertStatus } from 'src/utils/functions/convertContactStatus';
import {
FourteenMonthReport,
FourteenMonthReportCurrencyType,
StatusEnum,
} from '../../../graphql-rest.page.generated';

export interface FourteenMonthReportResponse {
Expand Down Expand Up @@ -69,61 +69,6 @@ export interface FourteenMonthReportResponse {
};
}

// Convert a status string into a StatusEnum
const convertStatus = (
status: string | null | undefined,
): StatusEnum | null => {
// Statuses will be lowercase and underscored (i.e. "never_contacted") after task phases lands
// Statuses will be sentence case with spaces (i.e. "Never Contacted") before task phases lands
switch (status) {
case 'never_contacted':
case 'Never Contacted':
return StatusEnum.NeverContacted;
case 'ask_in_future':
case 'Ask in Future':
return StatusEnum.AskInFuture;
case 'cultivate_relationship':
case 'Cultivate Relationship':
return StatusEnum.CultivateRelationship;
case 'contact_for_appointment':
case 'Contact for Appointment':
return StatusEnum.ContactForAppointment;
case 'appointment_scheduled':
case 'Appointment Scheduled':
return StatusEnum.AppointmentScheduled;
case 'call_for_decision':
case 'Call for Decision':
return StatusEnum.CallForDecision;
case 'partner_financial':
case 'Partner - Financial':
return StatusEnum.PartnerFinancial;
case 'partner_special':
case 'Partner - Special':
return StatusEnum.PartnerSpecial;
case 'partner_pray':
case 'Partner - Pray':
return StatusEnum.PartnerPray;
case 'not_interested':
case 'Not Interested':
return StatusEnum.NotInterested;
case 'unresponsive':
case 'Unresponsive':
return StatusEnum.Unresponsive;
case 'never_ask':
case 'Never Ask':
return StatusEnum.NeverAsk;
case 'research_abandoned':
case 'Research Abandoned':
return StatusEnum.ResearchAbandoned;
case 'expired_referral':
case 'Expired Referral':
return StatusEnum.ExpiredReferral;

default:
return null;
}
};

export const mapFourteenMonthReport = (
data: FourteenMonthReportResponse,
currencyType: FourteenMonthReportCurrencyType,
Expand Down
13 changes: 1 addition & 12 deletions pages/api/graphql-rest.page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import {
MergeContactsInput,
MergePeopleBulkInput,
} from 'src/graphql/types.generated';
import i18n from 'src/lib/i18n';
import { getLocalizedContactStatus } from '../../src/utils/functions/getLocalizedContactStatus';
import schema from './Schema';
import { getAccountListAnalytics } from './Schema/AccountListAnalytics/dataHandler';
import { getAccountListCoaches } from './Schema/AccountListCoaches/dataHandler';
Expand Down Expand Up @@ -615,16 +613,7 @@ class MpdxRestApi extends RESTDataSource {
// Status
case 'status':
filters[snakedKey] = (value as ContactFilterStatusEnum[])
.map((status) => {
const translated = getLocalizedContactStatus(i18n.t, status);
if (!translated) {
throw new Error(
`Unrecognized ContactFilterStatusEnum value ${value}`,
);
}

return translated;
})
.map((status) => status.toLowerCase())
.join(',');
break;

Expand Down
16 changes: 6 additions & 10 deletions src/components/Coaching/CoachingDetail/Activity/Activity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ import {
StatusEnum,
} from 'src/graphql/types.generated';
import { useLocale } from 'src/hooks/useLocale';
import { useLocalizedConstants } from 'src/hooks/useLocalizedConstants';
import {
currencyFormat,
dateFormat,
dateFormatWithoutYear,
} from 'src/lib/intlFormat';
import { getLocalizedContactStatus } from 'src/utils/functions/getLocalizedContactStatus';
import { MultilineSkeleton } from '../../../Shared/MultilineSkeleton';
import { AccountListTypeEnum, CoachingPeriodEnum } from '../CoachingDetail';
import { CoachingLink } from '../CoachingLink';
Expand Down Expand Up @@ -177,6 +177,7 @@ export const Activity: React.FC<ActivityProps> = ({
primaryAppeal,
}) => {
const { t } = useTranslation();
const { getLocalizedContactStatus } = useLocalizedConstants();
const locale = useLocale();

const periodDuration =
Expand Down Expand Up @@ -288,7 +289,7 @@ export const Activity: React.FC<ActivityProps> = ({
{data?.accountListAnalytics.contactsByStatus.neverContacted}
</StatsText>
<StatsColumnTitle>
{getLocalizedContactStatus(t, StatusEnum.NeverContacted)}
{getLocalizedContactStatus(StatusEnum.NeverContacted)}
</StatsColumnTitle>
</CoachingLink>
</StatsColumn>
Expand All @@ -303,7 +304,7 @@ export const Activity: React.FC<ActivityProps> = ({
{data?.accountListAnalytics.contactsByStatus.future}
</StatsText>
<StatsColumnTitle>
{getLocalizedContactStatus(t, StatusEnum.AskInFuture)}
{getLocalizedContactStatus(StatusEnum.AskInFuture)}
</StatsColumnTitle>
</CoachingLink>
</StatsColumn>
Expand All @@ -319,7 +320,6 @@ export const Activity: React.FC<ActivityProps> = ({
</StatsText>
<StatsColumnTitle>
{getLocalizedContactStatus(
t,
StatusEnum.CultivateRelationship,
)}
</StatsColumnTitle>
Expand Down Expand Up @@ -366,7 +366,6 @@ export const Activity: React.FC<ActivityProps> = ({
</StatsText>
<StatsColumnTitle>
{getLocalizedContactStatus(
t,
StatusEnum.ContactForAppointment,
)}
</StatsColumnTitle>
Expand All @@ -386,10 +385,7 @@ export const Activity: React.FC<ActivityProps> = ({
}
</StatsText>
<StatsColumnTitle>
{getLocalizedContactStatus(
t,
StatusEnum.AppointmentScheduled,
)}
{getLocalizedContactStatus(StatusEnum.AppointmentScheduled)}
</StatsColumnTitle>
</CoachingLink>
</StatsColumn>
Expand All @@ -407,7 +403,7 @@ export const Activity: React.FC<ActivityProps> = ({
}
</StatsText>
<StatsColumnTitle>
{getLocalizedContactStatus(t, StatusEnum.CallForDecision)}
{getLocalizedContactStatus(StatusEnum.CallForDecision)}
</StatsColumnTitle>
</CoachingLink>
</StatsColumn>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { render, waitFor } from '@testing-library/react';
import { GqlMockedProvider } from '__tests__/util/graphqlMocking';
import { loadConstantsMockData } from 'src/components/Constants/LoadConstantsMock';
import { CoachingPeriodEnum } from '../CoachingDetail';
import { levelOfEffortMocks } from '../coachingMocks';
import { LevelOfEffort } from './LevelOfEffort';
Expand All @@ -13,7 +12,6 @@ describe('LevelOfEffort', () => {
<GqlMockedProvider
mocks={{
...levelOfEffortMocks,
LoadConstants: loadConstantsMockData,
}}
>
<LevelOfEffort
Expand Down Expand Up @@ -117,7 +115,7 @@ describe('LevelOfEffort', () => {
);

await waitFor(() =>
expect(mutationSpy.mock.calls[1][0].operation.variables).toMatchObject({
expect(mutationSpy.mock.calls[0][0].operation.variables).toMatchObject({
range: '4w',
}),
);
Expand All @@ -134,7 +132,7 @@ describe('LevelOfEffort', () => {
);

await waitFor(() =>
expect(mutationSpy.mock.calls[1][0].operation.variables).toMatchObject({
expect(mutationSpy.mock.calls[0][0].operation.variables).toMatchObject({
range: '4m',
}),
);
Expand Down
9 changes: 9 additions & 0 deletions src/components/Constants/LoadConstants.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ query LoadConstants {
# }
pledgeCurrency {
id
key
codeSymbolString
name
code
value
symbol
}
pledgeFrequency {
Expand Down Expand Up @@ -83,4 +85,11 @@ query LoadConstants {
tasks
}
}
user {
id
preferences {
id
locale
}
}
}
Loading

0 comments on commit 1180b32

Please sign in to comment.