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

Website: User location based flag #986

Merged
merged 12 commits into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
18 changes: 18 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions shared/src/types/country.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,3 +250,5 @@ export const COUNTRY_CODES = [
'ZW', // 'Zimbabwe',
] as const;
export type CountryCode = (typeof COUNTRY_CODES)[number];

export const isValidCountryCode = (code: string): code is CountryCode => COUNTRY_CODES.includes(code as CountryCode);
3 changes: 2 additions & 1 deletion shared/src/utils/stats/ContributionStatsCalculator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import _ from 'lodash';
import { DateTime } from 'luxon';
import { FirestoreAdmin } from '../../firebase/admin/FirestoreAdmin';
import { Contribution, CONTRIBUTION_FIRESTORE_PATH, StatusKey } from '../../types/contribution';
import { CountryCode } from '../../types/country';
import { Currency } from '../../types/currency';
import { User, USER_FIRESTORE_PATH } from '../../types/user';
import { getLatestExchangeRate } from '../exchangeRates';
Expand Down Expand Up @@ -30,7 +31,7 @@ export interface ContributionStats {
type ContributionStatsEntry = {
userId: string;
isInstitution: boolean;
country: string;
country: CountryCode;
amount: number;
paymentFees: number;
source: string;
Expand Down
10 changes: 9 additions & 1 deletion ui/src/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { clsx, type ClassValue } from 'clsx';
import { CountryCode } from '@socialincome/shared/src/types/country';
import { WebsiteRegion } from '@socialincome/website/src/i18n';
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';

export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

/**
* We use the files from GitHub instead of the package so that donations from new countries are automatically supported.
*/
export const getFlagImageURL = (country: CountryCode | Exclude<WebsiteRegion, 'int'>) =>
`https://raw.githubusercontent.com/lipis/flag-icons/a87d8b256743c9b0df05f20de2c76a7975119045/flags/1x1/${country.toLowerCase()}.svg`;
1 change: 1 addition & 0 deletions website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@tanstack/react-query": "^5.59.0",
"@types/js-cookie": "^3.0.6",
"@vercel/analytics": "^1.3.1",
"@vercel/functions": "^1.5.2",
"@vimeo/player": "^2.24.0",
"accept-language-parser": "^1.5.0",
"classnames": "^2.5.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
'use client';

import { CountryCode } from '@socialincome/shared/src/types/country';
import { Button, Card, CardContent, Typography } from '@socialincome/ui';
import { getFlagImageURL } from '@socialincome/ui/src/lib/utils';
import { Children, PropsWithChildren, useState } from 'react';

/**
* We use the files from GitHub instead of the package so that donations from new countries are automatically supported.
*/
const getFlagImageURL = (country: string) => {
return `https://raw.githubusercontent.com/lipis/flag-icons/a87d8b256743c9b0df05f20de2c76a7975119045/flags/1x1/${country.toLowerCase()}.svg`;
};

type CountryCardProps = {
country: string;
country: CountryCode;
translations: {
country: string;
total: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { roundAmount } from '@/app/[lang]/[region]/(website)/transparency/finances/[currency]/section-1';
import { CountryCode } from '@socialincome/shared/src/types/country';
import { Translator } from '@socialincome/shared/src/utils/i18n';
import { Typography } from '@socialincome/ui';
import { SectionProps } from './page';
Expand All @@ -10,7 +11,7 @@ export async function Section3({ params, contributionStats }: SectionProps) {
namespaces: ['countries', 'website-finances'],
});
const totalContributionsByCountry = contributionStats.totalContributionsByCountry as {
country: string;
country: CountryCode;
amount: number;
usersCount: number;
}[];
Expand Down
1 change: 1 addition & 0 deletions website/src/app/[lang]/[region]/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { WebsiteLanguage, WebsiteRegion } from '@/i18n';

export const LANGUAGE_COOKIE = 'si_lang';
export const REGION_COOKIE = 'si_region';
export const COUNTRY_COOKIE = 'si_country';
export const CURRENCY_COOKIE = 'si_currency';

export interface DefaultParams {
Expand Down
12 changes: 12 additions & 0 deletions website/src/app/api/geolocation/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { handleApiError } from '@/app/api/auth';
import { Geo, geolocation } from '@vercel/functions';

export async function GET(request: Request) {
try {
const geo = geolocation(request);

return Response.json({ country: geo.country } as Geo);
} catch (error: any) {
return handleApiError(error);
}
dnhn marked this conversation as resolved.
Show resolved Hide resolved
}
36 changes: 29 additions & 7 deletions website/src/components/navbar/navbar-client.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use client';

import { DefaultParams } from '@/app/[lang]/[region]';
import { getFlagComponentByCurrency } from '@/components/country-flags';
import { DonateIcon } from '@/components/logos/donate-icon';
import { SIAnimatedLogo } from '@/components/logos/si-animated-logo';
import { SIIcon } from '@/components/logos/si-icon';
Expand All @@ -11,8 +10,10 @@ import { useGlobalStateProvider } from '@/components/providers/global-state-prov
import { WebsiteCurrency, WebsiteLanguage, WebsiteRegion } from '@/i18n';
import { Bars3Icon, CheckIcon, ChevronLeftIcon, XMarkIcon } from '@heroicons/react/24/outline';
import { Typography } from '@socialincome/ui';
import { getFlagImageURL } from '@socialincome/ui/src/lib/utils';
import classNames from 'classnames';
import _ from 'lodash';
import Image from 'next/image';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { twMerge } from 'tailwind-merge';
Expand Down Expand Up @@ -59,7 +60,8 @@ const MobileNavigation = ({ lang, region, languages, regions, currencies, naviga
const [visibleSection, setVisibleSection] = useState<
'main' | 'our-work' | 'about-us' | 'transparency' | 'i18n' | null
>(null);
const { language, setLanguage, setRegion, currency, setCurrency } = useI18n();
const { country, language, setLanguage, setRegion, currency, setCurrency } = useI18n();
const isIntRegion = region === 'int';

useEffect(() => {
// Prevent scrolling when the navbar is expanded
Expand Down Expand Up @@ -188,7 +190,6 @@ const MobileNavigation = ({ lang, region, languages, regions, currencies, naviga
break;
case 'main':
default:
const Flag = getFlagComponentByCurrency(currency);
const ourWork = navigation![0];
const aboutUs = navigation![1];
const transparency = navigation![2];
Expand All @@ -211,7 +212,17 @@ const MobileNavigation = ({ lang, region, languages, regions, currencies, naviga
{translations.myProfile}
</NavbarLink>
<div className="flex-inline flex items-center">
{Flag && <Flag className="mx-3 h-6 w-6 rounded-full" />}
{(!isIntRegion || (isIntRegion && country)) && (
<Image
Copy link
Contributor

Choose a reason for hiding this comment

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

Should we also do it like this in website/src/components/ui/currency-selector.tsx? Then we could uninstall the package. Wdyt?

Copy link
Member Author

Choose a reason for hiding this comment

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

Sure, I’ll update it.

Copy link
Member Author

@dnhn dnhn Dec 21, 2024

Choose a reason for hiding this comment

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

The library we are using https://raw.githubusercontent.com/lipis/flag-icons/a87d8b256743c9b0df05f20de2c76a7975119045/flags/… only accepts country code, do you have any library suggestions for currency flags?

I would work on this in another PR since this involves with other components.

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 mean currency icons? Otherwise, we would have to create some mapping to map currencies to countries (similiar to the countryToCurrency mapping in currency.ts).

FYI – I created an MR (#992) to use a middleware to set the country code. Let me know what you think :)

className="mx-3 rounded-full"
src={getFlagImageURL(isIntRegion ? country! : region)}
width={24}
height={24}
alt="Country flag"
priority
unoptimized
/>
)}
dnhn marked this conversation as resolved.
Show resolved Hide resolved
<Typography as="button" className="text-2xl font-medium" onClick={() => setVisibleSection('i18n')}>
{currency} / {languages.find((l) => l.code === language)?.translation}
</Typography>
Expand Down Expand Up @@ -251,8 +262,9 @@ const MobileNavigation = ({ lang, region, languages, regions, currencies, naviga
};

const DesktopNavigation = ({ lang, region, languages, regions, currencies, navigation, translations }: NavbarProps) => {
let { currency, setCurrency, setLanguage, setRegion } = useI18n();
const Flag = getFlagComponentByCurrency(currency);
const { country, currency, setCurrency, setLanguage, setRegion } = useI18n();
const isIntRegion = region === 'int';
dnhn marked this conversation as resolved.
Show resolved Hide resolved

const NavbarLink = ({ href, children, className }: { href: string; children: string; className?: string }) => (
<Link href={href} className={twMerge('hover:text-accent text-lg', className)}>
{children}
Expand Down Expand Up @@ -321,7 +333,17 @@ const DesktopNavigation = ({ lang, region, languages, regions, currencies, navig
</div>
<div className="group/i18n flex h-full flex-1 shrink-0 basis-1/4 flex-col">
<div className="flex flex-row items-baseline justify-end">
{Flag && <Flag className="m-auto mx-2 h-5 w-5 rounded-full" />}
{(!isIntRegion || (isIntRegion && country)) && (
<Image
className="m-auto mx-2 rounded-full"
src={getFlagImageURL(isIntRegion ? country! : region)}
width={24}
height={24}
alt="Country flag"
priority
unoptimized
/>
)}{' '}
<Typography size="lg">{languages.find((l) => l.code === lang)?.translation}</Typography>
</div>
<div className="ml-auto mt-6 hidden h-full grid-cols-1 justify-items-start gap-2 text-left opacity-0 group-hover/navbar:grid group-hover/i18n:opacity-100 lg:grid-cols-[repeat(3,auto)] lg:justify-items-end lg:gap-8">
Expand Down
14 changes: 10 additions & 4 deletions website/src/components/providers/context-providers.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import { CURRENCY_COOKIE, LANGUAGE_COOKIE, REGION_COOKIE } from '@/app/[lang]/[region]';
import { COUNTRY_COOKIE, CURRENCY_COOKIE, LANGUAGE_COOKIE, REGION_COOKIE } from '@/app/[lang]/[region]';
import { ApiProvider } from '@/components/providers/api-provider';
import { GlobalStateProviderProvider } from '@/components/providers/global-state-provider';
import { FacebookTracking } from '@/components/tracking/facebook-tracking';
Expand All @@ -10,6 +10,7 @@ import { useCookieState } from '@/hooks/useCookieState';
import { WebsiteCurrency, WebsiteLanguage, WebsiteRegion } from '@/i18n';
import { initializeAnalytics } from '@firebase/analytics';
import { DEFAULT_REGION } from '@socialincome/shared/src/firebase';
import { CountryCode } from '@socialincome/shared/src/types/country';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Analytics } from '@vercel/analytics/react';
import { ConsentSettings, ConsentStatusString, setConsent } from 'firebase/analytics';
Expand Down Expand Up @@ -140,6 +141,8 @@ function FirebaseSDKProviders({ children }: PropsWithChildren) {
}

type I18nContextType = {
country: CountryCode | undefined;
setCountry: (country: CountryCode) => void;
language: WebsiteLanguage | undefined;
setLanguage: (language: WebsiteLanguage) => void;
region: WebsiteRegion | undefined;
Expand Down Expand Up @@ -189,16 +192,19 @@ function I18nProvider({ children }: PropsWithChildren) {
const { value: language, setCookie: setLanguage } = useCookieState<WebsiteLanguage>(LANGUAGE_COOKIE);
const { value: region, setCookie: setRegion } = useCookieState<WebsiteRegion>(REGION_COOKIE);
const { value: currency, setCookie: setCurrency } = useCookieState<WebsiteCurrency>(CURRENCY_COOKIE);
const { value: country, setCookie: setCountry } = useCookieState<CountryCode>(COUNTRY_COOKIE);

return (
<I18nContext.Provider
value={{
country: country,
setCountry: (country) => setCountry(country, { expires: 7 }),
language: language,
setLanguage: (language) => setLanguage(language, { expires: 365 }),
setLanguage: (language) => setLanguage(language, { expires: 7 }),
region: region,
setRegion: (country) => setRegion(country, { expires: 365 }),
setRegion: (country) => setRegion(country, { expires: 7 }),
currency: currency,
setCurrency: (currency) => setCurrency(currency, { expires: 365 }),
setCurrency: (currency) => setCurrency(currency, { expires: 7 }),
}}
>
<Suspense fallback={null}>
Expand Down
21 changes: 21 additions & 0 deletions website/src/hooks/queries.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useApi } from '@/hooks/useApi';
import { useQuery } from '@tanstack/react-query';
import { Geo } from '@vercel/functions';

export const useGeolocation = () => {
const api = useApi();
const {
data: geolocation,
isLoading,
error,
} = useQuery({
queryKey: ['geolocation'],
queryFn: async () => {
const response = await api.get('/api/geolocation');
return (await response.json()) as Geo;
},
staleTime: Infinity,
});

return { geolocation, isLoading, error };
};
dnhn marked this conversation as resolved.
Show resolved Hide resolved
42 changes: 33 additions & 9 deletions website/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CURRENCY_COOKIE } from '@/app/[lang]/[region]';
import { COUNTRY_COOKIE, CURRENCY_COOKIE } from '@/app/[lang]/[region]';
import { WebsiteLanguage, WebsiteRegion, allWebsiteLanguages, findBestLocale, websiteRegions } from '@/i18n';
import { CountryCode } from '@socialincome/shared/src/types/country';
import { CountryCode, isValidCountryCode } from '@socialincome/shared/src/types/country';
import { NextRequest, NextResponse } from 'next/server';
import { bestGuessCurrency, isValidCurrency } from '../../shared/src/types/currency';

Expand All @@ -11,17 +11,39 @@ export const config = {
],
};

export const currencyMiddleware = (request: NextRequest, response: NextResponse) => {
// Checks if a valid currency is set as a cookie, and sets one with the best guess if not.
/**
* Checks if a valid country is set as a cookie, and sets one based on the request header if available.
*/
const countryMiddleware = (request: NextRequest, response: NextResponse) => {
if (request.cookies.has(COUNTRY_COOKIE) && isValidCountryCode(request.cookies.get(COUNTRY_COOKIE)?.value!))
return response;

const requestCountry = request.geo?.country;
if (requestCountry)
response.cookies.set({
name: COUNTRY_COOKIE,
value: requestCountry as CountryCode,
path: '/',
maxAge: 60 * 60 * 24 * 7,
}); // 1 week
return response;
};

/**
* Checks if a valid currency is set as a cookie, and sets one based on the country cookie if available.
*/
const currencyMiddleware = (request: NextRequest, response: NextResponse) => {
if (request.cookies.has(CURRENCY_COOKIE) && isValidCurrency(request.cookies.get(CURRENCY_COOKIE)?.value))
return response;
// We use the country code from the request header if available. If not, we use the region/country from the url path.
const requestCountry = request.geo?.country || request.nextUrl.pathname.split('/').at(2)?.toUpperCase();
const currency = bestGuessCurrency(requestCountry as CountryCode);
response.cookies.set({ name: CURRENCY_COOKIE, value: currency, path: '/', maxAge: 60 * 60 * 24 * 365 }); // 1 year
const country = request.cookies.get(CURRENCY_COOKIE)?.value as CountryCode | undefined;
const currency = bestGuessCurrency(country);

response.cookies.set({ name: CURRENCY_COOKIE, value: currency, path: '/', maxAge: 60 * 60 * 24 * 7 }); // 1 week
return response;
};
export const redirectMiddleware = (request: NextRequest) => {
dnhn marked this conversation as resolved.
Show resolved Hide resolved

const redirectMiddleware = (request: NextRequest) => {
switch (request.nextUrl.pathname) {
case '/twint':
return NextResponse.redirect('https://donate.raisenow.io/dpbdp');
Expand Down Expand Up @@ -53,7 +75,7 @@ export const redirectMiddleware = (request: NextRequest) => {
}
};

export const i18nRedirectMiddleware = (request: NextRequest) => {
const i18nRedirectMiddleware = (request: NextRequest) => {
// Checks if the language and country in the URL are supported, and redirects to the best locale if not.
const segments = request.nextUrl.pathname.split('/');
const detectedLanguage = segments.at(1) ?? '';
Expand Down Expand Up @@ -82,7 +104,9 @@ export function middleware(request: NextRequest) {
let response = redirectMiddleware(request) || i18nRedirectMiddleware(request);
if (response) return response;

// If no redirect was triggered, we continue with the country and currency middleware.
response = NextResponse.next();
response = countryMiddleware(request, response);
response = currencyMiddleware(request, response);
return response;
}
Loading