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

fix: AddressDrawer rework #1326

Merged
merged 24 commits into from
Jul 17, 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
2 changes: 2 additions & 0 deletions apps/app/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,5 @@ yarn-error.log*
.sentryclirc

webpack-stats.json

certificates
2 changes: 1 addition & 1 deletion apps/app/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ const MyApp = (appProps: AppPropsWithGridSwitch) => {
<Notifications transitionDuration={500} />
<ConditionalReactQueryDevtool />
<Analytics />
<SpeedInsights />
<DonateModal />
</Providers>
<SpeedInsights />
</>
)
}
Expand Down
2 changes: 1 addition & 1 deletion apps/app/src/pages/api/trpc/[trpc].ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export default createNextApiHandler({
const ONE_DAY_IN_SECONDS = 60 * 60 * 24
return {
headers: {
'Cache-Control': `s-maxage=1, public, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
'cache-control': `s-maxage=1, public, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
}
}
Expand Down
5 changes: 4 additions & 1 deletion apps/app/src/pages/org/[slug]/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,10 @@ export const getServerSideProps: GetServerSideProps<{ organizationId: string },
const { id: organizationId } = await ssg.organization.getIdFromSlug.fetch({ slug })

const [i18n] = await Promise.all([
getServerSideTranslations(locale, compact(['common', 'services', 'attribute', 'phone-type'])),
getServerSideTranslations(
locale,
compact(['common', 'services', 'attribute', 'phone-type', 'gov-dist', organizationId])
),
ssg.organization.forOrgPageEdits.prefetch({ slug }),
ssg.fieldOpt.countries.prefetch({ activeForOrgs: true }),
])
Expand Down
4 changes: 2 additions & 2 deletions apps/app/src/providers/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,9 @@ export const Providers = ({ children, session }: ProviderProps) => {
// )

const mantineTheme = useMemo(() => ({ ...appTheme, fontFamily: fontWorkSans.style.fontFamily }), [])

const mantineCache = useMemo(() => appCache, [])
JoeKarow marked this conversation as resolved.
Show resolved Hide resolved
return (
<MantineProvider withGlobalStyles withNormalizeCSS theme={mantineTheme} emotionCache={appCache}>
<MantineProvider withGlobalStyles withNormalizeCSS theme={mantineTheme} emotionCache={mantineCache}>
{/* <ConsentProvider options={consentOptions}> */}
<SessionProvider session={session}>
<EditModeProvider>
Expand Down
2 changes: 2 additions & 0 deletions packages/api/lib/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@ export type CreateContextOptions = {
*/

export const createContextInner = (opts: CreateContextOptions) => {
const locale = opts.req?.cookies['NEXT_LOCALE'] ?? 'en'
JoeKarow marked this conversation as resolved.
Show resolved Hide resolved
return {
generateId,
locale,
session: opts.session,
skipCache: false,
req: opts.req,
Expand Down
1 change: 1 addition & 0 deletions packages/api/router/geo/query.cityCoords.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const cityCoords = async ({ input }: TRPCHandlerParams<TCityCoordsSchema>) => {
key: process.env.GOOGLE_PLACES_API_KEY as string,
address: searchString,
components: PlaceAutocompleteType.cities,
region: searchCountry,
},
})

Expand Down
22 changes: 15 additions & 7 deletions packages/api/router/location/mutation.create.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { type TCreateSchema } from './mutation.create.schema'

const create = async ({ ctx, input }: TRPCHandlerParams<TCreateSchema, 'protected'>) => {
const prisma = getAuditedClient(ctx.actorId)
const { emails, phones, services, address, ...rest } = input
const { emails, phones, services, address, orgId, ...rest } = input
const serviceLinks = (
!services
? undefined
Expand Down Expand Up @@ -35,17 +35,25 @@ const create = async ({ ctx, input }: TRPCHandlerParams<TCreateSchema, 'protecte
})
)
) satisfies Prisma.OrgLocationPhoneCreateNestedManyWithoutLocationInput | undefined
const addressData = address
? {
...address,
...createGeoFields({ longitude: address.longitude, latitude: address.latitude }),
}
: address

const { countryId, govDistId, ...addressRest } = address

const addressData = {
...addressRest,
...createGeoFields({ longitude: address.longitude, latitude: address.latitude }),
country: {
connect: { id: countryId },
},
...(govDistId && { govDist: { connect: { id: govDistId } } }),
}

const createArgs = Prisma.validator<Prisma.OrgLocationCreateArgs>()({
data: {
...rest,
...addressData,
organization: {
connect: { id: orgId },
},
emails: emailLinks,
phones: phoneLinks,
services: serviceLinks,
Expand Down
6 changes: 3 additions & 3 deletions packages/api/router/location/mutation.create.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ export const ZCreateSchema = z.object({
name: z.string(),
address: z
.object({
street1: z.string(),
street2: z.string().optional(),
street1: z.string().nullish(),
street2: z.string().nullish(),
city: z.string(),
postCode: z.string().optional(),
postCode: z.string().nullish(),
govDistId: z.string(),
longitude: z.number(),
latitude: z.number(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ const forVisitCard = async ({ input }: TRPCHandlerParams<TForVisitCardSchema>) =
where: {
...globalWhere.isPublic(),
id: input,
addressVisibility: { in: ['FULL'] },
},
select: {
id: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { prisma } from '@weareinreach/db'
import { handleError } from '~api/lib/errorHandler'
import { type TRPCHandlerParams } from '~api/types/handler'

import { formatAddressVisiblity } from './lib.formatAddressVisibility'
import { type TForVisitCardEditsSchema } from './query.forVisitCardEdits.schema'

const forVisitCardEdits = async ({ input }: TRPCHandlerParams<TForVisitCardEditsSchema>) => {
Expand All @@ -25,14 +26,18 @@ const forVisitCardEdits = async ({ input }: TRPCHandlerParams<TForVisitCardEdits
},
latitude: true,
longitude: true,
addressVisibility: true,
JoeKarow marked this conversation as resolved.
Show resolved Hide resolved
},
})
if (!result) {
return null
}
const formattedAddress = formatAddressVisiblity(result)

const { attributes, ...rest } = result
const transformed = {
...rest,
...formattedAddress,
remote: attributes.find(({ attribute }) => attribute.tsKey === 'additional.offers-remote-services')
?.attribute,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const upsert = async ({ ctx, input }: TRPCHandlerParams<TUpsertSchema, 'protecte
const isCreateData = (op: 'create' | 'update', inputData: typeof data): inputData is CreateData =>
op === 'create'
const isCreate = operation === 'create'
const id = isCreate ? passedId ?? generateId('orgSocialMedia') : passedId
const id = isCreate ? (passedId ?? generateId('orgSocialMedia')) : passedId
let username = passedUsername

if (url && !passedUsername) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const upsert = async ({ ctx, input }: TRPCHandlerParams<TUpsertSchema, 'protecte
op === 'create'
const isCreate = operation === 'create'

const id = isCreate ? passedId ?? generateId('orgEmail') : passedId
const id = isCreate ? (passedId ?? generateId('orgEmail')) : passedId

const generateDescription = (): GeneratedDescription | undefined => {
if (!desc || !organizationId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { attributes, freeText } from '~api/schemas/selects/common'
import { type TRPCHandlerParams } from '~api/types/handler'

import { type TForOrgPageEditsSchema } from './query.forOrgPageEdits.schema'
import { formatAddressVisiblity } from '../location/lib.formatAddressVisibility'

const forOrgPageEdits = async ({ input }: TRPCHandlerParams<TForOrgPageEditsSchema>) => {
const { slug } = input
Expand Down Expand Up @@ -40,9 +41,10 @@ const forOrgPageEdits = async ({ input }: TRPCHandlerParams<TForOrgPageEditsSche
attributes,
},
})
const { allowedEditors, ...orgData } = org
const { allowedEditors, locations, ...orgData } = org
const reformatted = {
...orgData,
locations: locations.map((location) => ({ ...location, ...formatAddressVisiblity(location) })),
isClaimed: Boolean(allowedEditors.length),
}

Expand Down
2 changes: 1 addition & 1 deletion packages/api/trpc/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const getBaseUrl = () => {
return `https://${getEnv('VERCEL_URL')}`
}
// dev SSR should use localhost
return `http://localhost:${getEnv('PORT') ?? process.env.STORYBOOK ? 6006 : 3000}`
return `http://localhost:${(getEnv('PORT') ?? process.env.STORYBOOK) ? 6006 : 3000}`
}

export const trpcConfig = {
Expand Down
2 changes: 1 addition & 1 deletion packages/auth/lib/userLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import { type AuthResult, ClientId, cognito, generateHash, parseAuthResponse } f
export const userLogin: UserLogin = async (email, password) => {
const response = await cognito.initiateAuth({
AuthFlow: AuthFlowType.USER_PASSWORD_AUTH,
ClientId,
AuthParameters: {
USERNAME: email.toLowerCase(),
PASSWORD: password,
SECRET_HASH: generateHash(email.toLowerCase()),
},
ClientId,
})
return parseAuthResponse(response, email.toLowerCase())
}
Expand Down
5 changes: 3 additions & 2 deletions packages/crowdin/cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,10 @@ export const redisReadCache = async (
spanExpire.end()
}
const cacheArray = Array.from(cacheResults.entries())
const cacheArraySize = cacheArray.length === 0 ? 0 : sizeof(cacheArray)

log.info(`Cache return: ${cacheResults.size} ${formatBytes(sizeof(cacheArray))}`)
span.addEvent('data return size', { size: formatBytes(sizeof(cacheArray)) })
log.info(`Cache return: ${cacheResults.size} ${formatBytes(cacheArraySize)}`)
span.addEvent('data return size', { size: formatBytes(cacheArraySize) })
return cacheArray
} finally {
span.end()
Expand Down
3 changes: 2 additions & 1 deletion packages/db/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"clean:zod": "rm -rf ./zod-schemas/* || true",
"db:dataMigrate": "pnpm with-env tsx ./prisma/dataMigrationRunner.ts",
"db:deploy": "pnpm with-env prisma migrate deploy",
"db:generate": "pnpm clean:zod && pnpm with-env prisma generate --generator client --generator enum && prisma -v",
"db:generate": "pnpm clean:zod && pnpm with-env prisma generate --generator client --generator enum --no-hints && prisma -v && pnpm format:enums",
"db:generate:aws": "pnpm with-env prisma generate --generator aws",
"db:generate:kysely": "pnpm with-env kysely-codegen || true",
"db:migrate": "pnpm with-env prisma migrate dev",
Expand All @@ -26,6 +26,7 @@
"db:studio": "pnpm with-env prisma studio",
"format": "prettier --cache --cache-strategy metadata --write --ignore-unknown . && prisma format",
"format:all": "pnpm format:export && pnpm format:generated",
"format:enums": "prettier --write ./enums/*",
"format:export": "prettier --cache --cache-strategy metadata --write ./data-transfer/**/*.{ts,json}",
"format:generated": "prettier --cache --cache-strategy metadata --write ./zod*/*",
"generate:data": "pnpm with-env tsx ./lib/generateData.ts",
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-config/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ const config = {
},
{
files: ['./**/*.{js,mjs,cjs}'],
parserOptions: { project: true },
parserOptions: { project: true, ecmaVersion: 2020, sourceType: 'module' },
rules: {
'@typescript-eslint/require-await': 'off',
'@typescript-eslint/return-await': 'off',
Expand Down
11 changes: 10 additions & 1 deletion packages/ui/components/core/LangPicker.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { createStyles, Flex, Menu, rem, Text, UnstyledButton, type UnstyledButtonProps } from '@mantine/core'
import { hasCookie, setCookie } from 'cookies-next'
import { useRouter } from 'next/router'
import { useTranslation } from 'next-i18next'
import { forwardRef, useCallback, useMemo } from 'react'
import { forwardRef, useCallback, useEffect, useMemo } from 'react'

import { type LocaleCodes, translatedLangs } from '@weareinreach/db/generated/languages'
import { useCustomVariant } from '~ui/hooks/useCustomVariant'
Expand Down Expand Up @@ -59,6 +60,7 @@ export const LangPicker = () => {
(newLocale: LocaleCodes) => () => {
const { pathname, asPath, query } = router
i18n.changeLanguage(newLocale)
setCookie('NEXT_LOCALE', newLocale)
router.replace({ pathname, query }, asPath, { locale: newLocale })
},
[i18n, router]
Expand All @@ -73,6 +75,13 @@ export const LangPicker = () => {
[langHandler]
)

useEffect(() => {
if (!hasCookie('NEXT_LOCALE')) {
setCookie('NEXT_LOCALE', currentLanguage)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

return (
<Menu
trigger='hover'
Expand Down
Loading
Loading