Skip to content

Commit

Permalink
[To Main] Fix for issue of null appearing in public URLs (#2529)
Browse files Browse the repository at this point in the history
* Fix for issue of null appearing in public URLs

* updating change log

* Adding comments to HOC
  • Loading branch information
VineetBala-AOT authored May 31, 2024
1 parent 2b853c6 commit 0e58785
Show file tree
Hide file tree
Showing 18 changed files with 130 additions and 65 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.MD
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
## May 29, 2024

- **Bugfix** Null in the public URL [🎟️ DESENG-625](https://apps.itsm.gov.bc.ca/jira/browse/DESENG-625)
- Removed language from URLs other than engagement/survey links
- Fixed the issue of null appearing in public URLs

- **Feature** MET split out tenant specific variables from locale files [🎟️ DESENG-612](https://apps.itsm.gov.bc.ca/jira/browse/DESENG-612)
- Replaced tenant based values with data from tenant detail API

Expand Down
16 changes: 8 additions & 8 deletions met-api/sample.env
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,15 @@ ACCESS_REQUEST_EMAIL_ADDRESS="[email protected]"

# Site paths for creating emails from templates
SITE_URL=http://localhost:3000
SURVEY_PATH=/{lang}/surveys/submit/{survey_id}/{token}
SURVEY_PATH=/surveys/submit/{survey_id}/{token}/{lang}
USER_MANAGEMENT_PATH=/usermanagement
SUBMISSION_PATH=/{lang}/engagements/{engagement_id}/edit/{token}
SUBSCRIBE_PATH=/{lang}/engagements/{engagement_id}/subscribe/{token}
UNSUBSCRIBE_PATH=/{lang}/engagements/{engagement_id}/unsubscribe/{participant_id}
ENGAGEMENT_PATH=/{lang}/engagements/{engagement_id}/view
ENGAGEMENT_PATH_SLUG=/{lang}/{slug}
ENGAGEMENT_DASHBOARD_PATH=/{lang}/engagements/{engagement_id}/comments/public
ENGAGEMENT_DASHBOARD_PATH_SLUG=/{lang}/{slug}/comments/public
SUBMISSION_PATH=/engagements/{engagement_id}/edit/{token}/{lang}
SUBSCRIBE_PATH=/engagements/{engagement_id}/subscribe/{token}/{lang}
UNSUBSCRIBE_PATH=/engagements/{engagement_id}/unsubscribe/{participant_id}/{lang}
ENGAGEMENT_PATH=/engagements/{engagement_id}/view/{lang}
ENGAGEMENT_PATH_SLUG=/{slug}/{lang}
ENGAGEMENT_DASHBOARD_PATH=/engagements/{engagement_id}/comments/public/{lang}
ENGAGEMENT_DASHBOARD_PATH_SLUG=/{slug}/comments/public/{lang}

#CDogs API settings
CDOGS_ACCESS_TOKEN=
Expand Down
16 changes: 8 additions & 8 deletions met-api/src/met_api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,25 +239,25 @@ def SQLALCHEMY_DATABASE_URI(self) -> str:
# construct the links in the emails sent to users.
PATH_CONFIG = PATHS = {
'SITE': os.getenv('SITE_URL'),
'SURVEY': os.getenv('SURVEY_PATH', '/{lang}/surveys/submit/{survey_id}/{token}'),
'SURVEY': os.getenv('SURVEY_PATH', '/surveys/submit/{survey_id}/{token}/{lang}'),
'USER_MANAGEMENT': os.getenv('USER_MANAGEMENT_PATH', '/usermanagement'),
'SUBMISSION': os.getenv(
'SUBMISSION_PATH', '/{lang}/engagements/{engagement_id}/edit/{token}'
'SUBMISSION_PATH', '/engagements/{engagement_id}/edit/{token}/{lang}'
),
'SUBSCRIBE': os.getenv(
'SUBSCRIBE_PATH', '/{lang}/engagements/{engagement_id}/subscribe/{token}'
'SUBSCRIBE_PATH', '/engagements/{engagement_id}/subscribe/{token}/{lang}'
),
'UNSUBSCRIBE': os.getenv(
'UNSUBSCRIBE_PATH', '/{lang}/engagements/{engagement_id}/unsubscribe/{participant_id}'
'UNSUBSCRIBE_PATH', '/engagements/{engagement_id}/unsubscribe/{participant_id}/{lang}'
),
'ENGAGEMENT': {
'VIEW': os.getenv('ENGAGEMENT_PATH', '/{lang}/engagements/{engagement_id}/view'),
'SLUG': os.getenv('ENGAGEMENT_PATH_SLUG', '/{lang}/{slug}'),
'VIEW': os.getenv('ENGAGEMENT_PATH', '/engagements/{engagement_id}/view/{lang}'),
'SLUG': os.getenv('ENGAGEMENT_PATH_SLUG', '/{slug}/{lang}'),
'DASHBOARD': os.getenv(
'ENGAGEMENT_DASHBOARD_PATH', '/{lang}/engagements/{engagement_id}/comments/public'
'ENGAGEMENT_DASHBOARD_PATH', '/engagements/{engagement_id}/comments/public/{lang}'
),
'DASHBOARD_SLUG': os.getenv(
'ENGAGEMENT_DASHBOARD_PATH_SLUG', '/{lang}/{slug}/comments/public'
'ENGAGEMENT_DASHBOARD_PATH_SLUG', '/{slug}/comments/public/{lang}'
),
}
}
Expand Down
23 changes: 9 additions & 14 deletions met-web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,25 +94,22 @@ const App = () => {
}

const defaultTenant = AppConfig.tenant.defaultTenant;
const defaultLanguage = AppConfig.language.defaultLanguageId;

sessionStorage.setItem('languageId', AppConfig.language.defaultLanguageId);
// Determine the appropriate URL to redirect
const redirectToDefaultUrl = (base: string, includeLanguage = true) => {
const languageSegment = includeLanguage ? `/${defaultLanguage}` : '/home';
window.location.replace(`/${base}${languageSegment}`);
const redirectToDefaultUrl = (base: string, isAuthenticated: boolean) => {
const redirectUrl = `/${base}${isAuthenticated ? '/home' : ''}`;
window.location.replace(redirectUrl);
};

const shouldIncludeLanguage = !isAuthenticated;

if (basename) {
fetchTenant(basename);
// if language or admin dashboard url not set
if (pathSegments.length < 2) {
redirectToDefaultUrl(basename, shouldIncludeLanguage);
// if admin dashboard url not set
if (pathSegments.length < 2 && isAuthenticated) {
redirectToDefaultUrl(basename, isAuthenticated);
}
} else if (defaultTenant) {
fetchTenant(defaultTenant);
redirectToDefaultUrl(defaultTenant, shouldIncludeLanguage);
redirectToDefaultUrl(defaultTenant, isAuthenticated);
} else {
dispatch(loadingTenant(false));
}
Expand Down Expand Up @@ -213,9 +210,7 @@ const App = () => {
<Notification />
<NotificationModal />
<PublicHeader />
<Routes>
<Route path="/:lang/*" element={<UnauthenticatedRoutes />} />
</Routes>
<UnauthenticatedRoutes />
<FeedbackModal />
<Footer />
</Router>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export const CommentsBlock: React.FC<CommentsBlockProps> = ({ dashboardType }) =
if (isLoggedIn) {
navigate(`${basePath}/dashboard/public`);
} else {
navigate(`${languagePath}${basePath}/dashboard/public`);
navigate(`${basePath}/dashboard/public${languagePath}`);
}
};

Expand All @@ -67,7 +67,7 @@ export const CommentsBlock: React.FC<CommentsBlockProps> = ({ dashboardType }) =
<>
<Grid item xs={12} container direction="row" justifyContent="flex-end" paddingBottom={'8px'}>
<Link
to={isLoggedIn ? `${basePath}/view` : `${languagePath}${basePath}/view`}
to={isLoggedIn ? `${basePath}/view` : `${basePath}/view${languagePath}`}
style={{ color: '#1A5A96' }}
>
{translate('commentDashboard.block.link.0') +
Expand Down
2 changes: 1 addition & 1 deletion met-web/src/components/engagement/view/SurveyBlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ const SurveyBlock = ({ startSurvey }: SurveyBlockProps) => {
isLoggedIn
? navigate(`/engagements/${savedEngagement.id}/dashboard/public`)
: navigate(
`${languagePath}/engagements/${savedEngagement.id}/dashboard/public`,
`/engagements/${savedEngagement.id}/dashboard/public/${languagePath}`,
);
}}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const FormSignUpSection = ({ subscribeOption, widget }: { subscribeOption: Subsc
const languagePath = `${sessionStorage.getItem('languageId')}`;
const handleNavigate = () => {
const baseUrl = getBaseUrl();
window.open(`${baseUrl}/${languagePath}/engagements/${widget.engagement_id}/cacform/${widget.id}`, '_blank');
window.open(`${baseUrl}/engagements/${widget.engagement_id}/cacform/${widget.id}/${languagePath}`, '_blank');
};
return (
<Grid spacing={2} container item xs={12}>
Expand Down
2 changes: 1 addition & 1 deletion met-web/src/components/landing/EngagementTile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const EngagementTile = ({ passedEngagement, engagementId }: EngagementTileProps)
const dateFormat = 'MMM DD, YYYY';
const languagePath = `/${sessionStorage.getItem('languageId')}`;
const engagementPath = `/${slug}`;
const engagementUrl = `${getBaseUrl()}${languagePath}${engagementPath}`;
const engagementUrl = `${getBaseUrl()}${engagementPath}${languagePath}`;

const loadEngagement = async () => {
if (passedEngagement) {
Expand Down
3 changes: 1 addition & 2 deletions met-web/src/components/layout/Footer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { IconButton, Link } from 'components/common/Input';

const Footer = () => {
const baseURL = getBaseUrl();
const LanguageId = sessionStorage.getItem('languageId');
const { t: translate } = useAppTranslation();
const isLoggedIn = useAppSelector((state) => state.user.authentication.authenticated);

Expand Down Expand Up @@ -79,7 +78,7 @@ const Footer = () => {
<MetLabel>{translate('footer.moreInfo')}</MetLabel>
</Grid>
<Grid item xs={6}>
<Link to={isLoggedIn ? `/home` : `/${LanguageId}`} color={Palette.text.primary}>
<Link to={isLoggedIn ? `/home` : `/`} color={Palette.text.primary}>
{translate('footer.home')}
</Link>
</Grid>
Expand Down
7 changes: 3 additions & 4 deletions met-web/src/components/layout/Header/PublicHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import { TenantState } from 'reduxSlices/tenantSlice';

const PublicHeader = () => {
const isLoggedIn = useAppSelector((state) => state.user.authentication.authenticated);
const language = sessionStorage.getItem('languageId');
const [imageError, setImageError] = useState(false);
const navigate = useNavigate();
const { t: translate } = useAppTranslation();
Expand Down Expand Up @@ -56,7 +55,7 @@ const PublicHeader = () => {
cursor: 'pointer',
}}
onClick={() => {
navigate(`/${language}`);
navigate(`/`);
}}
onError={(_e) => {
setImageError(true);
Expand All @@ -74,15 +73,15 @@ const PublicHeader = () => {
cursor: 'pointer',
}}
onClick={() => {
navigate(`/${language}`);
navigate(`/`);
}}
alt={translate('common.defaultBCText')}
/>
</When>
<HeaderTitleOld
sx={{ flexGrow: 1, cursor: 'pointer' }}
onClick={() => {
navigate(`/${language}`);
navigate(`/`);
}}
>
{headerTitle}
Expand Down
4 changes: 2 additions & 2 deletions met-web/src/components/publicDashboard/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const Dashboard = () => {
if (isLoggedIn) {
navigate(`${basePath}/comments/${dashboardType}`);
} else {
navigate(`${languagePath}${basePath}/comments/${dashboardType}`);
navigate(`${basePath}/comments/${dashboardType}${languagePath}`);
}
};

Expand Down Expand Up @@ -83,7 +83,7 @@ const Dashboard = () => {
<Grid container item xs={12} flexDirection="column">
<Grid item xs={12} container justifyContent="flex-end" paddingBottom={'8px'}>
<Link
to={isLoggedIn ? `${basePath}/view` : `${languagePath}${basePath}/view`}
to={isLoggedIn ? `${basePath}/view` : `${basePath}/view${languagePath}`}
data-testid="link-container"
>
{translate('dashboard.link.0') + engagement.name + translate('dashboard.link.1')}
Expand Down
2 changes: 1 addition & 1 deletion met-web/src/components/survey/edit/FormWrapped.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const FormWrapped = () => {
const { isTokenValid, isLoading, savedEngagement, submission } = useContext(ActionContext);
const navigate = useNavigate();
const languagePath = `/${sessionStorage.getItem('languageId')}`;
const engagementPath = slug ? `${languagePath}/${slug}` : `${languagePath}/engagements/${savedEngagement?.id}/view`;
const engagementPath = slug ? `${slug}/${languagePath}` : `engagements/${savedEngagement?.id}/view/${languagePath}`;

if (isLoading || !savedEngagement) {
return <Skeleton variant="rectangular" width="100%" height="38em" />;
Expand Down
2 changes: 1 addition & 1 deletion met-web/src/components/survey/submit/ActionContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export const ActionProvider = ({ children }: { children: JSX.Element }) => {
text: translate('surveySubmit.surveySubmitNotification.success'),
}),
);
navigate(`${languagePath}/${slug}`, {
navigate(`/${slug}/${languagePath}`, {
state: {
open: true,
},
Expand Down
4 changes: 2 additions & 2 deletions met-web/src/components/survey/submit/SurveySubmitWrapped.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ const SurveySubmitWrapped = () => {
<When condition={isTokenValid}>
<SurveyForm
handleClose={() => {
navigate(`${languagePath}/${slug}`);
navigate(`/${slug}/${languagePath}`);
}}
/>
</When>
<InvalidTokenModal
open={!isTokenValid && Boolean(savedSurvey.engagement)}
handleClose={() => {
navigate(`${languagePath}/${slug}`);
navigate(`/${slug}/${languagePath}`);
}}
/>
</MetPaper>
Expand Down
53 changes: 53 additions & 0 deletions met-web/src/routes/LanguageParam.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import React, { useEffect, ComponentType, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useAppSelector } from '../hooks';
import { LanguageState } from 'reduxSlices/languageSlice';

interface RouteParams {
[key: string]: string | undefined;
engagementId?: string;
slug?: string;
subscriptionStatus?: string;
scriptionKey?: string;
dashboardType?: string;
token?: string;
widgetId?: string;
}

/**
* Higher-Order Component (HOC) to handle language parameter in the URL.
* This HOC checks if the current URL includes the language code and adds it if necessary.
* It uses the language state and available translations from the context to determine if the language code should be added.
* @param Component - The component to be wrapped by this HOC.
* @returns A new component with language parameter handling.
*/
const withLanguageParam = <P extends object>(Component: ComponentType<P>) => {
return (props: P) => {
const languageState: LanguageState = useAppSelector((state) => state.language);
const languageCode = languageState.id;
const rawParams = useParams<RouteParams>();
const params = useMemo(() => rawParams, [rawParams]);
const navigate = useNavigate();

useEffect(() => {
const currentUrl = window.location.pathname;
if (languageCode && !currentUrl.includes(languageCode)) {
let newUrl = currentUrl;

for (const param in params) {
if (params[param as keyof RouteParams]) {
newUrl = newUrl.replace(`:${param}`, params[param as keyof RouteParams] as string);
}
}

newUrl = newUrl.replace(':language', languageCode);

navigate(newUrl, { replace: true });
}
}, [languageCode, navigate, params]);

return <Component {...props} />;
};
};

export default withLanguageParam;
3 changes: 1 addition & 2 deletions met-web/src/routes/NotFound.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ const listItemStyle = { marginBottom: 1 };
const marginStyle = { mr: 2 };

const tenantId = sessionStorage.getItem('tenantId');
const LanguageId = sessionStorage.getItem('languageId');

const SuggestionsList = ({ translate }: { translate: (key: string) => string }) => (
<Box>
Expand All @@ -18,7 +17,7 @@ const SuggestionsList = ({ translate }: { translate: (key: string) => string })
<li style={listItemStyle}>{translate('notFound.list.0')}</li>
<li style={listItemStyle}>
{translate('notFound.list.1')}{' '}
<Link target="_blank" to={`/${tenantId}/${LanguageId}`}>
<Link target="_blank" to={`/${tenantId}`}>
{translate('notFound.list.2')}
</Link>{' '}
{translate('notFound.list.3')}
Expand Down
Loading

0 comments on commit 0e58785

Please sign in to comment.