Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Merge CAPTCHA projects with regular projects

Blue Mousea9c10452a2bf
diff --git a/backend/apps/cloud/src/captcha/captcha.service.ts b/backend/apps/cloud/src/captcha/captcha.service.ts
index 255b942b0..00c0832e4 100644
--- a/backend/apps/cloud/src/captcha/captcha.service.ts
+++ b/backend/apps/cloud/src/captcha/captcha.service.ts
@@ -70,7 +70,7 @@ export class CaptchaService {
private readonly projectService: ProjectService,
) {}
- // checks if captcha is enabled for pid
+ // checks if captcha is enabled for pid (by checking if captchaSecretKey exists)
async _isCaptchaEnabledForPID(pid: string) {
const project = await this.projectService.getRedisProject(pid)
@@ -78,7 +78,7 @@ export class CaptchaService {
return false
}
- return project.isCaptchaEnabled
+ return !!project.captchaSecretKey
}
// validates pid, checks if captcha is enabled and throws an error otherwise
diff --git a/backend/apps/cloud/src/project/dto/create-project.dto.ts b/backend/apps/cloud/src/project/dto/create-project.dto.ts
index 922ce5642..7436c0db6 100644
--- a/backend/apps/cloud/src/project/dto/create-project.dto.ts
+++ b/backend/apps/cloud/src/project/dto/create-project.dto.ts
@@ -12,11 +12,6 @@ export class CreateProjectDTO extends ProjectOrganisationDto {
@Length(1, 50)
name: string
- @ApiProperty({
- required: false,
- })
- isCaptcha?: boolean
-
@ApiProperty({
required: false,
})
diff --git a/backend/apps/cloud/src/project/dto/project.dto.ts b/backend/apps/cloud/src/project/dto/project.dto.ts
index 66a9df2b1..dcdda1fed 100644
--- a/backend/apps/cloud/src/project/dto/project.dto.ts
+++ b/backend/apps/cloud/src/project/dto/project.dto.ts
@@ -72,11 +72,4 @@ export class ProjectDTO {
"When true, anyone on the internet (including Google) would be able to see the project's Dashboard.",
})
public: boolean
-
- @ApiProperty({
- required: false,
- description:
- 'When true, created a new Captcha Project without Analytics Projects.',
- })
- isCaptcha: boolean
}
diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.ts
index 58a8259f9..f9d8afd3a 100644
--- a/backend/apps/cloud/src/project/entity/project.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project.entity.ts
@@ -65,19 +65,11 @@ export class Project {
@Column('boolean', { default: false })
isTransferring: boolean
- // Swetrix CAPTCHA related stuff
@ApiProperty()
@Column('boolean', { default: true })
isAnalyticsProject: boolean
- @ApiProperty()
- @Column('boolean', { default: false })
- isCaptchaProject: boolean
-
- @ApiProperty()
- @Column('boolean', { default: false })
- isCaptchaEnabled: boolean
-
+ // CAPTCHA secret key - if set, CAPTCHA is enabled for this project
@ApiProperty()
@Column('varchar', { default: null, length: CAPTCHA_SECRET_KEY_LENGTH })
captchaSecretKey: string
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index f728e38bb..f482cf30c 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -331,28 +331,7 @@ export class ProjectController {
)
}
- if (projectDTO.isCaptcha) {
- if (
- _size(
- _filter(
- user.projects,
- (project: Project) => project.isCaptchaProject,
- ),
- ) >= maxProjects
- ) {
- throw new HttpException(
- `You cannot create more than ${maxProjects} projects on your account plan. Please upgrade to be able to create more projects.`,
- HttpStatus.PAYMENT_REQUIRED,
- )
- }
- } else if (
- _size(
- _filter(
- user.projects,
- (project: Project) => project.isAnalyticsProject,
- ),
- ) >= maxProjects
- ) {
+ if (_size(user.projects) >= maxProjects) {
throw new ForbiddenException(
`You cannot create more than ${maxProjects} projects on your account plan. Please upgrade to be able to create more projects.`,
)
@@ -378,15 +357,6 @@ export class ProjectController {
},
} as Project
- if (projectDTO.isCaptcha) {
- project.isCaptchaProject = true
- project.isAnalyticsProject = false
- project.isCaptchaEnabled = true
- project.captchaSecretKey = generateRandomString(
- CAPTCHA_SECRET_KEY_LENGTH,
- )
- }
-
if (projectDTO.organisationId) {
project.organisation = {
id: projectDTO.organisationId,
@@ -1789,7 +1759,6 @@ export class ProjectController {
}
}
- // @ts-expect-error
await this.projectService.update({ id }, _omit(project, ['share', 'admin']))
await deleteProjectRedis(id)
@@ -1874,12 +1843,16 @@ export class ProjectController {
this.projectService.allowedToView(project, userId, headers['x-password'])
- const [isDataExists, isErrorDataExists] = await Promise.all([
- !_isEmpty(
- await this.projectService.getPIDsWhereAnalyticsDataExists([id]),
- ),
- !_isEmpty(await this.projectService.getPIDsWhereErrorsDataExists([id])),
- ])
+ const [isDataExists, isErrorDataExists, isCaptchaDataExists] =
+ await Promise.all([
+ !_isEmpty(
+ await this.projectService.getPIDsWhereAnalyticsDataExists([id]),
+ ),
+ !_isEmpty(await this.projectService.getPIDsWhereErrorsDataExists([id])),
+ !_isEmpty(
+ await this.projectService.getPIDsWhereCaptchaDataExists([id]),
+ ),
+ ])
let role
let isAccessConfirmed = true
@@ -1917,6 +1890,7 @@ export class ProjectController {
isLocked: !!project.admin?.dashboardBlockReason,
isDataExists,
isErrorDataExists,
+ isCaptchaDataExists,
organisationId: project.organisation?.id,
role,
}
diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.ts
index a1bbd519a..6c62830d2 100644
--- a/backend/apps/cloud/src/project/project.service.ts
+++ b/backend/apps/cloud/src/project/project.service.ts
@@ -321,7 +321,6 @@ export class ProjectService {
'project.countryBlacklist',
'project.botsProtectionLevel',
'project.captchaSecretKey',
- 'project.isCaptchaEnabled',
'project.passwordHash',
'project.isPasswordProtected',
'admin.id',
@@ -1182,6 +1181,55 @@ export class ProjectService {
return _map(data, ({ pid }) => pid)
}
+ async getPIDsWhereCaptchaDataExists(projectIds: string[]): Promise<string[]> {
+ if (_isEmpty(projectIds)) {
+ return []
+ }
+
+ const params = _reduce(
+ projectIds,
+ (acc, curr, index) => ({
+ ...acc,
+ [`pid_${index}`]: curr,
+ }),
+ {},
+ )
+
+ const pids = _join(
+ _map(params, (val, key) => `{${key}:FixedString(12)}`),
+ ',',
+ )
+
+ const query = `
+ SELECT
+ pid,
+ CASE
+ WHEN EXISTS (
+ SELECT 1
+ FROM captcha
+ WHERE pid IN (${pids})
+ )
+ THEN 1
+ ELSE 0
+ END AS exists
+ FROM
+ (
+ SELECT DISTINCT pid
+ FROM captcha
+ WHERE pid IN (${pids})
+ );
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: params,
+ })
+ .then(resultSet => resultSet.json<{ pid: string }>())
+
+ return _map(data, ({ pid }) => pid)
+ }
+
async getSubscriberByEmail(projectId: string, email: string) {
return this.projectSubscriberRepository.findOne({
where: { projectId, email },
diff --git a/backend/apps/community/src/user/user.controller.ts b/backend/apps/community/src/user/user.controller.ts
index 03cab10f6..3c893a4fc 100644
--- a/backend/apps/community/src/user/user.controller.ts
+++ b/backend/apps/community/src/user/user.controller.ts
@@ -109,8 +109,6 @@ export class UserController {
botsProtectionLevel: row.projectBotsProtectionLevel,
created: row.projectCreated,
isAnalyticsProject: true,
- isCaptchaProject: false,
- isCaptchaEnabled: false,
captchaSecretKey: null,
uiHidden: false,
funnels: [],
diff --git a/backend/migrations/mysql/2025_12_06_remove_captcha_flags.sql b/backend/migrations/mysql/2025_12_06_remove_captcha_flags.sql
new file mode 100644
index 000000000..c91f049c7
--- /dev/null
+++ b/backend/migrations/mysql/2025_12_06_remove_captcha_flags.sql
@@ -0,0 +1,5 @@
+-- Remove isCaptchaProject and isCaptchaEnabled columns from project table
+-- CAPTCHA functionality is now determined by the presence of captchaSecretKey
+
+ALTER TABLE project DROP COLUMN `isCaptchaProject`;
+ALTER TABLE project DROP COLUMN `isCaptchaEnabled`;
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index 7c6a19b0d..ba1d5eed8 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -407,7 +407,7 @@ export const getProject = (pid: string, password?: string) =>
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
-export const createProject = (data: { name: string; organisationId?: string; isCaptcha?: boolean }) =>
+export const createProject = (data: { name: string; organisationId?: string }) =>
api
.post('/project', data)
.then((response): Project => response.data)
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index 926195044..20f907f0a 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -485,6 +485,7 @@ const PRODUCTION_PROJECT_TABS = {
sessions: 'sessions',
errors: 'errors',
alerts: 'alerts',
+ captcha: 'captcha',
} as const
export const PROJECT_TABS = (
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index ba854b01e..3f1270187 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -172,8 +172,6 @@ export interface Project {
active: boolean
public: boolean
isAnalyticsProject: boolean
- isCaptchaProject: boolean
- isCaptchaEnabled: boolean
captchaSecretKey: string | null
created: string
share?: ShareOwnerProject[]
@@ -190,16 +188,12 @@ export interface Project {
isLocked: boolean
isDataExists: boolean
isErrorDataExists: boolean
+ isCaptchaDataExists: boolean
botsProtectionLevel: 'off' | 'basic'
role?: Role
gscPropertyUri?: string | null
}
-export interface CaptchaProject extends Project {
- isCaptchaProject: true
- isCaptchaEnabled: true
-}
-
export interface Extension {
id: string
name: string
diff --git a/web/app/pages/Captcha/Settings/CaptchaSettings.tsx b/web/app/pages/Captcha/Settings/CaptchaSettings.tsx
deleted file mode 100644
index aa05f8476..000000000
--- a/web/app/pages/Captcha/Settings/CaptchaSettings.tsx
+++ /dev/null
@@ -1,524 +0,0 @@
-import { ExclamationTriangleIcon, XCircleIcon } from '@heroicons/react/24/outline'
-import cx from 'clsx'
-import _includes from 'lodash/includes'
-import _isEmpty from 'lodash/isEmpty'
-import _isString from 'lodash/isString'
-import _join from 'lodash/join'
-import _keys from 'lodash/keys'
-import _map from 'lodash/map'
-import _replace from 'lodash/replace'
-import _size from 'lodash/size'
-import _split from 'lodash/split'
-import { Trash2Icon } from 'lucide-react'
-import React, { useState, useEffect, memo } from 'react'
-import { useTranslation } from 'react-i18next'
-import { Link, useNavigate } from 'react-router'
-import { toast } from 'sonner'
-
-import {
- createProject,
- updateProject,
- deleteProject,
- resetProject,
- reGenerateCaptchaSecretKey,
- getProject,
-} from '~/api'
-import { withAuthentication, auth } from '~/hoc/protected'
-import { useRequiredParams } from '~/hooks/useRequiredParams'
-import { TITLE_SUFFIX } from '~/lib/constants'
-import { CaptchaProject } from '~/lib/models/Project'
-import { useAuth } from '~/providers/AuthProvider'
-import Button from '~/ui/Button'
-import Checkbox from '~/ui/Checkbox'
-import Input from '~/ui/Input'
-import Loader from '~/ui/Loader'
-import Modal from '~/ui/Modal'
-import { trackCustom } from '~/utils/analytics'
-import routes from '~/utils/routes'
-
-const MAX_NAME_LENGTH = 50
-const MAX_ORIGINS_LENGTH = 300
-const MAX_IPBLACKLIST_LENGTH = 300
-
-interface Form extends Partial<CaptchaProject> {
- isCaptcha?: boolean
- id: string
- name: string
- origins?: string | null | string[]
- ipBlacklist?: string | null | string[]
-}
-
-interface CaptchaSettingsProps {
- isSettings: boolean
-}
-
-const CaptchaSettings = ({ isSettings }: CaptchaSettingsProps) => {
- const { isLoading: authLoading } = useAuth()
-
- const { t } = useTranslation('common')
- const { id } = useRequiredParams<{
- id: string
- }>()
- const navigate = useNavigate()
- const [form, setForm] = useState<Form>({
- name: '',
- id,
- public: false,
- isCaptcha: true,
- })
- const [validated, setValidated] = useState(false)
- const [errors, setErrors] = useState<{
- name?: string
- id?: string
- origins?: string
- ipBlacklist?: string
- }>({})
- const [beenSubmitted, setBeenSubmitted] = useState(false)
- const [showDelete, setShowDelete] = useState(false)
- const [showReset, setShowReset] = useState(false)
- const [projectDeleting, setProjectDeleting] = useState(false)
- const [projectResetting, setProjectResetting] = useState(false)
- const [projectSaving, setProjectSaving] = useState(false)
- const [captchaSecretKey, setCaptchaSecretKey] = useState<string | null>(null)
- const [showRegenerateSecret, setShowRegenerateSecret] = useState(false)
-
- const [project, setProject] = useState<CaptchaProject | null>(null)
- const [isLoading, setIsLoading] = useState(false)
- const [error, setError] = useState<string | null>(null)
-
- const loadProject = async (projectId: string) => {
- if (isLoading) {
- return
- }
- setIsLoading(true)
-
- try {
- const result = (await getProject(projectId)) as CaptchaProject
- setProject(result)
- setCaptchaSecretKey(result.captchaSecretKey)
- setForm({
- ...result,
- ipBlacklist: _isString(result.ipBlacklist) ? result.ipBlacklist : _join(result.ipBlacklist, ', '),
- origins: _isString(result.origins) ? result.origins : _join(result.origins, ', '),
- })
- } catch (reason: any) {
- setError(reason)
- } finally {
- setIsLoading(false)
- }
- }
-
- useEffect(() => {
- if (authLoading) {
- return
- }
-
- loadProject(id)
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [authLoading, id])
-
- const onSubmit = async (data: Form) => {
- if (!projectSaving) {
- setProjectSaving(true)
- try {
- const formalisedData: Form = {
- ...data,
- origins: _isEmpty(data.origins)
- ? null
- : _map(_split(data.origins as string, ','), (origin) => {
- try {
- if (_includes(origin, 'localhost')) {
- return origin
- }
- return new URL(origin).host
- } catch {
- return origin
- }
- }),
- ipBlacklist: _isEmpty(data.ipBlacklist) ? null : _split(data.ipBlacklist as string, ','),
- }
- if (isSettings) {
- await updateProject(id, formalisedData as CaptchaProject)
- toast.success(t('project.settings.updated'))
- } else {
- await createProject({
- name: formalisedData.name,
- isCaptcha: true,
- })
- trackCustom('CAPTCHA_CREATED')
- toast.success(t('project.settings.created'))
- }
-
- navigate(routes.dashboard)
- } catch (reason: any) {
- toast.error(reason)
- } finally {
- setProjectSaving(false)
- }
- }
- }
-
- const onDelete = async () => {
- setShowDelete(false)
- if (!projectDeleting) {
- setProjectDeleting(true)
- try {
- await deleteProject(id)
- toast.success(t('project.settings.deleted'))
- navigate(routes.dashboard)
- } catch (reason: any) {
- toast.error(reason)
- } finally {
- setProjectDeleting(false)
- }
- }
- }
-
- const onReset = async () => {
- setShowReset(false)
- if (!projectResetting) {
- setProjectResetting(true)
- try {
- await resetProject(id)
- toast.success(t('project.settings.projectReset'))
- navigate(routes.dashboard)
- } catch (reason: any) {
- toast.error(reason)
- } finally {
- setProjectResetting(false)
- }
- }
- }
-
- const validate = () => {
- const allErrors = {} as {
- name?: string
- origins?: string
- ipBlacklist?: string
- }
-
- if (_isEmpty(form.name)) {
- allErrors.name = t('project.settings.noNameError')
- }
-
- if (_size(form.name) > MAX_NAME_LENGTH) {
- allErrors.name = t('project.settings.pxCharsError', { amount: MAX_NAME_LENGTH })
- }
-
- if (_size(form.origins) > MAX_ORIGINS_LENGTH) {
- allErrors.origins = t('project.settings.oxCharsError', { amount: MAX_ORIGINS_LENGTH })
- }
-
- if (_size(form.ipBlacklist) > MAX_IPBLACKLIST_LENGTH) {
- allErrors.ipBlacklist = t('project.settings.oxCharsError', { amount: MAX_IPBLACKLIST_LENGTH })
- }
-
- const valid = _isEmpty(_keys(allErrors))
- setErrors(allErrors)
- setValidated(valid)
- }
-
- useEffect(() => {
- validate()
- }, [form]) // eslint-disable-line
-
- const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
- const { target } = event
-
- setForm((oldForm) => ({
- ...oldForm,
- [target.name]: target.value,
- }))
- }
-
- const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
- e.preventDefault()
- e.stopPropagation()
- setBeenSubmitted(true)
-
- if (validated) {
- onSubmit(form)
- }
- }
-
- const onCancel = () => {
- navigate(isSettings ? _replace(routes.captcha, ':id', id) : routes.dashboard)
- }
-
- const title = isSettings ? `${t('project.settings.settings')} ${form.name}` : t('project.settings.create')
-
- useEffect(() => {
- let pageTitle = isSettings ? `${t('project.settings.settings')} ${form.name}` : t('project.settings.create')
- pageTitle += ` ${TITLE_SUFFIX}`
-
- document.title = pageTitle
- }, [form, t, isSettings])
-
- const onRegenerateSecretKey = async () => {
- try {
- const res = await reGenerateCaptchaSecretKey(id)
- setCaptchaSecretKey(res)
- } catch (reason: any) {
- toast.error(reason)
- }
- }
-
- if (isLoading || isLoading === null || !project) {
- return (
- <div className='flex min-h-min-footer flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900'>
- <Loader />
- </div>
- )
- }
-
- if (error && !isLoading) {
- return (
- <div className='min-h-page bg-gray-50 px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8 dark:bg-slate-900'>
- <div className='mx-auto max-w-max'>
- <main className='sm:flex'>
- <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
- <div className='sm:ml-6'>
- <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>
- <h1 className='text-4xl font-extrabold text-gray-900 sm:text-5xl dark:text-gray-50'>
- {t('apiNotifications.somethingWentWrong')}
- </h1>
- <p className='mt-4 text-2xl font-medium text-gray-700 dark:text-gray-200'>
- {t('apiNotifications.errorCode', { error })}
- </p>
- </div>
- <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
- <button
- type='button'
- onClick={() => window.location.reload()}
- className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden'
- >
- {t('dashboard.reloadPage')}
- </button>
- <Link
- to={routes.contact}
- className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'
- >
- {t('notFoundPage.support')}
- </Link>
- </div>
- </div>
- </main>
- </div>
- </div>
- )
- }
-
- return (
- <div
- className={cx('flex min-h-min-footer flex-col bg-gray-50 dark:bg-slate-900', {
- 'pb-40': isSettings,
- })}
- >
- <form className='mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8' onSubmit={handleSubmit}>
- <h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>{title}</h2>
- <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>{t('profileSettings.general')}</h3>
- <Input
- name='name'
- label={t('project.captcha.settings.name')}
- value={form.name}
- placeholder='My awesome project'
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.name : null}
- />
- {isSettings ? (
- <>
- <Input
- name='id'
- label={t('project.captcha.settings.pid')}
- value={form.id}
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.id : null}
- disabled
- />
- <Input
- name='origins'
- label={t('project.settings.origins')}
- hint={t('project.settings.originsHint')}
- value={(form.origins as string) || ''}
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.origins : null}
- />
- <Input
- name='ipBlacklist'
- label={t('project.settings.ipBlacklist')}
- hint={t('project.settings.ipBlacklistHint')}
- value={(form.ipBlacklist as string) || ''}
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.ipBlacklist : null}
- />
- <hr className='mt-5 border-gray-200 dark:border-gray-600' />
- <h3 className='mt-2 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
- {t('profileSettings.captchaSecretKey')}
- </h3>
- {captchaSecretKey ? (
- <>
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
- {t('profileSettings.captchaSecretKeyHint')}
- </p>
- <div className='grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
- <Input
- label={t('profileSettings.captchaSecretKey')}
- name='sercretKey'
- className='mt-4'
- value={captchaSecretKey}
- disabled
- />
- </div>
- </>
- ) : (
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>{t('profileSettings.noApiKey')}</p>
- )}
- {captchaSecretKey ? (
- <Button className='mt-4' onClick={() => setShowRegenerateSecret(true)} danger large>
- {t('profileSettings.regenerateSecretKey')}
- </Button>
- ) : (
- <Button className='mt-4' onClick={onRegenerateSecretKey} primary large>
- {t('profileSettings.generateSecretKey')}
- </Button>
- )}
- <hr className='mt-5 border-gray-200 dark:border-gray-600' />
- <Checkbox
- checked={Boolean(form.active)}
- onChange={(checked) =>
- setForm((prev) => ({
- ...prev,
- active: checked,
- }))
- }
- name='active'
- classes={{
- label: 'mt-4',
- }}
- label={t('project.captcha.settings.enabled')}
- hint={t('project.captcha.settings.enabledHint')}
- />
- <Checkbox
- checked={Boolean(form.public)}
- onChange={(checked) =>
- setForm((prev) => ({
- ...prev,
- public: checked,
- }))
- }
- name='public'
- classes={{
- label: 'mt-4',
- }}
- label={t('project.settings.public')}
- hint={t('project.settings.publicHint')}
- />
- <div className='mt-8 flex flex-wrap justify-center gap-2 sm:justify-between'>
- <div className='flex flex-wrap items-center justify-center gap-2'>
- <Button
- className='border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
- onClick={onCancel}
- secondary
- regular
- >
- {t('common.cancel')}
- </Button>
- <Button type='submit' loading={projectSaving} primary regular>
- {t('common.save')}
- </Button>
- </div>
- <div className='flex flex-wrap items-center justify-center gap-2'>
- <Button
- onClick={() => !projectResetting && setShowReset(true)}
- loading={projectDeleting}
- semiDanger
- semiSmall
- >
- <>
- <Trash2Icon className='mr-1 h-5 w-5' strokeWidth={1.5} />
- {t('project.settings.reset')}
- </>
- </Button>
- <Button
- onClick={() => !projectDeleting && setShowDelete(true)}
- loading={projectDeleting}
- danger
- semiSmall
- >
- <>
- <ExclamationTriangleIcon className='mr-1 h-5 w-5' />
- {t('project.settings.delete')}
- </>
- </Button>
- </div>
- </div>
- <hr className='mt-2 border-gray-200 sm:mt-5 dark:border-gray-600' />
- </>
- ) : (
- <p className='mt-1 mb-4 text-sm text-gray-500 italic dark:text-gray-300'>
- {t('project.settings.createHint')}
- </p>
- )}
-
- {!isSettings ? (
- <div>
- <Button
- className='mr-2 border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
- onClick={onCancel}
- secondary
- regular
- >
- {t('common.cancel')}
- </Button>
- <Button type='submit' loading={projectSaving} primary regular>
- {t('common.save')}
- </Button>
- </div>
- ) : null}
- </form>
- <Modal
- onClose={() => setShowDelete(false)}
- onSubmit={onDelete}
- submitText={t('project.settings.delete')}
- closeText={t('common.close')}
- title={t('project.settings.qDelete')}
- message={t('project.settings.deleteHint')}
- submitType='danger'
- type='error'
- isOpened={showDelete}
- />
- <Modal
- onClose={() => setShowReset(false)}
- onSubmit={onReset}
- submitText={t('project.settings.reset')}
- closeText={t('common.close')}
- title={t('project.settings.qReset')}
- message={t('project.settings.resetHint')}
- submitType='danger'
- type='error'
- isOpened={showReset}
- />
- <Modal
- onClose={() => setShowRegenerateSecret(false)}
- onSubmit={() => {
- setShowRegenerateSecret(false)
- onRegenerateSecretKey()
- }}
- submitText={t('profileSettings.regenerateSecretKey')}
- closeText={t('common.close')}
- title={t('profileSettings.regenerateSecretKeyTitle')}
- submitType='danger'
- type='error'
- message={t('profileSettings.regenerateSecretKeyMessage')}
- isOpened={showRegenerateSecret}
- />
- </div>
- )
-}
-
-export default memo(withAuthentication(CaptchaSettings, auth.authenticated))
diff --git a/web/app/pages/Captcha/Settings/index.tsx b/web/app/pages/Captcha/Settings/index.tsx
deleted file mode 100644
index f75891d0e..000000000
--- a/web/app/pages/Captcha/Settings/index.tsx
+++ /dev/null
@@ -1,3 +0,0 @@
-import ProjectSettings from './CaptchaSettings'
-
-export default ProjectSettings
diff --git a/web/app/pages/Captcha/View/ViewCaptcha.helpers.tsx b/web/app/pages/Captcha/View/ViewCaptcha.helpers.tsx
deleted file mode 100644
index ddd0d5ad4..000000000
--- a/web/app/pages/Captcha/View/ViewCaptcha.helpers.tsx
+++ /dev/null
@@ -1,188 +0,0 @@
-import { LanguageIcon, ArrowRightCircleIcon } from '@heroicons/react/24/outline'
-import { area, bar } from 'billboard.js'
-import type { ChartOptions } from 'billboard.js'
-import * as d3 from 'd3'
-import dayjs from 'dayjs'
-import type i18next from 'i18next'
-import _map from 'lodash/map'
-import _size from 'lodash/size'
-import { CompassIcon, FileTextIcon, MapPinIcon, MonitorCog, TabletSmartphoneIcon } from 'lucide-react'
-
-import {
- TimeFormat,
- chartTypes,
- tbsFormatMapper,
- tbsFormatMapper24h,
- tbsFormatMapperTooltip,
- tbsFormatMapperTooltip24h,
-} from '~/lib/constants'
-import { nFormatter } from '~/utils/generic'
-
-const PANELS_ORDER = ['cc', 'br', 'os', 'dv']
-
-// function to filter the data for the chart
-const getColumns = (chart: { x: string[]; results: string[] }) => {
- const columns = [['x', ..._map(chart.x, (el) => dayjs(el).toDate())]]
- columns.push(['results', ...chart.results])
-
- return columns
-}
-
-// setting the default values for the time period dropdown
-const noRegionPeriods = ['custom', 'yesterday']
-
-// function to get the settings and data for the chart(main diagram)
-const getSettings = (
- chart: any,
- timeBucket: string,
- applyRegions: boolean,
- timeFormat: string,
- rotateXAxis: boolean,
- chartType: string,
-): ChartOptions => {
- const xAxisSize = _size(chart.x)
- let regions
-
- if (applyRegions) {
- let regionStart
-
- if (xAxisSize > 1) {
- regionStart = dayjs(chart.x[xAxisSize - 2]).toDate()
- } else {
- regionStart = dayjs(chart.x[xAxisSize - 1]).toDate()
- }
-
- regions = {
- results: [
- {
- start: regionStart,
- style: {
- dasharray: '6 2',
- },
- },
- ],
- }
- }
-
- return {
- data: {
- x: 'x',
- columns: getColumns({
- ...chart,
- }),
- types: {
- results: chartType === chartTypes.line ? area() : bar(),
- },
- colors: {
- results: '#2563EB',
- },
- // @ts-expect-error
- regions,
- },
- transition: {
- duration: 500,
- },
- resize: {
- auto: true,
- timer: false,
- },
- axis: {
- x: {
- clipPath: false,
- tick: {
- fit: true,
- rotate: rotateXAxis ? 45 : 0,
- format:
- // @ts-expect-error
- timeFormat === TimeFormat['24-hour']
- ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
- : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
- },
- localtime: timeFormat === TimeFormat['24-hour'],
- type: 'timeseries',
- },
- y: {
- tick: {
- format: (d: number) => nFormatter(d, 1),
- },
- show: true,
- inner: true,
- },
- },
- tooltip: {
- contents: (item: any, _: any, __: any, color: any) => {
- return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-800 rounded-md ring-1 ring-black/10 px-3 py-1'>
- <li class='font-semibold'>${
- timeFormat === TimeFormat['24-hour']
- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
- }</li>
- <hr class='border-gray-200 dark:border-gray-600' />
- ${_map(item, (el: { id: string; index: number; name: string; value: string; x: Date }) => {
- return `
- <li class='flex justify-between'>
- <div class='flex justify-items-start'>
- <div class='w-3 h-3 rounded-xs mt-1.5 mr-2' style=background-color:${color(el.id)}></div>
- <span>${el.name}</span>
- </div>
- <span class='pl-4'>${el.value}</span>
- </li>
- `
- }).join('')}`
- },
- },
- point: {
- focus: {
- only: xAxisSize > 1,
- },
- pattern: ['circle'],
- r: 2,
- },
- legend: {
- item: {
- tile: {
- type: 'circle',
- width: 10,
- r: 3,
- },
- },
- },
- area: {
- linearGradient: true,
- },
- padding: {
- right: rotateXAxis ? 35 : 0,
- },
- bindto: '#captchaChart',
- }
-}
-
-const typeNameMapping = (t: typeof i18next.t) => ({
- cc: t('project.mapping.cc'),
- dv: t('project.mapping.dv'),
- br: t('project.mapping.br'),
- os: t('project.mapping.os'),
-})
-
-const iconClassName = 'w-6 h-6'
-const panelIconMapping = {
- cc: <MapPinIcon className={iconClassName} strokeWidth={1.5} />,
- pg: <FileTextIcon className={iconClassName} strokeWidth={1.5} />,
- lc: <LanguageIcon className={iconClassName} />,
- ref: <ArrowRightCircleIcon className={iconClassName} />,
- dv: <TabletSmartphoneIcon className={iconClassName} strokeWidth={1.5} />,
- br: <CompassIcon className={iconClassName} strokeWidth={1.5} />,
- os: <MonitorCog className={iconClassName} strokeWidth={1.5} />,
-}
-
-// This function return date using the same format as the backend
-const getFormatDate = (date: Date) => {
- const yyyy = date.getFullYear()
- let mm: string | number = date.getMonth() + 1
- let dd: string | number = date.getDate()
- if (dd < 10) dd = `0${dd}`
- if (mm < 10) mm = `0${mm}`
- return `${yyyy}-${mm}-${dd}`
-}
-
-export { getFormatDate, panelIconMapping, typeNameMapping, noRegionPeriods, getSettings, getColumns, PANELS_ORDER }
diff --git a/web/app/pages/Captcha/View/ViewCaptcha.tsx b/web/app/pages/Captcha/View/ViewCaptcha.tsx
deleted file mode 100644
index 3ba6ac4a0..000000000
--- a/web/app/pages/Captcha/View/ViewCaptcha.tsx
+++ /dev/null
@@ -1,676 +0,0 @@
-import { GlobeAltIcon } from '@heroicons/react/24/outline'
-import billboard from 'billboard.js'
-import cx from 'clsx'
-import _filter from 'lodash/filter'
-import _find from 'lodash/find'
-import _includes from 'lodash/includes'
-import _isEmpty from 'lodash/isEmpty'
-import _keys from 'lodash/keys'
-import _map from 'lodash/map'
-import _replace from 'lodash/replace'
-import { DownloadIcon, RotateCw, SettingsIcon } from 'lucide-react'
-import { useState, useEffect, useMemo, useRef } from 'react'
-import { useTranslation } from 'react-i18next'
-import { Link, LinkProps, useSearchParams } from 'react-router'
-import { ClientOnly } from 'remix-utils/client-only'
-
-import { getCaptchaData } from '~/api'
-import EventsRunningOutBanner from '~/components/EventsRunningOutBanner'
-import useSize from '~/hooks/useSize'
-import {
- captchaTbPeriodPairs,
- timeBucketToDays,
- MAX_MONTHS_IN_PAST,
- TimeFormat,
- chartTypes,
- TITLE_SUFFIX,
- BROWSER_LOGO_MAP,
- OS_LOGO_MAP,
- OS_LOGO_MAP_DARK,
- DEFAULT_TIMEZONE,
- VALID_PERIODS,
- type Period,
- TBPeriodPairsProps,
- TimeBucket,
- VALID_TIME_BUCKETS,
-} from '~/lib/constants'
-import Filters from '~/pages/Project/View/components/Filters'
-import NoEvents from '~/pages/Project/View/components/NoEvents'
-import TBPeriodSelector from '~/pages/Project/View/components/TBPeriodSelector'
-import { Filter } from '~/pages/Project/View/interfaces/traffic'
-import { Panel } from '~/pages/Project/View/Panels'
-import { parseFilters } from '~/pages/Project/View/utils/filters'
-import { ViewProjectContext } from '~/pages/Project/View/ViewProject'
-import { deviceIconMapping, onCSVExportClick } from '~/pages/Project/View/ViewProject.helpers'
-import { useAuth } from '~/providers/AuthProvider'
-import { useCurrentProject } from '~/providers/CurrentProjectProvider'
-import { useTheme } from '~/providers/ThemeProvider'
-import DatePicker from '~/ui/Datepicker'
-import Dropdown from '~/ui/Dropdown'
-import Loader from '~/ui/Loader'
-import LoadingBar from '~/ui/LoadingBar'
-import routes from '~/utils/routes'
-
-import CCRow from '../../Project/View/components/CCRow'
-
-import {
- getFormatDate,
- panelIconMapping,
- typeNameMapping,
- noRegionPeriods,
- getSettings,
- getColumns,
- PANELS_ORDER,
-} from './ViewCaptcha.helpers'
-
-const PageLoader = () => (
- <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
- <Loader />
- </div>
-)
-
-const ViewCaptcha = () => {
- const { id, project, preferences, updatePreferences } = useCurrentProject()
-
- const { user, isLoading: authLoading } = useAuth()
- const { theme } = useTheme()
-
- const [searchParams, setSearchParams] = useSearchParams()
-
- const {
- t,
- i18n: { language },
- } = useTranslation('common')
- const dashboardRef = useRef(null)
-
- const [panelsData, setPanelsData] = useState<any>({})
- const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)
- const [analyticsLoading, setAnalyticsLoading] = useState(true)
-
- const period = useMemo<Period>(() => {
- const urlPeriod = searchParams.get('period') as Period
-
- if (VALID_PERIODS.includes(urlPeriod)) {
- return urlPeriod
- }
-
- return preferences.period || '7d'
- }, [searchParams, preferences.period])
-
- const [chartData, setChartData] = useState<any>({})
- const [dataLoading, setDataLoading] = useState(false)
-
- const filters = useMemo<Filter[]>(() => {
- return parseFilters(searchParams)
- }, [searchParams])
-
- const tnMapping = typeNameMapping(t)
- const refCalendar = useRef(null)
-
- const dateRange = useMemo<Date[] | null>(() => {
- if (period !== 'custom') {
- return null
- }
-
- let initialDateRange: Date[] | null = preferences.rangeDate
- ? [new Date(preferences.rangeDate[0]), new Date(preferences.rangeDate[1])]
- : null
-
- const from = searchParams.get('from')
- const to = searchParams.get('to')
-
- if (from && to) {
- const fromDate = new Date(from)
- const toDate = new Date(to)
-
- if (fromDate.getDate() && toDate.getDate()) {
- initialDateRange = [fromDate, toDate]
- }
- }
-
- return initialDateRange
- }, [period, searchParams, preferences.rangeDate])
-
- const periodPairs = useMemo<TBPeriodPairsProps[]>(() => {
- let tbs = null
-
- if (dateRange) {
- const days = Math.ceil(Math.abs(dateRange[1].getTime() - dateRange[0].getTime()) / (1000 * 3600 * 24))
-
- for (const index in timeBucketToDays) {
- if (timeBucketToDays[index].lt >= days) {
- tbs = timeBucketToDays[index].tb
- }
- }
- }
-
- return captchaTbPeriodPairs(t, tbs, dateRange, language)
- }, [t, language, dateRange])
-
- const timeBucket = useMemo<TimeBucket>(() => {
- let _timeBucket = preferences.timeBucket || periodPairs[4].tbs[1]
- const urlTimeBucket = searchParams.get('timeBucket') as TimeBucket
- const currentPeriodPair = _find(periodPairs, (el) => el.period === period)
-
- // If the time bucket from preferences is not compatible with the current period, use the first time bucket of the period
- if (currentPeriodPair && !currentPeriodPair.tbs.includes(urlTimeBucket)) {
- _timeBucket = currentPeriodPair.tbs[0]
- }
-
- // Or use the time bucket from the URL if it's compatible with the current period
- if (VALID_TIME_BUCKETS.includes(urlTimeBucket)) {
- if (currentPeriodPair?.tbs?.includes(urlTimeBucket)) {
- _timeBucket = urlTimeBucket
- }
- }
-
- if (dateRange) {
- const days = Math.ceil(Math.abs(dateRange[1].getTime() - dateRange[0].getTime()) / (1000 * 3600 * 24))
-
- for (const index in timeBucketToDays) {
- if (timeBucketToDays[index].lt >= days) {
- if (!timeBucketToDays[index].tb?.includes(_timeBucket)) {
- _timeBucket = timeBucketToDays[index].tb[0]
- }
-
- break
- }
- }
- }
-
- return _timeBucket
- }, [searchParams, preferences.timeBucket, periodPairs, period, dateRange])
-
- const activePeriod = useMemo(() => _find(periodPairs, (p) => p.period === period), [period, periodPairs])
-
- const timeFormat = useMemo<'12-hour' | '24-hour'>(() => user?.timeFormat || TimeFormat['12-hour'], [user])
- const [ref, size] = useSize() as any
- const rotateXAxias = useMemo(() => size.width > 0 && size.width < 500, [size])
- const [mainChart, setMainChart] = useState<any>(null)
-
- const { timezone = DEFAULT_TIMEZONE } = user || {}
-
- useEffect(() => {
- if (!project) {
- return
- }
-
- let pageTitle = project.name || t('titles.main')
-
- pageTitle += ` ${TITLE_SUFFIX}`
-
- document.title = pageTitle
- }, [project, t])
-
- const dataNames = useMemo(() => {
- return {
- results: t('project.results'),
- }
- }, [t])
-
- const loadCaptcha = async () => {
- setDataLoading(true)
-
- try {
- let data
- let from
- let to
-
- if (dateRange) {
- from = getFormatDate(dateRange[0])
- to = getFormatDate(dateRange[1])
- }
-
- if (period === 'custom' && dateRange) {
- data = await getCaptchaData(id, timeBucket, '', filters, from, to)
- } else {
- data = await getCaptchaData(id, timeBucket, period, filters, '', '')
- }
-
- if (_isEmpty(data)) {
- setAnalyticsLoading(false)
- setDataLoading(false)
- setIsPanelsDataEmpty(true)
- return
- }
-
- const { chart, params, customs, timeBucket: timeBucketFromResponse } = data
-
- let newTimebucket = timeBucket
-
- if (period === 'all' && !_isEmpty(timeBucketFromResponse)) {
- newTimebucket = _includes(timeBucketFromResponse, timeBucket) ? timeBucket : timeBucketFromResponse[0]
-
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.set('timeBucket', newTimebucket)
- setSearchParams(newSearchParams)
- }
-
- if (_isEmpty(params)) {
- setIsPanelsDataEmpty(true)
- } else {
- const applyRegions = !_includes(noRegionPeriods, activePeriod?.period)
- const bbSettings: any = getSettings(
- chart,
- newTimebucket,
- applyRegions,
- timeFormat,
- rotateXAxias,
- chartTypes.line,
- )
- setChartData(chart)
-
- setPanelsData({
- types: _keys(params),
- data: params,
- customs,
- })
-
- setIsPanelsDataEmpty(false)
- setMainChart(() => {
- const generete = billboard.generate(bbSettings)
- generete.data.names(dataNames)
- return generete
- })
- }
-
- setAnalyticsLoading(false)
- setDataLoading(false)
- } catch (reason) {
- setAnalyticsLoading(false)
- setDataLoading(false)
- setIsPanelsDataEmpty(true)
- console.error('[ERROR](loadAnalytics) Loading analytics data failed:', reason)
- }
- }
-
- useEffect(() => {
- if (mainChart) {
- mainChart.load({
- columns: getColumns({ ...chartData }),
- })
- }
- }, [chartData, mainChart])
-
- useEffect(() => {
- if (authLoading || !project) return
-
- loadCaptcha()
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [filters, authLoading, project, dateRange, period, timeBucket])
-
- const getFilterLink = (column: string, value: string | null): LinkProps['to'] => {
- const isFilterActive = filters.findIndex((filter) => filter.column === column && filter.filter === value) >= 0
-
- const newSearchParams = new URLSearchParams(searchParams.toString())
- let searchString = ''
-
- if (isFilterActive) {
- newSearchParams.delete(column, value ?? 'null')
- searchString = newSearchParams.toString()
- } else {
- newSearchParams.append(column, value ?? 'null')
- searchString = newSearchParams.toString()
- }
-
- return {
- search: searchString,
- }
- }
-
- const refreshStats = () => {
- if (authLoading || dataLoading) {
- return
- }
-
- loadCaptcha()
- }
-
- // We can assume period provided is never custom, as it's handled separately in the Flatpickr callback function
- const updatePeriod = ({ period: newPeriod }: { period: Period }) => {
- if (period === newPeriod) {
- return
- }
-
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.delete('from')
- newSearchParams.delete('to')
- newSearchParams.set('period', newPeriod)
-
- updatePreferences({
- period: newPeriod,
- rangeDate: undefined,
- })
-
- setSearchParams(newSearchParams)
- }
-
- const resetDateRange = () => {
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.delete('from')
- newSearchParams.delete('to')
- setSearchParams(newSearchParams)
- }
-
- const updateTimebucket = (newTimebucket: TimeBucket) => {
- if (dataLoading) {
- return
- }
-
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.set('timeBucket', newTimebucket)
- setSearchParams(newSearchParams)
-
- updatePreferences({
- timeBucket: newTimebucket,
- })
- }
-
- const exportTypes = [
- {
- label: t('project.asCSV'),
- onClick: () => {
- return onCSVExportClick(panelsData, id, tnMapping, language)
- },
- },
- ]
-
- if (authLoading || !project) {
- return <PageLoader />
- }
-
- return (
- <ClientOnly fallback={<PageLoader />}>
- {() => (
- <ViewProjectContext.Provider
- value={{
- // States
- timezone,
- dateRange,
- isLoading: authLoading,
- timeBucket,
- period,
- activePeriod,
- periodPairs,
- timeFormat,
- size,
- dataLoading,
- activeTab: 'traffic',
- filters,
- customPanelTabs: [],
-
- // Functions
- updatePeriod,
- updateTimebucket,
-
- // Refs
- refCalendar,
- }}
- >
- <>
- {dataLoading ? <LoadingBar /> : null}
- <EventsRunningOutBanner />
- <div ref={ref} className='bg-gray-50 dark:bg-slate-900'>
- <div className='mx-auto min-h-min-footer w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8' ref={dashboardRef}>
- <div className='mt-2 flex flex-col items-center justify-between lg:flex-row lg:items-start'>
- <h2 className='text-xl font-bold break-words break-all text-gray-900 dark:text-gray-50'>
- {project.name}
- </h2>
- <div className='lg:mt- mx-auto mt-3 flex w-full max-w-[420px] flex-wrap items-center justify-center gap-x-2 gap-y-1 sm:mx-0 sm:w-auto sm:max-w-none sm:flex-nowrap sm:justify-between'>
- <button
- type='button'
- title={t('project.refreshStats')}
- onClick={refreshStats}
- className={cx(
- 'relative rounded-md border border-gray-50/0 bg-gray-50 p-2 text-sm font-medium transition-colors hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:bg-slate-900 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
- {
- 'cursor-not-allowed opacity-50': authLoading || dataLoading,
- },
- )}
- >
- <RotateCw className='h-5 w-5 text-gray-700 dark:text-gray-50' />
- </button>
- <Dropdown
- header={t('project.exportData')}
- items={exportTypes}
- title={[<DownloadIcon key='download-icon' className='h-5 w-5' strokeWidth={1.5} />]}
- labelExtractor={(item) => item.label}
- keyExtractor={(item) => item.label}
- onSelect={(item) => item.onClick()}
- className={cx({ hidden: isPanelsDataEmpty || analyticsLoading })}
- chevron='mini'
- buttonClassName='!p-2 rounded-md hover:bg-white border border-gray-50/0 hover:border-gray-300 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:z-10 focus:outline-hidden focus:ring-1 focus:ring-indigo-500 focus:dark:ring-gray-200'
- headless
- />
- <div className='flex items-center'>
- <TBPeriodSelector
- activePeriod={activePeriod}
- items={_filter(periodPairs, (item) => !_includes(['all', '1h'], item.period))}
- title={activePeriod?.label}
- onSelect={(pair) => {
- if (pair.isCustomDate) {
- setTimeout(() => {
- // @ts-expect-error
- refCalendar.current.openCalendar()
- }, 100)
- } else {
- resetDateRange()
- updatePeriod(pair)
- }
- }}
- />
- <DatePicker
- ref={refCalendar}
- onChange={([from, to]) => {
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.set('from', from.toISOString())
- newSearchParams.set('to', to.toISOString())
- newSearchParams.set('period', 'custom')
- setSearchParams(newSearchParams)
- }}
- value={dateRange || []}
- maxDateMonths={MAX_MONTHS_IN_PAST}
- />
- </div>
- {project.role === 'admin' || project.role === 'owner' ? (
- <Link
- to={_replace(routes.captcha_settings, ':id', id)}
- className='flex rounded-md border border-transparent p-2 px-3 text-sm font-medium text-gray-700 transition-colors hover:border-gray-300 hover:bg-white hover:text-gray-600 focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 dark:hover:text-gray-200 focus:dark:ring-gray-200'
- >
- <>
- <SettingsIcon className='mr-1 h-5 w-5' strokeWidth={1.5} />
- {t('common.settings')}
- </>
- </Link>
- ) : null}
- </div>
- </div>
- {analyticsLoading ? <Loader /> : null}
- {isPanelsDataEmpty ? <NoEvents filters={filters} /> : null}
- <div className={cx('pt-4', { hidden: isPanelsDataEmpty || analyticsLoading })}>
- <div className='h-80'>
- <div className='h-80 [&_svg]:!overflow-visible' id='captchaChart' />
- </div>
- <Filters tnMapping={tnMapping} />
- {dataLoading ? (
- <div className='static mt-4 !bg-transparent' id='loader'>
- <div className='loader-head dark:!bg-slate-800'>
- <div className='first dark:!bg-slate-600' />
- <div className='second dark:!bg-slate-600' />
- </div>
- </div>
- ) : null}
- <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>
- {!_isEmpty(panelsData.types)
- ? _map(PANELS_ORDER, (type: keyof typeof tnMapping) => {
- const panelName = tnMapping[type]
- const panelIcon = panelIconMapping[type]
-
- if (type === 'cc') {
- const rowMapper = (entry: any) => {
- const { name: entryName, cc } = entry
-
- if (cc) {
- return <CCRow cc={cc} name={entryName} language={language} />
- }
-
- return <CCRow cc={entryName} language={language} />
- }
-
- return (
- <Panel
- key={type}
- icon={panelIcon}
- id={type}
- getFilterLink={getFilterLink}
- name={panelName}
- data={panelsData.data[type]}
- rowMapper={rowMapper}
- activeTabId={type}
- />
- )
- }
-
- if (type === 'dv') {
- return (
- <Panel
- key={type}
- icon={panelIcon}
- id={type}
- getFilterLink={getFilterLink}
- name={panelName}
- data={panelsData.data[type]}
- rowMapper={(entry: { name: keyof typeof deviceIconMapping }) => {
- const { name: entryName } = entry
-
- const icon = deviceIconMapping[entryName]
-
- if (!icon) {
- return entryName
- }
-
- return (
- <>
- {icon}
- &nbsp;
- {entryName}
- </>
- )
- }}
- capitalize
- activeTabId={type}
- />
- )
- }
-
- if (type === 'br') {
- const rowMapper = (entry: any) => {
- const { name: entryName } = entry
- // @ts-expect-error
- const logoUrl = BROWSER_LOGO_MAP[entryName]
-
- if (!logoUrl) {
- return (
- <>
- <GlobeAltIcon className='h-5 w-5' />
- &nbsp;
- {entryName}
- </>
- )
- }
-
- return (
- <>
- <img src={logoUrl} className='h-5 w-5' alt='' />
- &nbsp;
- {entryName}
- </>
- )
- }
-
- return (
- <Panel
- key={type}
- icon={panelIcon}
- id={type}
- getFilterLink={getFilterLink}
- name={panelName}
- data={panelsData.data[type]}
- rowMapper={rowMapper}
- activeTabId={type}
- />
- )
- }
-
- if (type === 'os') {
- const rowMapper = (entry: any) => {
- const { name: entryName } = entry
- // @ts-expect-error
- const logoPathLight = OS_LOGO_MAP[entryName]
- // @ts-expect-error
- const logoPathDark = OS_LOGO_MAP_DARK[entryName]
-
- let logoPath = theme === 'dark' ? logoPathDark : logoPathLight
- logoPath ||= logoPathLight
-
- if (!logoPath) {
- return (
- <>
- <GlobeAltIcon className='h-5 w-5' />
- &nbsp;
- {entryName}
- </>
- )
- }
-
- const logoUrl = `/${logoPath}`
-
- return (
- <>
- <img src={logoUrl} className='h-5 w-5 dark:fill-gray-50' alt='' />
- &nbsp;
- {entryName}
- </>
- )
- }
-
- return (
- <Panel
- key={type}
- icon={panelIcon}
- id={type}
- getFilterLink={getFilterLink}
- name={panelName}
- data={panelsData.data[type]}
- rowMapper={rowMapper}
- activeTabId={type}
- />
- )
- }
-
- return (
- <Panel
- key={type}
- icon={panelIcon}
- id={type}
- getFilterLink={getFilterLink}
- name={panelName}
- data={panelsData.data[type]}
- activeTabId={type}
- />
- )
- })
- : null}
- </div>
- </div>
- </div>
- </div>
- </>
- </ViewProjectContext.Provider>
- )}
- </ClientOnly>
- )
-}
-
-export default ViewCaptcha
diff --git a/web/app/pages/Captcha/View/index.tsx b/web/app/pages/Captcha/View/index.tsx
deleted file mode 100644
index ec73a2c1b..000000000
--- a/web/app/pages/Captcha/View/index.tsx
+++ /dev/null
@@ -1,3 +0,0 @@
-import ViewCaptcha from './ViewCaptcha'
-
-export default ViewCaptcha
diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsx
index e5e9b837c..e8ac7f252 100644
--- a/web/app/pages/Dashboard/Dashboard.tsx
+++ b/web/app/pages/Dashboard/Dashboard.tsx
@@ -367,10 +367,7 @@ const Dashboard = () => {
}
const updateAllOverallStats = async () => {
- await Promise.all([
- updateOverallStats(projects.filter((p) => p.isAnalyticsProject).map((p) => p.id)),
- updateOverallStatsCaptcha(projects.filter((p) => p.isCaptchaProject).map((p) => p.id)),
- ])
+ await updateOverallStats(projects.map((p) => p.id))
}
updateLiveVisitors()
diff --git a/web/app/pages/Dashboard/ProjectCard.tsx b/web/app/pages/Dashboard/ProjectCard.tsx
index 0e459a6ee..c431d7970 100644
--- a/web/app/pages/Dashboard/ProjectCard.tsx
+++ b/web/app/pages/Dashboard/ProjectCard.tsx
@@ -130,10 +130,6 @@ export const ProjectCard = ({
list.push({ colour: 'yellow', label: t('common.pending') })
}
- if (project.isCaptchaProject) {
- list.push({ colour: 'indigo', label: t('dashboard.captcha') })
- }
-
if (isTransferring) {
list.push({ colour: 'indigo', label: t('common.transferring') })
}
@@ -149,18 +145,7 @@ export const ProjectCard = ({
}
return list
- }, [
- t,
- active,
- isTransferring,
- isPublic,
- organisation,
- share,
- project.isAccessConfirmed,
- project.role,
- project.isCaptchaProject,
- shareId,
- ])
+ }, [t, active, isTransferring, isPublic, organisation, share, project.isAccessConfirmed, project.role, shareId])
const onAccept = async () => {
try {
@@ -215,7 +200,7 @@ export const ProjectCard = ({
return (
<Link
to={{
- pathname: _replace(project.isCaptchaProject ? routes.captcha : routes.project, ':id', id),
+ pathname: _replace(routes.project, ':id', id),
search: searchParams,
}}
onClick={onElementClick}
@@ -252,7 +237,7 @@ export const ProjectCard = ({
<div className={cx('flex shrink-0 gap-5', viewMode === 'list' ? 'ml-4' : 'mt-4 px-4 pb-4')}>
{isHostnameNavigationEnabled ? (
<MiniCard
- labelTKey={project.isCaptchaProject ? 'dashboard.captchaEvents' : 'dashboard.pageviews'}
+ labelTKey='dashboard.pageviews'
// @ts-expect-error
total={project?.trafficStats?.visits}
percChange={
@@ -264,7 +249,7 @@ export const ProjectCard = ({
/>
) : (
<MiniCard
- labelTKey={project.isCaptchaProject ? 'dashboard.captchaEvents' : 'dashboard.pageviews'}
+ labelTKey='dashboard.pageviews'
total={live === 'N/A' ? 'N/A' : (overallStats?.current.all ?? null)}
percChange={
live === 'N/A'
@@ -273,7 +258,7 @@ export const ProjectCard = ({
}
/>
)}
- {project.isAnalyticsProject ? <MiniCard labelTKey='dashboard.liveVisitors' total={live} /> : null}
+ <MiniCard labelTKey='dashboard.liveVisitors' total={live} />
</div>
{project.role !== 'owner' && !project.isAccessConfirmed ? (
<Modal
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index ca6431274..f68369dd8 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -21,6 +21,7 @@ import {
ChevronLeftIcon,
PuzzleIcon,
StickyNoteIcon,
+ ShieldCheckIcon,
} from 'lucide-react'
import React, { useState, useEffect, useMemo, useCallback } from 'react'
import { Trans, useTranslation } from 'react-i18next'
@@ -42,6 +43,7 @@ import {
getGSCProperties,
setGSCProperty,
disconnectGSC,
+ reGenerateCaptchaSecretKey,
} from '~/api'
import { withAuthentication, auth } from '~/hoc/protected'
import { useRequiredParams } from '~/hooks/useRequiredParams'
@@ -316,7 +318,16 @@ const ProjectSettings = () => {
const [error, setError] = useState<string | null>(null)
const [searchParams, setSearchParams] = useSearchParams()
- type SettingsTab = 'general' | 'shields' | 'access' | 'integrations' | 'emails' | 'people' | 'annotations' | 'danger'
+ type SettingsTab =
+ | 'general'
+ | 'shields'
+ | 'access'
+ | 'captcha'
+ | 'integrations'
+ | 'emails'
+ | 'people'
+ | 'annotations'
+ | 'danger'
const tabs = useMemo(
() =>
@@ -324,6 +335,12 @@ const ProjectSettings = () => {
{ id: 'general', label: t('project.settings.tabs.general'), icon: Settings2Icon, visible: true },
{ id: 'access', label: t('project.settings.tabs.access'), icon: LockIcon, visible: true },
{ id: 'shields', label: t('project.settings.tabs.shields'), icon: ShieldIcon, visible: true },
+ {
+ id: 'captcha',
+ label: t('project.settings.tabs.captcha'),
+ icon: ShieldCheckIcon,
+ visible: !isSelfhosted,
+ },
{
id: 'integrations',
label: t('project.settings.tabs.integrations'),
@@ -360,6 +377,10 @@ const ProjectSettings = () => {
const [gscProperties, setGscProperties] = useState<{ siteUrl: string; permissionLevel?: string }[]>([])
const [gscEmail, setGscEmail] = useState<string | null>(null)
+ // CAPTCHA state
+ const [captchaSecretKey, setCaptchaSecretKey] = useState<string | null>(null)
+ const [showRegenerateSecret, setShowRegenerateSecret] = useState(false)
+
// for reset data via filters
const [activeFilter, setActiveFilter] = useState<string[]>([])
const [filterType, setFilterType] = useState('')
@@ -414,6 +435,7 @@ const ProjectSettings = () => {
try {
const result = await getProject(projectId)
setProject(result)
+ setCaptchaSecretKey(result.captchaSecretKey)
setForm({
...result,
ipBlacklist: _isString(result.ipBlacklist) ? result.ipBlacklist : _join(result.ipBlacklist, ', '),
@@ -960,6 +982,62 @@ const ProjectSettings = () => {
</div>
) : null}
+ {activeTab === 'captcha' ? (
+ <div>
+ <div className='rounded-lg border border-gray-200 p-4 dark:border-slate-800'>
+ <h3 className='mb-2 text-lg font-medium text-gray-900 dark:text-gray-50'>
+ {t('project.settings.captcha.title')}
+ </h3>
+ <p className='mb-4 text-sm text-gray-600 dark:text-gray-300'>
+ {t('project.settings.captcha.description')}
+ </p>
+
+ {captchaSecretKey ? (
+ <>
+ <Input
+ label={t('project.settings.captcha.secretKey')}
+ name='captchaSecretKey'
+ className='mt-4 lg:w-1/2'
+ value={captchaSecretKey}
+ disabled
+ />
+ <div className='mt-4 flex gap-2'>
+ <Button type='button' onClick={() => setShowRegenerateSecret(true)} danger regular>
+ {t('project.settings.captcha.regenerateKey')}
+ </Button>
+ </div>
+ </>
+ ) : (
+ <>
+ <p className='mb-4 text-sm text-gray-600 dark:text-gray-300'>
+ {t('project.settings.captcha.noKeyGenerated')}
+ </p>
+ <Button
+ type='button'
+ onClick={async () => {
+ try {
+ const newKey = await reGenerateCaptchaSecretKey(id)
+ setCaptchaSecretKey(newKey)
+ toast.success(t('project.settings.captcha.keyGenerated'))
+ } catch (reason: any) {
+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
+ }
+ }}
+ primary
+ regular
+ >
+ {t('project.settings.captcha.generateKey')}
+ </Button>
+ </>
+ )}
+
+ <hr className='-mx-4 mt-6 mb-4 border-gray-200 dark:border-slate-800' />
+
+ <p className='text-sm text-gray-600 dark:text-gray-300'>{t('project.settings.captcha.learnMore')}</p>
+ </div>
+ </div>
+ ) : null}
+
{activeTab === 'danger' ? (
<DangerZone
setShowTransfer={setShowTransfer}
@@ -1063,6 +1141,26 @@ const ProjectSettings = () => {
isOpened={showTransfer}
onSubmit={onTransfer}
/>
+ <Modal
+ onClose={() => setShowRegenerateSecret(false)}
+ onSubmit={async () => {
+ try {
+ const newKey = await reGenerateCaptchaSecretKey(id)
+ setCaptchaSecretKey(newKey)
+ setShowRegenerateSecret(false)
+ toast.success(t('project.settings.captcha.keyRegenerated'))
+ } catch (reason: any) {
+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
+ }
+ }}
+ submitText={t('project.settings.captcha.regenerateKey')}
+ closeText={t('common.cancel')}
+ title={t('project.settings.captcha.regenerateKeyTitle')}
+ message={t('project.settings.captcha.regenerateKeyWarning')}
+ submitType='danger'
+ type='error'
+ isOpened={showRegenerateSecret}
+ />
</div>
)
}
diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsx
index b48b7b43a..a91365954 100644
--- a/web/app/pages/Project/View/ViewProject.helpers.tsx
+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx
@@ -1801,6 +1801,145 @@ export const getDeviceRowMapper = (activeTab: string, theme: string, t: typeof i
return undefined
}
+const getSettingsCaptcha = (
+ chart: { x: string[]; results: number[] },
+ timeBucket: string,
+ timeFormat: string,
+ rotateXAxis: boolean,
+ chartType: string,
+): ChartOptions => {
+ const xAxisSize = _size(chart.x)
+
+ // Build columns directly since getColumns doesn't handle 'results'
+ const columns: any[] = [
+ ['x', ..._map(chart.x, (el) => dayjs(el).toDate())],
+ ['results', ...chart.results],
+ ]
+
+ const allYValues: number[] = []
+ if (chart.results) {
+ allYValues.push(...chart.results.filter((n: any) => n !== undefined && n !== null))
+ }
+
+ const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+
+ let regionStart
+
+ if (xAxisSize > 1) {
+ regionStart = dayjs(chart.x[xAxisSize - 2]).toDate()
+ } else {
+ regionStart = dayjs(chart.x[xAxisSize - 1]).toDate()
+ }
+
+ return {
+ data: {
+ x: 'x',
+ columns,
+ types: {
+ results: chartType === chartTypes.line ? area() : bar(),
+ },
+ colors: {
+ results: '#16a34a',
+ },
+ regions: {
+ results: [
+ {
+ // @ts-expect-error
+ start: regionStart,
+ style: {
+ dasharray: '6 2',
+ },
+ },
+ ],
+ },
+ },
+ grid: {
+ y: {
+ show: true,
+ },
+ },
+ transition: {
+ duration: 200,
+ },
+ resize: {
+ auto: true,
+ timer: false,
+ },
+ axis: {
+ x: {
+ clipPath: false,
+ tick: {
+ fit: true,
+ rotate: rotateXAxis ? 45 : 0,
+ format:
+ // @ts-expect-error
+ timeFormat === TimeFormat['24-hour']
+ ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
+ : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
+ },
+ localtime: timeFormat === TimeFormat['24-hour'],
+ type: 'timeseries',
+ },
+ y: {
+ tick: {
+ format: (d: number) => nFormatter(d, 1),
+ values: optimalTicks,
+ },
+ show: true,
+ inner: true,
+ },
+ },
+ tooltip: {
+ contents: (item: any, _: any, __: any, color: any) => {
+ return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-800 rounded-md ring-1 ring-black/10 px-3 py-1'>
+ <li class='font-semibold'>${
+ timeFormat === TimeFormat['24-hour']
+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
+ }</li>
+ <hr class='border-gray-200 dark:border-gray-600' />
+ ${_map(
+ item,
+ (el: { id: string; index: number; name: string; value: string; x: Date }) => `
+ <li class='flex justify-between'>
+ <div class='flex justify-items-start'>
+ <div class='w-3 h-3 rounded-xs mt-1.5 mr-2' style=background-color:${color(el.id)}></div>
+ <span>${el.name}</span>
+ </div>
+ <span class='pl-4'>${el.value}</span>
+ </li>
+ `,
+ ).join('')}`
+ },
+ },
+ point:
+ chartType === chartTypes.bar
+ ? {}
+ : {
+ focus: {
+ only: xAxisSize > 1,
+ },
+ pattern: ['circle'],
+ r: 2,
+ },
+ legend: {
+ item: {
+ tile: {
+ type: 'circle',
+ width: 10,
+ r: 3,
+ },
+ },
+ },
+ area: {
+ linearGradient: true,
+ },
+ bar: {
+ linearGradient: true,
+ },
+ }
+}
+
export {
getFormatDate,
panelIconMapping,
@@ -1819,4 +1958,5 @@ export {
SHORTCUTS_TIMEBUCKETS_LISTENERS,
CHART_MEASURES_MAPPING_PERF,
getSettingsError,
+ getSettingsCaptcha,
}
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 38383e316..f04239442 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -38,6 +38,7 @@ import {
EyeIcon,
PercentIcon,
KeyboardIcon,
+ ShieldCheckIcon,
} from 'lucide-react'
import React, {
useState,
@@ -176,6 +177,7 @@ import { ErrorChart } from './components/ErrorChart'
import { ErrorDetails } from './components/ErrorDetails'
import { Errors } from './components/Errors'
import Filters from './components/Filters'
+const CaptchaView = lazy(() => import('./components/CaptchaView'))
import { FunnelChart } from './components/FunnelChart'
import FunnelsList from './components/FunnelsList'
const InteractiveMap = lazy(() => import('./components/InteractiveMap'))
@@ -400,6 +402,7 @@ interface ViewProjectContextType {
activeTab: keyof typeof PROJECT_TABS
filters: Filter[]
customPanelTabs: CustomTab[]
+ captchaRefreshTrigger: number
// Functions
updatePeriod: (newPeriod: { period: Period; label?: string }) => void
@@ -423,6 +426,7 @@ const defaultViewProjectContext: ViewProjectContextType = {
activeTab: PROJECT_TABS.traffic,
filters: [],
customPanelTabs: [],
+ captchaRefreshTrigger: 0,
updatePeriod: () => {},
updateTimebucket: (_newTimebucket) => {},
refCalendar: { current: null } as any,
@@ -533,6 +537,7 @@ const ViewProjectContent = () => {
// prevY2NeededRef removed - no longer needed with new chart management
const [dataLoading, setDataLoading] = useState(false)
const [isAutoRefreshing, setIsAutoRefreshing] = useState(false)
+ const [captchaRefreshTrigger, setCaptchaRefreshTrigger] = useState(0)
const [activeChartMetrics, setActiveChartMetrics] = useState<Record<keyof typeof CHART_METRICS_MAPPING, boolean>>({
[CHART_METRICS_MAPPING.unique]: true,
[CHART_METRICS_MAPPING.views]: false,
@@ -1513,6 +1518,11 @@ const ViewProjectContent = () => {
label: t('dashboard.alerts'),
icon: BellRingIcon,
},
+ {
+ id: PROJECT_TABS.captcha,
+ label: t('common.captcha'),
+ icon: ShieldCheckIcon,
+ },
...adminTabs,
].filter((x) => !!x)
@@ -2648,6 +2658,11 @@ const ViewProjectContent = () => {
return
}
+ if (activeTab === PROJECT_TABS.captcha) {
+ setCaptchaRefreshTrigger((prev) => prev + 1)
+ return
+ }
+
loadAnalytics()
}
},
@@ -3300,7 +3315,12 @@ const ViewProjectContent = () => {
)
}
- if (!project.isDataExists && activeTab !== PROJECT_TABS.errors && !analyticsLoading) {
+ if (
+ !project.isDataExists &&
+ activeTab !== PROJECT_TABS.errors &&
+ !(activeTab === PROJECT_TABS.captcha && project.isCaptchaDataExists) &&
+ !analyticsLoading
+ ) {
return (
<>
{!isEmbedded ? <Header /> : null}
@@ -3391,6 +3411,7 @@ const ViewProjectContent = () => {
activeTab,
filters,
customPanelTabs,
+ captchaRefreshTrigger,
// Functions
updatePeriod,
@@ -4274,6 +4295,7 @@ const ViewProjectContent = () => {
{activeTab === PROJECT_TABS.alerts && project.role === 'owner' && isAuthenticated ? (
<ProjectAlertsView />
) : null}
+ {activeTab === PROJECT_TABS.captcha ? <CaptchaView projectId={id} /> : null}
{analyticsLoading &&
(activeTab === PROJECT_TABS.traffic || activeTab === PROJECT_TABS.performance) ? (
<Loader />
diff --git a/web/app/pages/Project/View/components/CaptchaChart.tsx b/web/app/pages/Project/View/components/CaptchaChart.tsx
new file mode 100644
index 000000000..7b5b424f1
--- /dev/null
+++ b/web/app/pages/Project/View/components/CaptchaChart.tsx
@@ -0,0 +1,57 @@
+import { ChartOptions } from 'billboard.js'
+import React, { useMemo } from 'react'
+
+import { getSettingsCaptcha } from '../ViewProject.helpers'
+
+import { MainChart } from './MainChart'
+
+interface CaptchaChartProps {
+ chart?: {
+ x: string[]
+ results: number[]
+ }
+ timeBucket: string
+ timeFormat: string
+ rotateXAxis: boolean
+ chartType: string
+ dataNames: Record<string, string>
+ className?: string
+}
+
+export const CaptchaChart = ({
+ chart,
+ timeBucket,
+ timeFormat,
+ rotateXAxis,
+ chartType,
+ dataNames,
+ className,
+}: CaptchaChartProps) => {
+ const options: ChartOptions = useMemo(() => {
+ if (!chart) {
+ return {} as ChartOptions
+ }
+ return getSettingsCaptcha(chart, timeBucket, timeFormat, rotateXAxis, chartType)
+ }, [chart, timeBucket, timeFormat, rotateXAxis, chartType])
+
+ const deps = useMemo(
+ () => [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames],
+ [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames],
+ )
+
+ if (!chart) {
+ return null
+ }
+
+ return (
+ <div className='overflow-hidden rounded-lg border border-gray-300 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-800/25'>
+ <MainChart
+ chartId='captcha-chart'
+ options={options}
+ dataNames={dataNames}
+ className={className || 'mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible'}
+ deps={deps}
+ />
+ </div>
+ )
+}
diff --git a/web/app/pages/Project/View/components/CaptchaView.tsx b/web/app/pages/Project/View/components/CaptchaView.tsx
new file mode 100644
index 000000000..a1c7da4a8
--- /dev/null
+++ b/web/app/pages/Project/View/components/CaptchaView.tsx
@@ -0,0 +1,370 @@
+import { GlobeAltIcon } from '@heroicons/react/24/outline'
+import billboard from 'billboard.js'
+import cx from 'clsx'
+import _filter from 'lodash/filter'
+import _includes from 'lodash/includes'
+import _isEmpty from 'lodash/isEmpty'
+import _keys from 'lodash/keys'
+import _map from 'lodash/map'
+import { CompassIcon, MapPinIcon, MonitorCog, TabletSmartphoneIcon, RotateCw } from 'lucide-react'
+import { useState, useEffect, useMemo, useContext } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useSearchParams } from 'react-router'
+
+import { getCaptchaData } from '~/api'
+import useSize from '~/hooks/useSize'
+import {
+ captchaTbPeriodPairs,
+ TimeFormat,
+ chartTypes,
+ BROWSER_LOGO_MAP,
+ OS_LOGO_MAP,
+ OS_LOGO_MAP_DARK,
+} from '~/lib/constants'
+import { useTheme } from '~/providers/ThemeProvider'
+import Loader from '~/ui/Loader'
+
+import { ViewProjectContext } from '../ViewProject'
+import { deviceIconMapping } from '../ViewProject.helpers'
+
+import { CaptchaChart } from './CaptchaChart'
+import CCRow from './CCRow'
+import Filters from './Filters'
+import NoEvents from './NoEvents'
+import { Panel } from '../Panels'
+import { Filter } from '../interfaces/traffic'
+import { parseFilters } from '../utils/filters'
+
+const PANELS_ORDER = ['cc', 'br', 'os', 'dv']
+
+const iconClassName = 'w-6 h-6'
+const panelIconMapping: Record<string, JSX.Element> = {
+ cc: <MapPinIcon className={iconClassName} strokeWidth={1.5} />,
+ dv: <TabletSmartphoneIcon className={iconClassName} strokeWidth={1.5} />,
+ br: <CompassIcon className={iconClassName} strokeWidth={1.5} />,
+ os: <MonitorCog className={iconClassName} strokeWidth={1.5} />,
+}
+
+const typeNameMapping = (t: any) => ({
+ cc: t('project.mapping.cc'),
+ dv: t('project.mapping.dv'),
+ br: t('project.mapping.br'),
+ os: t('project.mapping.os'),
+})
+
+interface CaptchaViewProps {
+ projectId: string
+}
+
+const CaptchaView = ({ projectId }: CaptchaViewProps) => {
+ const { theme } = useTheme()
+ const { period, timeBucket, dateRange, captchaRefreshTrigger, timeFormat, size } = useContext(ViewProjectContext)
+ const [searchParams] = useSearchParams()
+
+ const {
+ t,
+ i18n: { language },
+ } = useTranslation('common')
+
+ const [panelsData, setPanelsData] = useState<any>({})
+ const [chartData, setChartData] = useState<{ x: string[]; results: number[] } | null>(null)
+ const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)
+ const [analyticsLoading, setAnalyticsLoading] = useState(true)
+ const [dataLoading, setDataLoading] = useState(false)
+
+ const rotateXAxis = useMemo(() => size.width > 0 && size.width < 500, [size])
+
+ const dataNames = useMemo(
+ () => ({
+ results: t('project.captchaCompletions'),
+ }),
+ [t],
+ )
+
+ const filters = useMemo<Filter[]>(() => {
+ return parseFilters(searchParams)
+ }, [searchParams])
+
+ const tnMapping = typeNameMapping(t)
+ const [ref] = useSize() as any
+
+ const getFormatDate = (date: Date) => {
+ const yyyy = date.getFullYear()
+ let mm: string | number = date.getMonth() + 1
+ let dd: string | number = date.getDate()
+ if (dd < 10) dd = `0${dd}`
+ if (mm < 10) mm = `0${mm}`
+ return `${yyyy}-${mm}-${dd}`
+ }
+
+ const loadCaptcha = async () => {
+ setDataLoading(true)
+
+ try {
+ let data
+ let from
+ let to
+
+ if (dateRange) {
+ from = getFormatDate(dateRange[0])
+ to = getFormatDate(dateRange[1])
+ }
+
+ if (period === 'custom' && dateRange) {
+ data = await getCaptchaData(projectId, timeBucket, '', filters, from, to)
+ } else {
+ data = await getCaptchaData(projectId, timeBucket, period, filters, '', '')
+ }
+
+ if (_isEmpty(data)) {
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ setIsPanelsDataEmpty(true)
+ setChartData(null)
+ return
+ }
+
+ const { params, chart } = data
+
+ if (chart && chart.x && chart.results) {
+ setChartData(chart)
+ } else {
+ setChartData(null)
+ }
+
+ if (_isEmpty(params)) {
+ setIsPanelsDataEmpty(true)
+ } else {
+ setPanelsData({
+ types: _keys(params),
+ data: params,
+ })
+ setIsPanelsDataEmpty(false)
+ }
+
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ } catch (reason) {
+ setAnalyticsLoading(false)
+ setDataLoading(false)
+ setIsPanelsDataEmpty(true)
+ setChartData(null)
+ console.error('[ERROR](loadCaptcha) Loading captcha data failed:', reason)
+ }
+ }
+
+ useEffect(() => {
+ loadCaptcha()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [filters, dateRange, period, timeBucket, projectId])
+
+ // Refresh captcha data when refresh button is clicked
+ useEffect(() => {
+ if (captchaRefreshTrigger > 0) {
+ loadCaptcha()
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [captchaRefreshTrigger])
+
+ const getFilterLink = (column: string, value: string | null) => {
+ const isFilterActive = filters.findIndex((filter) => filter.column === column && filter.filter === value) >= 0
+ const newSearchParams = new URLSearchParams(searchParams.toString())
+
+ if (isFilterActive) {
+ newSearchParams.delete(column, value ?? 'null')
+ } else {
+ newSearchParams.append(column, value ?? 'null')
+ }
+
+ return { search: newSearchParams.toString() }
+ }
+
+ if (analyticsLoading) {
+ return <Loader />
+ }
+
+ if (isPanelsDataEmpty) {
+ return <NoEvents filters={filters} />
+ }
+
+ return (
+ <div ref={ref}>
+ <div className='mt-5'>
+ <Filters tnMapping={tnMapping} />
+ {dataLoading ? (
+ <div className='static mt-4 !bg-transparent' id='loader'>
+ <div className='loader-head dark:!bg-slate-800'>
+ <div className='first dark:!bg-slate-600' />
+ <div className='second dark:!bg-slate-600' />
+ </div>
+ </div>
+ ) : null}
+ {chartData ? (
+ <div className='mt-4'>
+ <CaptchaChart
+ chart={chartData}
+ timeBucket={timeBucket}
+ timeFormat={timeFormat}
+ rotateXAxis={rotateXAxis}
+ chartType={chartTypes.line}
+ dataNames={dataNames}
+ />
+ </div>
+ ) : null}
+ <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>
+ {!_isEmpty(panelsData.types)
+ ? _map(PANELS_ORDER, (type: keyof typeof tnMapping) => {
+ const panelName = tnMapping[type]
+ const panelIcon = panelIconMapping[type]
+
+ if (type === 'cc') {
+ const rowMapper = (entry: any) => {
+ const { name: entryName, cc } = entry
+ if (cc) {
+ return <CCRow cc={cc} name={entryName} language={language} />
+ }
+ return <CCRow cc={entryName} language={language} />
+ }
+
+ return (
+ <Panel
+ key={type}
+ icon={panelIcon}
+ id={type}
+ getFilterLink={getFilterLink}
+ name={panelName}
+ data={panelsData.data[type]}
+ rowMapper={rowMapper}
+ activeTabId={type}
+ />
+ )
+ }
+
+ if (type === 'dv') {
+ return (
+ <Panel
+ key={type}
+ icon={panelIcon}
+ id={type}
+ getFilterLink={getFilterLink}
+ name={panelName}
+ data={panelsData.data[type]}
+ rowMapper={(entry: { name: keyof typeof deviceIconMapping }) => {
+ const { name: entryName } = entry
+ const icon = deviceIconMapping[entryName]
+ if (!icon) {
+ return entryName
+ }
+ return (
+ <>
+ {icon}
+ &nbsp;
+ {entryName}
+ </>
+ )
+ }}
+ capitalize
+ activeTabId={type}
+ />
+ )
+ }
+
+ if (type === 'br') {
+ const rowMapper = (entry: any) => {
+ const { name: entryName } = entry
+ // @ts-expect-error
+ const logoUrl = BROWSER_LOGO_MAP[entryName]
+ if (!logoUrl) {
+ return (
+ <>
+ <GlobeAltIcon className='h-5 w-5' />
+ &nbsp;
+ {entryName}
+ </>
+ )
+ }
+ return (
+ <>
+ <img src={logoUrl} className='h-5 w-5' alt='' />
+ &nbsp;
+ {entryName}
+ </>
+ )
+ }
+
+ return (
+ <Panel
+ key={type}
+ icon={panelIcon}
+ id={type}
+ getFilterLink={getFilterLink}
+ name={panelName}
+ data={panelsData.data[type]}
+ rowMapper={rowMapper}
+ activeTabId={type}
+ />
+ )
+ }
+
+ if (type === 'os') {
+ const rowMapper = (entry: any) => {
+ const { name: entryName } = entry
+ // @ts-expect-error
+ const logoPathLight = OS_LOGO_MAP[entryName]
+ // @ts-expect-error
+ const logoPathDark = OS_LOGO_MAP_DARK[entryName]
+ let logoPath = theme === 'dark' ? logoPathDark : logoPathLight
+ logoPath ||= logoPathLight
+ if (!logoPath) {
+ return (
+ <>
+ <GlobeAltIcon className='h-5 w-5' />
+ &nbsp;
+ {entryName}
+ </>
+ )
+ }
+ const logoUrl = `/${logoPath}`
+ return (
+ <>
+ <img src={logoUrl} className='h-5 w-5 dark:fill-gray-50' alt='' />
+ &nbsp;
+ {entryName}
+ </>
+ )
+ }
+
+ return (
+ <Panel
+ key={type}
+ icon={panelIcon}
+ id={type}
+ getFilterLink={getFilterLink}
+ name={panelName}
+ data={panelsData.data[type]}
+ rowMapper={rowMapper}
+ activeTabId={type}
+ />
+ )
+ }
+
+ return (
+ <Panel
+ key={type}
+ icon={panelIcon}
+ id={type}
+ getFilterLink={getFilterLink}
+ name={panelName}
+ data={panelsData.data[type]}
+ activeTabId={type}
+ />
+ )
+ })
+ : null}
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default CaptchaView
diff --git a/web/app/pages/Project/View/components/ProjectSidebar.tsx b/web/app/pages/Project/View/components/ProjectSidebar.tsx
index 1119c8fc7..6188c0122 100644
--- a/web/app/pages/Project/View/components/ProjectSidebar.tsx
+++ b/web/app/pages/Project/View/components/ProjectSidebar.tsx
@@ -1,6 +1,13 @@
import cx from 'clsx'
import _map from 'lodash/map'
-import { ChevronDownIcon, ChevronRightIcon, GlobeIcon, BarChart3Icon, SettingsIcon } from 'lucide-react'
+import {
+ ChevronDownIcon,
+ ChevronRightIcon,
+ GlobeIcon,
+ BarChart3Icon,
+ SettingsIcon,
+ ShieldCheckIcon,
+} from 'lucide-react'
import React, { useState, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, LinkProps } from 'react-router'
@@ -22,6 +29,8 @@ const ICON_COLORS: Record<string, string> = {
sessions: 'text-indigo-500',
errors: 'text-red-500',
funnels: 'text-teal-500',
+ // CAPTCHA
+ captcha: 'text-emerald-500',
// Settings
settings: 'text-gray-500',
}
@@ -30,6 +39,7 @@ const ICON_COLORS: Record<string, string> = {
const GROUP_ICON_COLORS: Record<string, string> = {
webAnalytics: 'text-blue-500',
productAnalytics: 'text-green-500',
+ captcha: 'text-emerald-500',
}
interface Tab {
@@ -205,6 +215,18 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
})
}
+ // CAPTCHA group
+ const captchaTabs = tabs.filter((tab) => tab.id === PROJECT_TABS.captcha)
+ if (captchaTabs.length > 0) {
+ groups.push({
+ id: 'captcha',
+ label: t('common.captcha'),
+ icon: ShieldCheckIcon,
+ tabs: captchaTabs,
+ defaultExpanded: false,
+ })
+ }
+
return groups
}, [tabs, t])
@@ -213,6 +235,7 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
{/* Project name at the top */}
<div className='sticky top-0 z-10 flex items-center border-b border-gray-200 bg-white px-4 py-2 dark:border-slate-800 dark:bg-slate-900'>
<Tooltip
+ className='max-w-full'
text={projectName}
tooltipNode={
<Text as='h2' size='lg' weight='semibold' truncate className='max-w-full'>
diff --git a/web/app/routes/captchas.$id.tsx b/web/app/routes/captchas.$id.tsx
deleted file mode 100644
index 1699b2855..000000000
--- a/web/app/routes/captchas.$id.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import type { LinksFunction } from 'react-router'
-
-import { useRequiredParams } from '~/hooks/useRequiredParams'
-import ViewCaptcha from '~/pages/Captcha/View'
-import { CurrentProjectProvider } from '~/providers/CurrentProjectProvider'
-import ProjectViewStyle from '~/styles/ProjectViewStyle.css?url'
-
-export const links: LinksFunction = () => [{ rel: 'stylesheet', href: ProjectViewStyle }]
-
-export default function Index() {
- const { id } = useRequiredParams<{ id: string }>()
-
- return (
- <CurrentProjectProvider id={id}>
- <ViewCaptcha />
- </CurrentProjectProvider>
- )
-}
diff --git a/web/app/routes/captchas.new.tsx b/web/app/routes/captchas.new.tsx
deleted file mode 100644
index fc782ccc3..000000000
--- a/web/app/routes/captchas.new.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import CaptchaSettings from '~/pages/Captcha/Settings'
-
-export default function Index() {
- return <CaptchaSettings />
-}
diff --git a/web/app/routes/captchas.settings.$id.tsx b/web/app/routes/captchas.settings.$id.tsx
deleted file mode 100644
index 7da1aa565..000000000
--- a/web/app/routes/captchas.settings.$id.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import CaptchaSettings from '~/pages/Captcha/Settings'
-
-export default function Index() {
- return <CaptchaSettings isSettings />
-}
diff --git a/web/app/utils/analytics.ts b/web/app/utils/analytics.ts
index 3c1e4e712..80100cc5e 100644
--- a/web/app/utils/analytics.ts
+++ b/web/app/utils/analytics.ts
@@ -45,14 +45,6 @@ const PATHS_REPLACEMENT_MAP = [
regex: /^\/share/i,
replacement: '/share/[token]',
},
- {
- regex: /^\/captchas\/(?!new$)[^/]+$/i,
- replacement: '/captchas/[id]',
- },
- {
- regex: /^\/captchas\/settings/i,
- replacement: '/captchas/settings/[id]',
- },
{
regex: /^\/ref/i,
replacement: '/ref/[id]',
diff --git a/web/app/utils/routes.ts b/web/app/utils/routes.ts
index 6e1cf70c1..b37df5675 100644
--- a/web/app/utils/routes.ts
+++ b/web/app/utils/routes.ts
@@ -14,11 +14,8 @@ const routes = Object.freeze({
user_settings: '/user-settings',
verify: '/verify/:id',
change_email: '/change-email/:id',
- new_captcha: '/captchas/new',
project_settings: '/projects/settings/:id',
- captcha_settings: '/captchas/settings/:id',
project: '/projects/:id',
- captcha: '/captchas/:id',
billing: '/billing',
privacy: '/privacy',
cookiePolicy: '/cookie-policy',
diff --git a/web/app/utils/server.ts b/web/app/utils/server.ts
index d4e8d653a..69f7651e9 100644
--- a/web/app/utils/server.ts
+++ b/web/app/utils/server.ts
@@ -120,12 +120,6 @@ export const getPageMeta = (t: typeof i18next.t, url?: string, _pathname?: strin
}
break
- case routes.new_captcha:
- result = {
- title: t('project.settings.create'),
- }
- break
-
case routes.billing:
result = {
title: t('titles.billing'),
@@ -226,7 +220,7 @@ export const getPageMeta = (t: typeof i18next.t, url?: string, _pathname?: strin
break
}
- // organisation, project_settings, captcha_settings, project, captcha titles are set dynamically
+ // organisation, project_settings, project titles are set dynamically
// todo: create_alert, alert_settings, project_protected_password
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 79c1399b2..d0464815d 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -111,6 +111,7 @@
"error": "Error",
"close": "Close",
"cancel": "Cancel",
+ "captcha": "CAPTCHA",
"gotIt": "Got it",
"settings": "Settings",
"openMenu": "Open menu",
@@ -960,6 +961,7 @@
"support": "Contact support"
},
"project": {
+ "captchaCompletions": "CAPTCHA completions",
"addAnnotation": "Add annotation",
"editAnnotation": "Edit annotation",
"deleteAnnotation": "Delete annotation",
@@ -1229,12 +1231,26 @@
"general": "General",
"access": "Access",
"shields": "Shields",
+ "captcha": "CAPTCHA",
"emails": "Emails",
"people": "People",
"annotations": "Annotations",
"danger": "Danger zone",
"integrations": "Integrations"
},
+ "captcha": {
+ "title": "CAPTCHA Integration",
+ "description": "Enable CAPTCHA protection for your forms and actions. Generate a secret key to integrate Swetrix CAPTCHA with your application.",
+ "secretKey": "Secret key",
+ "generateKey": "Generate secret key",
+ "regenerateKey": "Regenerate secret key",
+ "keyGenerated": "Secret key has been generated",
+ "keyRegenerated": "Secret key has been regenerated",
+ "regenerateKeyTitle": "Regenerate secret key?",
+ "regenerateKeyWarning": "Are you sure you want to regenerate the secret key? This will invalidate the current key and all applications using it will need to be updated.",
+ "noKeyGenerated": "No secret key has been generated yet. Generate one to enable CAPTCHA for this project.",
+ "learnMore": "Use this secret key in your backend to verify CAPTCHA tokens. Learn more in our documentation."
+ },
"annotations": {
"title": "Annotations",
"description": "Mark important events on your charts to remember why traffic patterns changed.",