Skip to content

Commit

Permalink
Merge pull request #917 from betagouv/main
Browse files Browse the repository at this point in the history
MEP (matomo stuff again, fixed)
  • Loading branch information
eletallbetagouv authored Sep 24, 2024
2 parents eefd904 + c6eccf9 commit c7b6407
Show file tree
Hide file tree
Showing 9 changed files with 77 additions and 38 deletions.
10 changes: 6 additions & 4 deletions website/src/analytic/AnalyticContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import {Analytic} from './analytic'

export interface AnalyticContextProps {
trackEvent: Analytic['trackEvent']
trackSearch: Analytic['trackSearch']
setTrackedCompanyKind: Analytic['setTrackedCompanyKind']
}

interface Props {
Expand All @@ -19,10 +21,10 @@ export const AnalyticProvider = ({analytic, children}: Props) => {
return (
<AnalyticContext.Provider
value={{
trackEvent:
analytic?.trackEvent ??
// analytics are not available server-side
((...args: any[]) => {}),
// analytics are not available server-side
trackEvent: analytic?.trackEvent ?? (() => {}),
trackSearch: analytic?.trackSearch ?? (() => {}),
setTrackedCompanyKind: analytic?.setTrackedCompanyKind ?? (() => {}),
}}
>
{children}
Expand Down
37 changes: 27 additions & 10 deletions website/src/analytic/analytic.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {appConfig} from '@/core/appConfig'
import {usePathname, useSearchParams} from 'next/navigation'
import {useEffect} from 'react'
import {CompanyKind} from 'shared/anomalies/Anomaly'
import {Eularian} from '../plugins/eularian'
import {Matomo} from '../plugins/matomo'

Expand All @@ -11,10 +12,15 @@ export class Analytic {
return new Analytic(matomo, eularian)
}

private log = (...args: (string | undefined)[]) => {
private log = (...args: unknown[]) => {
console.debug('[Analytic]', ...args)
}

private matomoPush = (args: (number[] | string[] | number | string | undefined)[]) => {
this.log(...args)
this.matomo?.push(args)
}

private constructor(
private matomo: Matomo | undefined,
private eularian: Eularian | undefined,
Expand All @@ -27,15 +33,26 @@ export class Analytic {
}

readonly trackEvent = (category: EventCategories, action: AnalyticAction, name?: string, value?: string) => {
this.log('[trackEvent]', category, action, name, value)
try {
this.matomo?.push(['trackEvent', category, action, name, value])
} catch (e: any) {
console.error('[Analytic]', e)
if (!(e instanceof ReferenceError)) {
throw e
}
}
this.matomoPush(['trackEvent', category, action, name, value])
}

readonly trackSearch = (
inputs: {q: string; postalCode?: string; departmentCode?: string},
searchCategory: 'companysearch_smart' | 'companysearch_nameandpostalcode' | 'companysearch_name' | 'companysearch_siret',
nbResults: number,
) => {
const {q, postalCode, departmentCode} = inputs
const trackedSearch = `${postalCode ? `[${postalCode}] ` : ''}${departmentCode ? `[${departmentCode}] ` : ''}${q}`
// https://developer.matomo.org/guides/tracking-javascript-guide#internal-search-tracking
this.matomoPush(['trackSiteSearch', trackedSearch, searchCategory, nbResults])
}

readonly setTrackedCompanyKind = (companyKind: CompanyKind) => {
const customDimensionId = 1
// https://developer.matomo.org/guides/tracking-javascript-guide#custom-dimensions
// This doesn't send anything
// but should set the custom dimension "companykind" for the events after it
this.matomoPush(['setCustomDimension', customDimensionId, companyKind])
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@ export const CompanySearchByIdentifier = ({children}: Props) => {
const [submittedIdentity, setSubmittedIdentity] = useState<string | undefined>(undefined)
const _searchByIdentity = useQuery({
queryKey: ['searchCompaniesByIdentity', submittedIdentity],
queryFn: () => {
queryFn: async () => {
if (submittedIdentity) {
return companyApiClient.searchCompaniesByIdentity(submittedIdentity, false, currentLang)
const res = await companyApiClient.searchCompaniesByIdentity(submittedIdentity, false, currentLang)
_analytic.trackSearch({q: submittedIdentity}, 'companysearch_siret', res.length)
return res
}
return null
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import {CompanySearchResult} from '@/model/Company'
import {ReactNode, useState} from 'react'
import {useI18n} from '@/i18n/I18n'
import {useApiClients} from '@/context/ApiClientsContext'
import {useQuery} from '@tanstack/react-query'
import {useToastOnQueryError} from '@/clients/apiHooks'
import {useAnalyticContext} from '@/analytic/AnalyticContext'
import {useForm} from 'react-hook-form'
import {CompanySearchEventActions, EventCategories} from '@/analytic/analytic'
import {useToastOnQueryError} from '@/clients/apiHooks'
import {Animate} from '@/components_simple/Animate'
import {RequiredFieldsLegend} from '@/components_simple/RequiredFieldsLegend'
import {ScTextInput} from '@/components_simple/formInputs/ScTextInput'
import {ButtonWithLoader} from '@/components_simple/buttons/Buttons'
import {ScTextInput} from '@/components_simple/formInputs/ScTextInput'
import {useApiClients} from '@/context/ApiClientsContext'
import {useI18n} from '@/i18n/I18n'
import {CompanySearchResult} from '@/model/Company'
import {ifDefined} from '@/utils/utils'
import {useQuery} from '@tanstack/react-query'
import {ReactNode, useState} from 'react'
import {useForm} from 'react-hook-form'

interface Form {
name: string
Expand All @@ -27,9 +27,12 @@ export const CompanySearchByName = ({children}: Props) => {
const [submittedForm, setSubmittedForm] = useState<Form | undefined>()
const _search = useQuery({
queryKey: ['searchHeadOfficesByName', submittedForm?.name],
queryFn: () => {
queryFn: async () => {
if (submittedForm) {
return companyApiClient.searchHeadOfficesByName(submittedForm.name, currentLang)
const {name} = submittedForm
const res = await companyApiClient.searchHeadOfficesByName(name, currentLang)
_analytic.trackSearch({q: name}, 'companysearch_name', res.length)
return res
}
return null
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,12 @@ export const CompanySearchByNameAndPostalCode = ({children}: Props) => {
const [submittedForm, setSubmittedForm] = useState<Form | undefined>()
const _search = useQuery({
queryKey: ['searchCompaniesByNameAndPostalCode', submittedForm?.name, submittedForm?.postalCode],
queryFn: () => {
queryFn: async () => {
if (submittedForm) {
return companyApiClient.searchCompaniesByNameAndPostalCode(submittedForm.name, submittedForm.postalCode, currentLang)
const {name, postalCode} = submittedForm
const res = await companyApiClient.searchCompaniesByNameAndPostalCode(name, postalCode, currentLang)
_analytic.trackSearch({q: name, postalCode}, 'companysearch_nameandpostalcode', res.length)
return res
}
return null
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {useAnalyticContext} from '@/analytic/AnalyticContext'
import {useToastOnQueryError} from '@/clients/apiHooks'
import {Animate} from '@/components_simple/Animate'
import {useApiClients} from '@/context/ApiClientsContext'
Expand Down Expand Up @@ -139,14 +140,17 @@ export function CompanySmartIdentification({
function useCompanySearchSmartQuery(searchInputs: CompanySearchInputs | undefined) {
const {companyApiClient} = useApiClients()
const {currentLang} = useI18n()
const _analytic = useAnalyticContext()
const _search = useQuery({
queryKey: ['searchCompany', searchInputs],
queryFn: async () => {
if (searchInputs) {
const {input, geoArea} = searchInputs
const postalCode = geoArea && geoArea.kind === 'postcode' ? geoArea.postalCode : undefined
const departmentCode = geoArea && geoArea.kind === 'department' ? geoArea.dpt.code : undefined
return companyApiClient.searchSmart(input, postalCode, departmentCode, currentLang)
const res = await companyApiClient.searchSmart(input, postalCode, departmentCode, currentLang)
_analytic.trackSearch({q: input, postalCode, departmentCode}, 'companysearch_smart', res.length)
return res
}
return null
},
Expand Down
16 changes: 10 additions & 6 deletions website/src/components_feature/reportFlow/Problem/Problem.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import {useAnalyticContext} from '@/analytic/AnalyticContext'
import {AnalyticContextProps, useAnalyticContext} from '@/analytic/AnalyticContext'
import {EventCategories, ReportEventActions} from '@/analytic/analytic'
import {NextStepButton} from '@/components_feature/reportFlow/reportFlowStepper/NextStepButton'
import {StepNavigation} from '@/components_feature/reportFlow/reportFlowStepper/ReportFlowStepper'
import {OpenFfWelcomeText, useOpenFfSetupLoaded as useHandleOpenFfSetupLoaded, useOpenFfSetup} from '@/feature/openFoodFacts'
import {RappelConsoWelcome, useHandleRcSetupLoaded, useRappelConsoSetup} from '@/feature/rappelConso'
import {hasStep0, hasStep1Full} from '@/feature/reportUtils'
import {getCompanyKind, hasStep0, hasStep1Full} from '@/feature/reportUtils'
import {initiateReport} from '@/feature/reportUtils2'
import {useI18n} from '@/i18n/I18n'
import {Step2Model} from '@/model/Step2Model'
Expand Down Expand Up @@ -41,6 +41,7 @@ export function Problem({anomaly, isWebView, stepNavigation}: Props) {
}

function ProblemInner({anomaly, isWebView, stepNavigation}: Props) {
const _analytic = useAnalyticContext()
const {report, setReport, sendReportEvent} = useReportFlowContext()
if (!hasStep0(report)) {
throw new Error('Report should have a lang and a category already (in Problem)')
Expand All @@ -50,7 +51,7 @@ function ProblemInner({anomaly, isWebView, stepNavigation}: Props) {
useHandleOpenFfSetupLoaded(openFfSetup, setReport)
useHandleRcSetupLoaded(rappelConsoSetup, setReport)
const specialCategoriesNotLoading = openFfSetup.status !== 'loading' && rappelConsoSetup.status !== 'loading'
const onNext = buildOnNext({sendReportEvent, setReport, stepNavigation})
const onNext = buildOnNext({sendReportEvent, setReport, stepNavigation, _analytic})
return (
<>
<OpenFfWelcomeText setup={openFfSetup} />
Expand All @@ -74,16 +75,19 @@ function buildOnNext({
setReport: setReport,
stepNavigation,
sendReportEvent,
_analytic,
}: {
setReport: SetReport
stepNavigation: StepNavigation
sendReportEvent: SendReportEvent
_analytic: AnalyticContextProps
}) {
return function onNext(next: () => void): void {
return function (next: () => void): void {
setReport(draft => {
if (!hasStep1Full(draft)) {
throw new Error(`Report is not ready to go to next step, step1 is not full`)
if (!hasStep0(draft) || !hasStep1Full(draft)) {
throw new Error(`Report is not ready to go to step2`)
}
_analytic.setTrackedCompanyKind(getCompanyKind(draft))
// In the openFf scenario
// Only if we got all the data, then we build the company/product from it.
// If we only have partial data, then we will build it in step 2.
Expand Down
4 changes: 2 additions & 2 deletions website/src/plugins/eularian.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ export class Eularian {
readonly send = (path: string): void => {
try {
window.EA_push(['path', path])
} catch (e: any) {
console.error('[Eularian Analytic]', e)
} catch (e) {
console.error('Eularian error', e)
}
}
}
6 changes: 5 additions & 1 deletion website/src/plugins/matomo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ export class Matomo {
if (!window._paq) {
window._paq = []
}
window._paq.push(args)
try {
window._paq.push(args)
} catch (e) {
console.error('Matomo error', e)
}
}
}

Expand Down

0 comments on commit c7b6407

Please sign in to comment.