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!

Implement SSR / proxy API requests through RR actions (#459)

Andrii Romasiunf0d7aa55eb1d
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index 591917687..adb340521 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -239,6 +239,11 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, metrics: ${metrics}`,
+ 'GET /analytics',
+ )
+
let parsedMetrics: ProjectViewCustomEventDto[]
if (!isCaptcha) {
@@ -404,6 +409,8 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(`pid: ${pid}, period: ${period}`, 'GET /analytics/funnel')
+
const pagesArr = await this.analyticsService.getPagesArray(
pages,
funnelId,
@@ -471,6 +478,8 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(`pid: ${pid}`, 'GET /analytics/meta')
+
return this.analyticsService.getCustomEventMetadata(data)
}
@@ -491,6 +500,8 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(`pid: ${pid}`, 'GET /analytics/property')
+
return this.analyticsService.getPagePropertyMeta(data)
}
@@ -511,6 +522,8 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(`pid: ${pid}, type: ${type}`, 'GET /analytics/filters')
+
return this.analyticsService.getFilters(pid, type)
}
@@ -531,6 +544,11 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(
+ `pid: ${pid}, type: ${type}`,
+ 'GET /analytics/errors-filters',
+ )
+
return this.analyticsService.getErrorsFilters(pid, type)
}
@@ -551,6 +569,11 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(
+ `pid: ${pid}, type: ${type}, column: ${column}`,
+ 'GET /analytics/filters/versions',
+ )
+
return this.analyticsService.getVersionFilters(pid, type, column)
}
@@ -591,6 +614,8 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(`pid: ${pid}, period: ${period}`, 'GET /analytics/chart')
+
const paramsData = { params: { pid, groupFrom, groupTo, ...filtersParams } }
const result = await this.analyticsService.groupChartByTimeBucket(
@@ -635,6 +660,11 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, measure: ${measure}`,
+ 'GET /analytics/performance',
+ )
+
let newTimeBucket = timeBucket
let allowedTumebucketForPeriodAll
let diff
@@ -727,6 +757,11 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, measure: ${measure}`,
+ 'GET /analytics/performance/chart',
+ )
+
const paramsData = { params: { pid, groupFrom, groupTo, ...filtersParams } }
const chart = await this.analyticsService.getPerfChartData(
@@ -768,6 +803,11 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}`,
+ 'GET /analytics/user-flow',
+ )
+
let diff
if (period === 'all') {
@@ -816,6 +856,8 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(`pid: ${pid}, period: ${period}`, 'GET /analytics/keywords')
+
let diff
if (period === 'all') {
@@ -862,6 +904,8 @@ export class AnalyticsController {
} = data
const pidsArray = getPIDsArray(pids, pid)
+ this.logger.log(`pidsArray: ${pidsArray}`, 'GET /analytics/birdseye')
+
const validPids = []
const validationPromises = _map(pidsArray, async currentPID => {
@@ -938,6 +982,11 @@ export class AnalyticsController {
await Promise.all(validationPromises)
+ this.logger.log(
+ `pidsArray: ${pidsArray}, measure: ${measure}`,
+ 'GET /analytics/performance/birdseye',
+ )
+
return this.analyticsService.getPerformanceSummary(
pidsArray,
period,
@@ -980,6 +1029,8 @@ export class AnalyticsController {
const { pids, pid } = data
const pidsArray = getPIDsArray(pids, pid)
+ this.logger.log(`pidsArray: ${pidsArray}`, 'GET /analytics/hb')
+
const validPids = []
const validationPromises = _map(pidsArray, async currentPID => {
@@ -1040,6 +1091,8 @@ export class AnalyticsController {
)
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(`pid: ${pid}`, 'GET /analytics/live-visitors')
+
const since = dayjs
.utc()
.subtract(ONLINE_VISITORS_WINDOW_MINUTES, 'minute')
@@ -1133,6 +1186,11 @@ export class AnalyticsController {
this.analyticsService.checkCountryBlacklist(project, country)
+ this.logger.log(
+ `pid: ${errorDTO.pid}, pg: ${errorDTO.pg}, name: ${errorDTO.name}, message: ${errorDTO.message}`,
+ 'POST /analytics/error',
+ )
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1246,6 +1304,11 @@ export class AnalyticsController {
this.analyticsService.checkCountryBlacklist(project, country)
+ this.logger.log(
+ `pid: ${eventsDTO.pid}, ev: ${eventsDTO.ev}, pg: ${eventsDTO.pg}`,
+ 'POST /analytics/custom',
+ )
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1352,6 +1415,8 @@ export class AnalyticsController {
await this.analyticsService.extendSessionTTL(psid)
await this.analyticsService.recordSessionActivity(psid, pid, profileId)
+ this.logger.log(`pid: ${pid}, psid: ${psid}`, 'POST /analytics/hb')
+
return {}
}
@@ -1401,6 +1466,8 @@ export class AnalyticsController {
this.analyticsService.checkCountryBlacklist(project, country)
+ this.logger.log(`pid: ${logDTO.pid}, pg: ${logDTO.pg}`, 'POST /analytics')
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1540,6 +1607,8 @@ export class AnalyticsController {
this.analyticsService.checkCountryBlacklist(project, country)
+ this.logger.log(`pid: ${pid}`, 'GET /analytics/noscript')
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1609,6 +1678,11 @@ export class AnalyticsController {
)
}
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, take: ${take}, skip: ${skip}`,
+ 'GET /analytics/sessions',
+ )
+
let timeBucket
let diff
@@ -1692,6 +1766,11 @@ export class AnalyticsController {
)
}
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, take: ${take}, skip: ${skip}`,
+ 'GET /analytics/errors',
+ )
+
let timeBucket
let diff
@@ -1766,6 +1845,11 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(
+ `pid: ${pid}, eid: ${eid}, period: ${period}`,
+ 'GET /analytics/get-error',
+ )
+
let newTimeBucket = timeBucket
let diff
@@ -1827,6 +1911,11 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}`,
+ 'GET /analytics/error-overview',
+ )
+
let parsedOptions: GetErrorOverviewOptions = {}
if (typeof options === 'string') {
@@ -1915,6 +2004,11 @@ export class AnalyticsController {
)
}
+ this.logger.log(
+ `pid: ${pid}, eid: ${eid}, period: ${period}, take: ${take}, skip: ${skip}`,
+ 'GET /analytics/error-sessions',
+ )
+
let newTimeBucket = timeBucket
let diff
@@ -1965,6 +2059,8 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(`pid: ${pid}, psid: ${psid}`, 'GET /analytics/session')
+
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
const result = await this.analyticsService.getSessionDetails(
@@ -2010,6 +2106,11 @@ export class AnalyticsController {
)
}
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, take: ${take}, skip: ${skip}`,
+ 'GET /analytics/profiles',
+ )
+
let timeBucket
let diff
@@ -2084,6 +2185,11 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(
+ `pid: ${pid}, profileId: ${profileId}, period: ${period}`,
+ 'GET /analytics/profile',
+ )
+
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
let timeBucket
@@ -2166,6 +2272,11 @@ export class AnalyticsController {
)
}
+ this.logger.log(
+ `pid: ${pid}, profileId: ${profileId}, period: ${period}, take: ${take}, skip: ${skip}`,
+ 'GET /analytics/profile/sessions',
+ )
+
let timeBucket
let diff
@@ -2242,6 +2353,11 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, customEvents: ${customEvents}`,
+ 'GET /analytics/custom-events',
+ )
+
let newTimeBucket = timeBucket
let diff
let timeBucketForAllTime
@@ -2321,6 +2437,11 @@ export class AnalyticsController {
ip,
)
+ this.logger.log(
+ `pid: ${pid}, profileId: ${profileId}`,
+ 'POST /analytics/profile-id',
+ )
+
return { profileId }
} catch (error) {
this.logger.error({ error, pid }, 'Error generating profile ID')
@@ -2347,6 +2468,11 @@ export class AnalyticsController {
ip,
)
+ this.logger.log(
+ `pid: ${pid}, sessionId: ${psid}`,
+ 'POST /analytics/session-id',
+ )
+
return { sessionId: psid }
} catch (error) {
this.logger.error({ error, pid }, 'Error generating session ID')
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 6d92938e7..1f244c862 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -3259,12 +3259,6 @@ export class AnalyticsService {
customEVFilterApplied,
parsedFilters,
)
-
- if (!_some(_values(params), val => !_isEmpty(val))) {
- throw new BadRequestException(
- 'There are no parameters for the specified time frames',
- )
- }
})(),
// Getting chart & average session duration data
@@ -4614,21 +4608,22 @@ export class AnalyticsService {
}
if (!details) {
- const querySessionDetailsBackup = `
+ const querySessionDetailsFromCustomEV = `
SELECT
dv, br, brv, os, osv, lc, ref, so, me, ca, te, co, cc, rg, ct, profileId
- FROM analytics
+ FROM customEV
WHERE
pid = {pid:FixedString(12)}
AND psid IS NOT NULL
AND toString(psid) = {psid:String}
+ ORDER BY created ASC
LIMIT 1;
`
details = (
await clickhouse
.query({
- query: querySessionDetailsBackup,
+ query: querySessionDetailsFromCustomEV,
query_params: paramsData.params,
})
.then(resultSet => resultSet.json())
@@ -4708,23 +4703,88 @@ export class AnalyticsService {
skip = 0,
customEVFilterApplied = false,
): Promise<object | void> {
- const primaryEventsTable = customEVFilterApplied ? 'customEV' : 'analytics'
+ let primaryEventsSubquery: string
- const primaryEventsSubquery = `
- SELECT
- CAST(${primaryEventsTable}.psid, 'String') AS psidCasted,
- ${primaryEventsTable}.pid,
- ${primaryEventsTable}.cc,
- ${primaryEventsTable}.os,
- ${primaryEventsTable}.br,
- toTimeZone(${primaryEventsTable}.created, {timezone:String}) AS created_for_grouping
- FROM ${primaryEventsTable}
- WHERE
- ${primaryEventsTable}.pid = {pid:FixedString(12)}
- AND ${primaryEventsTable}.psid IS NOT NULL
- AND ${primaryEventsTable}.created BETWEEN {groupFrom:String} AND {groupTo:String}
- ${filtersQuery}
- `
+ if (customEVFilterApplied) {
+ // When filtering by custom events, we need to:
+ // 1. Identify sessions (psids) that have matching custom events
+ // 2. Calculate session boundaries from ALL analytics events for those sessions
+ primaryEventsSubquery = `
+ SELECT
+ all_events.psidCasted,
+ all_events.pid,
+ all_events.cc,
+ all_events.os,
+ all_events.br,
+ all_events.created_for_grouping
+ FROM (
+ SELECT
+ CAST(analytics.psid, 'String') AS psidCasted,
+ analytics.pid,
+ analytics.cc,
+ analytics.os,
+ analytics.br,
+ toTimeZone(analytics.created, {timezone:String}) AS created_for_grouping
+ FROM analytics
+ WHERE
+ analytics.pid = {pid:FixedString(12)}
+ AND analytics.psid IS NOT NULL
+ AND analytics.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ UNION ALL
+ SELECT
+ CAST(customEV.psid, 'String') AS psidCasted,
+ customEV.pid,
+ customEV.cc,
+ customEV.os,
+ customEV.br,
+ toTimeZone(customEV.created, {timezone:String}) AS created_for_grouping
+ FROM customEV
+ WHERE
+ customEV.pid = {pid:FixedString(12)}
+ AND customEV.psid IS NOT NULL
+ AND customEV.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ) AS all_events
+ WHERE all_events.psidCasted IN (
+ SELECT DISTINCT CAST(customEV.psid, 'String')
+ FROM customEV
+ WHERE
+ customEV.pid = {pid:FixedString(12)}
+ AND customEV.psid IS NOT NULL
+ AND customEV.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ )
+ `
+ } else {
+ primaryEventsSubquery = `
+ SELECT
+ CAST(analytics.psid, 'String') AS psidCasted,
+ analytics.pid,
+ analytics.cc,
+ analytics.os,
+ analytics.br,
+ toTimeZone(analytics.created, {timezone:String}) AS created_for_grouping
+ FROM analytics
+ WHERE
+ analytics.pid = {pid:FixedString(12)}
+ AND analytics.psid IS NOT NULL
+ AND analytics.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ UNION ALL
+ SELECT
+ CAST(customEV.psid, 'String') AS psidCasted,
+ customEV.pid,
+ customEV.cc,
+ customEV.os,
+ customEV.br,
+ toTimeZone(customEV.created, {timezone:String}) AS created_for_grouping
+ FROM customEV
+ WHERE
+ customEV.pid = {pid:FixedString(12)}
+ AND customEV.psid IS NOT NULL
+ AND customEV.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ `
+ }
const query = `
WITH distinct_sessions_filtered AS (
@@ -4871,34 +4931,54 @@ export class AnalyticsService {
}
const query = `
- WITH profile_analytics AS (
+ WITH all_profile_data AS (
SELECT
profileId,
- count() AS pageviewsCount,
- countDistinct(psid) AS sessionsCount,
- min(created) AS firstSeen,
- max(created) AS lastSeen,
- any(cc) AS cc_agg,
- any(os) AS os_agg,
- any(br) AS br_agg,
- any(dv) AS dv_agg
+ psid,
+ cc,
+ os,
+ br,
+ dv,
+ created,
+ 1 AS isPageview,
+ 0 AS isEvent
FROM analytics
WHERE pid = {pid:FixedString(12)}
AND profileId IS NOT NULL
AND profileId != ''
${profileTypeFilter}
${filtersQuery}
- GROUP BY profileId
- ),
- profile_events AS (
+ UNION ALL
SELECT
profileId,
- count() AS eventsCount
+ psid,
+ cc,
+ os,
+ br,
+ dv,
+ created,
+ 0 AS isPageview,
+ 1 AS isEvent
FROM customEV
WHERE pid = {pid:FixedString(12)}
AND profileId IS NOT NULL
AND profileId != ''
${profileTypeFilter}
+ ${filtersQuery}
+ ),
+ profile_aggregated AS (
+ SELECT
+ profileId,
+ sum(isPageview) AS pageviewsCount,
+ countDistinct(psid) AS sessionsCount,
+ sum(isEvent) AS eventsCount,
+ min(created) AS firstSeen,
+ max(created) AS lastSeen,
+ any(cc) AS cc_agg,
+ any(os) AS os_agg,
+ any(br) AS br_agg,
+ any(dv) AS dv_agg
+ FROM all_profile_data
GROUP BY profileId
),
profile_errors AS (
@@ -4916,7 +4996,7 @@ export class AnalyticsService {
pa.profileId AS profileId,
pa.sessionsCount AS sessionsCount,
pa.pageviewsCount AS pageviewsCount,
- COALESCE(pe.eventsCount, 0) AS eventsCount,
+ pa.eventsCount AS eventsCount,
COALESCE(perr.errorsCount, 0) AS errorsCount,
pa.firstSeen AS firstSeen,
pa.lastSeen AS lastSeen,
@@ -4924,8 +5004,7 @@ export class AnalyticsService {
pa.os_agg AS os,
pa.br_agg AS br,
pa.dv_agg AS dv
- FROM profile_analytics AS pa
- LEFT JOIN profile_events AS pe ON pa.profileId = pe.profileId
+ FROM profile_aggregated AS pa
LEFT JOIN profile_errors AS perr ON pa.profileId = perr.profileId
ORDER BY pa.lastSeen DESC
LIMIT {take:UInt32}
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index c6144d915..cfc676216 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -830,7 +830,7 @@ export class ProjectController {
await deleteProjectRedis(pid)
- return secret
+ return { captchaSecretKey: secret }
}
@Delete('/partially/:pid')
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index 84ae9d684..fc001a065 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -220,6 +220,11 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, metrics: ${metrics}`,
+ 'GET /analytics',
+ )
+
let parsedMetrics
if (!isCaptcha) {
@@ -398,6 +403,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(`pid: ${pid}, period: ${period}`, 'GET /analytics/funnel')
+
let diff
if (period === 'all') {
@@ -457,6 +464,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(`pid: ${pid}`, 'GET /analytics/meta')
+
return this.analyticsService.getCustomEventMetadata(data)
}
@@ -475,6 +484,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(`pid: ${pid}`, 'GET /analytics/property')
+
return this.analyticsService.getPagePropertyMeta(data)
}
@@ -493,6 +504,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(`pid: ${pid}, type: ${type}`, 'GET /analytics/filters')
+
return this.analyticsService.getFilters(pid, type)
}
@@ -531,6 +544,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(`pid: ${pid}, period: ${period}`, 'GET /analytics/chart')
+
const paramsData = { params: { pid, groupFrom, groupTo, ...filtersParams } }
const result = await this.analyticsService.groupChartByTimeBucket(
@@ -573,10 +588,14 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, measure: ${measure}`,
+ 'GET /analytics/performance',
+ )
+
let newTimeBucket = timeBucket
let allowedTumebucketForPeriodAll
let diff
-
if (period === 'all') {
const res = await this.analyticsService.calculateTimeBucketForAllTime(
pid,
@@ -663,6 +682,11 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, measure: ${measure}`,
+ 'GET /analytics/performance/chart',
+ )
+
const paramsData = { params: { pid, groupFrom, groupTo, ...filtersParams } }
const chart = await this.analyticsService.getPerfChartData(
@@ -693,6 +717,11 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}`,
+ 'GET /analytics/user-flow',
+ )
+
let diff
if (period === 'all') {
@@ -745,6 +774,8 @@ export class AnalyticsController {
} = data
const pidsArray = getPIDsArray(pids, pid)
+ this.logger.log(`pidsArray: ${pidsArray}`, 'GET /analytics/birdseye')
+
const validationPromises = _map(pidsArray, async currentPID => {
await this.analyticsService.checkProjectAccess(
currentPID,
@@ -802,6 +833,11 @@ export class AnalyticsController {
await Promise.all(validationPromises)
+ this.logger.log(
+ `pidsArray: ${pidsArray}, measure: ${measure}`,
+ 'GET /analytics/performance/birdseye',
+ )
+
return this.analyticsService.getPerformanceSummary(
pidsArray,
period,
@@ -822,6 +858,8 @@ export class AnalyticsController {
const { pids, pid } = data
const pidsArray = getPIDsArray(pids, pid)
+ this.logger.log(`pidsArray: ${pidsArray}`, 'GET /analytics/hb')
+
const validationPromises = _map(pidsArray, async currentPID => {
await this.analyticsService.checkProjectAccess(
currentPID,
@@ -864,6 +902,8 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(`pid: ${pid}`, 'GET /analytics/live-visitors')
+
const since = dayjs
.utc()
.subtract(ONLINE_VISITORS_WINDOW_MINUTES, 'minute')
@@ -959,6 +999,11 @@ export class AnalyticsController {
this.analyticsService.checkCountryBlacklist(project, country)
+ this.logger.log(
+ `pid: ${eventsDTO.pid}, ev: ${eventsDTO.ev}, pg: ${eventsDTO.pg}`,
+ 'POST /analytics/custom',
+ )
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1065,6 +1110,8 @@ export class AnalyticsController {
await this.analyticsService.extendSessionTTL(psid)
await this.analyticsService.recordSessionActivity(psid, pid, profileId)
+ this.logger.log(`pid: ${pid}, psid: ${psid}`, 'POST /analytics/hb')
+
return {}
}
@@ -1113,6 +1160,8 @@ export class AnalyticsController {
this.analyticsService.checkCountryBlacklist(project, country)
+ this.logger.log(`pid: ${logDTO.pid}, pg: ${logDTO.pg}`, 'POST /analytics')
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1217,6 +1266,8 @@ export class AnalyticsController {
const { 'user-agent': userAgent, origin } = headers
const { pid } = data
+ const logDTO: PageviewsDto = { pid }
+
const isBot = await this.analyticsService.isBot(pid, userAgent)
if (isBot) {
@@ -1226,8 +1277,6 @@ export class AnalyticsController {
const ip = getIPFromHeaders(headers) || reqIP || ''
- const logDTO: PageviewsDto = { pid }
-
const project = await this.analyticsService.validate(logDTO, origin, ip)
const [, psid] = await this.analyticsService.generateAndStoreSessionId(
@@ -1254,6 +1303,8 @@ export class AnalyticsController {
this.analyticsService.checkCountryBlacklist(project, country)
+ this.logger.log(`pid: ${pid}`, 'GET /analytics/noscript')
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1321,6 +1372,11 @@ export class AnalyticsController {
)
}
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, take: ${take}, skip: ${skip}`,
+ 'GET /analytics/sessions',
+ )
+
let timeBucket
let diff
@@ -1384,6 +1440,9 @@ export class AnalyticsController {
uid,
headers['x-password'],
)
+
+ this.logger.log(`pid: ${pid}, psid: ${psid}`, 'GET /analytics/session')
+
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
const result = await this.analyticsService.getSessionDetails(
@@ -1419,6 +1478,11 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, customEvents: ${customEvents}`,
+ 'GET /analytics/custom-events',
+ )
+
let newTimeBucket = timeBucket
let diff
let timeBucketForAllTime
@@ -1500,6 +1564,11 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(
+ `pid: ${pid}, type: ${type}`,
+ 'GET /analytics/errors-filters',
+ )
+
return this.analyticsService.getErrorsFilters(pid, type)
}
@@ -1518,6 +1587,11 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(
+ `pid: ${pid}, type: ${type}, column: ${column}`,
+ 'GET /analytics/filters/versions',
+ )
+
return this.analyticsService.getVersionFilters(pid, type, column)
}
@@ -1559,6 +1633,11 @@ export class AnalyticsController {
this.analyticsService.checkCountryBlacklist(project, country)
+ this.logger.log(
+ `pid: ${errorDTO.pid}, pg: ${errorDTO.pg}, name: ${errorDTO.name}, message: ${errorDTO.message}`,
+ 'POST /analytics/error',
+ )
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1667,6 +1746,11 @@ export class AnalyticsController {
)
}
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, take: ${take}, skip: ${skip}`,
+ 'GET /analytics/errors',
+ )
+
let timeBucket
let diff
@@ -1739,6 +1823,11 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(
+ `pid: ${pid}, eid: ${eid}, period: ${period}`,
+ 'GET /analytics/get-error',
+ )
+
let newTimeBucket = timeBucket
let diff
@@ -1798,6 +1887,11 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(
+ `pid: ${pid}, period: ${period}`,
+ 'GET /analytics/error-overview',
+ )
+
let parsedOptions: GetErrorOverviewOptions = {}
if (typeof options === 'string') {
@@ -1884,6 +1978,11 @@ export class AnalyticsController {
)
}
+ this.logger.log(
+ `pid: ${pid}, eid: ${eid}, period: ${period}, take: ${take}, skip: ${skip}`,
+ 'GET /analytics/error-sessions',
+ )
+
let newTimeBucket = timeBucket
let diff
@@ -1949,6 +2048,11 @@ export class AnalyticsController {
)
}
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, take: ${take}, skip: ${skip}`,
+ 'GET /analytics/profiles',
+ )
+
let timeBucket
let diff
@@ -2021,6 +2125,11 @@ export class AnalyticsController {
headers['x-password'],
)
+ this.logger.log(
+ `pid: ${pid}, profileId: ${profileId}, period: ${period}`,
+ 'GET /analytics/profile',
+ )
+
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
let timeBucket
@@ -2101,6 +2210,11 @@ export class AnalyticsController {
)
}
+ this.logger.log(
+ `pid: ${pid}, profileId: ${profileId}, period: ${period}, take: ${take}, skip: ${skip}`,
+ 'GET /analytics/profile/sessions',
+ )
+
let timeBucket
let diff
@@ -2170,6 +2284,11 @@ export class AnalyticsController {
ip,
)
+ this.logger.log(
+ `pid: ${pid}, profileId: ${profileId}`,
+ 'POST /analytics/profile-id',
+ )
+
return { profileId }
} catch (error) {
this.logger.error({ error, pid }, 'Error generating profile ID')
@@ -2196,6 +2315,11 @@ export class AnalyticsController {
ip,
)
+ this.logger.log(
+ `pid: ${pid}, sessionId: ${psid}`,
+ 'POST /analytics/session-id',
+ )
+
return { sessionId: psid }
} catch (error) {
this.logger.error({ error, pid }, 'Error generating session ID')
diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.ts
index c24f24506..ccac045f4 100644
--- a/backend/apps/community/src/analytics/analytics.service.ts
+++ b/backend/apps/community/src/analytics/analytics.service.ts
@@ -2878,12 +2878,6 @@ export class AnalyticsService {
customEVFilterApplied,
parsedFilters,
)
-
- if (!_some(_values(params), val => !_isEmpty(val))) {
- throw new BadRequestException(
- 'There are no parameters for the specified time frames',
- )
- }
})(),
// Getting chart & average session duration data
@@ -4166,20 +4160,22 @@ export class AnalyticsService {
}
if (!details) {
- const querySessionDetailsBackup = `
+ const querySessionDetailsFromCustomEV = `
SELECT
dv, br, brv, os, osv, lc, ref, so, me, ca, te, co, cc, rg, ct, profileId
- FROM analytics
+ FROM customEV
WHERE
pid = {pid:FixedString(12)}
+ AND psid IS NOT NULL
AND CAST(psid, 'String') = {psid:String}
+ ORDER BY created ASC
LIMIT 1;
`
details = (
await clickhouse
.query({
- query: querySessionDetailsBackup,
+ query: querySessionDetailsFromCustomEV,
query_params: paramsData.params,
})
.then(resultSet => resultSet.json())
@@ -4259,23 +4255,55 @@ export class AnalyticsService {
skip = 0,
customEVFilterApplied = false,
): Promise<object | void> {
- const primaryEventsTable = customEVFilterApplied ? 'customEV' : 'analytics'
+ let primaryEventsSubquery: string
- const primaryEventsSubquery = `
- SELECT
- CAST(${primaryEventsTable}.psid, 'String') AS psidCasted,
- ${primaryEventsTable}.pid,
- ${primaryEventsTable}.cc,
- ${primaryEventsTable}.os,
- ${primaryEventsTable}.br,
- toTimeZone(${primaryEventsTable}.created, {timezone:String}) AS created_for_grouping
- FROM ${primaryEventsTable}
- WHERE
- ${primaryEventsTable}.pid = {pid:FixedString(12)}
- AND ${primaryEventsTable}.psid IS NOT NULL
- AND ${primaryEventsTable}.created BETWEEN {groupFrom:String} AND {groupTo:String}
- ${filtersQuery}
- `
+ if (customEVFilterApplied) {
+ primaryEventsSubquery = `
+ SELECT
+ CAST(customEV.psid, 'String') AS psidCasted,
+ customEV.pid,
+ customEV.cc,
+ customEV.os,
+ customEV.br,
+ toTimeZone(customEV.created, {timezone:String}) AS created_for_grouping
+ FROM customEV
+ WHERE
+ customEV.pid = {pid:FixedString(12)}
+ AND customEV.psid IS NOT NULL
+ AND customEV.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ `
+ } else {
+ primaryEventsSubquery = `
+ SELECT
+ CAST(analytics.psid, 'String') AS psidCasted,
+ analytics.pid,
+ analytics.cc,
+ analytics.os,
+ analytics.br,
+ toTimeZone(analytics.created, {timezone:String}) AS created_for_grouping
+ FROM analytics
+ WHERE
+ analytics.pid = {pid:FixedString(12)}
+ AND analytics.psid IS NOT NULL
+ AND analytics.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ UNION ALL
+ SELECT
+ CAST(customEV.psid, 'String') AS psidCasted,
+ customEV.pid,
+ customEV.cc,
+ customEV.os,
+ customEV.br,
+ toTimeZone(customEV.created, {timezone:String}) AS created_for_grouping
+ FROM customEV
+ WHERE
+ customEV.pid = {pid:FixedString(12)}
+ AND customEV.psid IS NOT NULL
+ AND customEV.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filtersQuery}
+ `
+ }
const query = `
WITH distinct_sessions_filtered AS (
@@ -5149,34 +5177,54 @@ export class AnalyticsService {
}
const query = `
- WITH profile_analytics AS (
+ WITH all_profile_data AS (
SELECT
profileId,
- count() AS pageviewsCount,
- countDistinct(psid) AS sessionsCount,
- min(created) AS firstSeen,
- max(created) AS lastSeen,
- any(cc) AS cc_agg,
- any(os) AS os_agg,
- any(br) AS br_agg,
- any(dv) AS dv_agg
+ psid,
+ cc,
+ os,
+ br,
+ dv,
+ created,
+ 1 AS isPageview,
+ 0 AS isEvent
FROM analytics
WHERE pid = {pid:FixedString(12)}
AND profileId IS NOT NULL
AND profileId != ''
${profileTypeFilter}
${filtersQuery}
- GROUP BY profileId
- ),
- profile_events AS (
+ UNION ALL
SELECT
profileId,
- count() AS eventsCount
+ psid,
+ cc,
+ os,
+ br,
+ dv,
+ created,
+ 0 AS isPageview,
+ 1 AS isEvent
FROM customEV
WHERE pid = {pid:FixedString(12)}
AND profileId IS NOT NULL
AND profileId != ''
${profileTypeFilter}
+ ${filtersQuery}
+ ),
+ profile_aggregated AS (
+ SELECT
+ profileId,
+ sum(isPageview) AS pageviewsCount,
+ countDistinct(psid) AS sessionsCount,
+ sum(isEvent) AS eventsCount,
+ min(created) AS firstSeen,
+ max(created) AS lastSeen,
+ any(cc) AS cc_agg,
+ any(os) AS os_agg,
+ any(br) AS br_agg,
+ any(dv) AS dv_agg
+ FROM all_profile_data
GROUP BY profileId
),
profile_errors AS (
@@ -5194,7 +5242,7 @@ export class AnalyticsService {
pa.profileId AS profileId,
pa.sessionsCount AS sessionsCount,
pa.pageviewsCount AS pageviewsCount,
- COALESCE(pe.eventsCount, 0) AS eventsCount,
+ pa.eventsCount AS eventsCount,
COALESCE(perr.errorsCount, 0) AS errorsCount,
pa.firstSeen AS firstSeen,
pa.lastSeen AS lastSeen,
@@ -5202,8 +5250,7 @@ export class AnalyticsService {
pa.os_agg AS os,
pa.br_agg AS br,
pa.dv_agg AS dv
- FROM profile_analytics AS pa
- LEFT JOIN profile_events AS pe ON pa.profileId = pe.profileId
+ FROM profile_aggregated AS pa
LEFT JOIN profile_errors AS perr ON pa.profileId = perr.profileId
ORDER BY pa.lastSeen DESC
LIMIT {take:UInt32}
diff --git a/backend/apps/community/src/project/project.controller.ts b/backend/apps/community/src/project/project.controller.ts
index 03f83b353..4899d9a6c 100644
--- a/backend/apps/community/src/project/project.controller.ts
+++ b/backend/apps/community/src/project/project.controller.ts
@@ -621,7 +621,7 @@ export class ProjectController {
await deleteProjectRedis(pid)
- return secret
+ return { captchaSecretKey: secret }
}
@ApiBearerAuth()
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
new file mode 100644
index 000000000..9ffac29a9
--- /dev/null
+++ b/web/app/api/api.server.ts
@@ -0,0 +1,2172 @@
+import { Alerts } from '~/lib/models/Alerts'
+import { Auth } from '~/lib/models/Auth'
+import { User } from '~/lib/models/User'
+import {
+ getAccessToken,
+ getRefreshToken,
+ createAuthCookies,
+ clearAuthCookies,
+ AuthTokens,
+ isPersistentSession,
+} from '~/utils/session.server'
+
+// ============================================================================
+// MARK: API utils
+// ============================================================================
+
+function getApiUrl(): string {
+ const isStaging = process.env.STAGING === 'true'
+ const isSelfhosted = Boolean(process.env.__SELFHOSTED)
+
+ let apiUrl: string | undefined
+
+ if (isSelfhosted || !isStaging) {
+ apiUrl = process.env.API_URL
+ } else {
+ apiUrl = process.env.API_STAGING_URL
+ }
+
+ if (!apiUrl) {
+ throw new Error('API_URL environment variable is not set')
+ }
+
+ // Ensure trailing slash
+ return apiUrl.endsWith('/') ? apiUrl : `${apiUrl}/`
+}
+
+function getClientIP(request: Request): string | null {
+ const headers = request.headers
+
+ const cfIP = headers.get('cf-connecting-ip')
+ if (cfIP) return cfIP
+
+ const realIP = headers.get('x-real-ip')
+ if (realIP) return realIP
+
+ const forwardedFor = headers.get('x-forwarded-for')
+ if (forwardedFor) {
+ return forwardedFor.split(',')[0].trim()
+ }
+
+ return null
+}
+
+async function fetchWithTimeout(
+ input: string | URL,
+ init: Parameters<typeof fetch>[1] = {},
+ timeoutMs = 15000,
+): Promise<Response> {
+ const controller = new AbortController()
+ const id = setTimeout(() => controller.abort(), timeoutMs)
+ return fetch(input, { ...init, signal: controller.signal }).finally(() => clearTimeout(id))
+}
+
+interface ServerFetchOptions {
+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
+ body?: Record<string, unknown>
+ headers?: Record<string, string>
+ /** Skip authentication - for public endpoints */
+ skipAuth?: boolean
+}
+
+interface ServerFetchResult<T> {
+ data: T | null
+ error: string | string[] | null
+ status: number
+ /** New cookies to set (e.g., after token refresh) */
+ cookies: string[]
+}
+
+export async function serverFetch<T = unknown>(
+ request: Request,
+ endpoint: string,
+ options: ServerFetchOptions = {},
+): Promise<ServerFetchResult<T>> {
+ const { method = 'GET', body, headers: customHeaders = {}, skipAuth = false } = options
+
+ const apiUrl = getApiUrl()
+ const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint
+ const url = `${apiUrl}${cleanEndpoint}`
+
+ const fetchHeaders: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ ...customHeaders,
+ }
+
+ const clientIP = getClientIP(request)
+ if (clientIP) {
+ fetchHeaders['X-Client-IP-Address'] = clientIP
+ }
+
+ const userAgent = request.headers.get('user-agent')
+ if (userAgent) {
+ fetchHeaders['User-Agent'] = userAgent
+ }
+
+ if (!skipAuth) {
+ const accessToken = getAccessToken(request)
+ if (accessToken) {
+ fetchHeaders['Authorization'] = `Bearer ${accessToken}`
+ }
+ }
+
+ try {
+ const response = await fetchWithTimeout(url, {
+ method,
+ headers: fetchHeaders,
+ body: body ? JSON.stringify(body) : undefined,
+ })
+
+ if ((response.status === 401 || response.status === 403) && !skipAuth) {
+ const refreshResult = await tryRefreshToken(request)
+
+ if (refreshResult.success && refreshResult.tokens) {
+ fetchHeaders['Authorization'] = `Bearer ${refreshResult.tokens.accessToken}`
+
+ const retryResponse = await fetchWithTimeout(url, {
+ method,
+ headers: fetchHeaders,
+ body: body ? JSON.stringify(body) : undefined,
+ })
+
+ if (retryResponse.ok) {
+ const retryContentType = retryResponse.headers.get('content-type')
+ if (!retryContentType?.includes('application/json')) {
+ return {
+ data: null,
+ error: null,
+ status: retryResponse.status,
+ cookies: refreshResult.cookies,
+ }
+ }
+
+ const data = (await retryResponse.json()) as T
+ return {
+ data,
+ error: null,
+ status: retryResponse.status,
+ cookies: refreshResult.cookies,
+ }
+ }
+
+ const errorData = await parseErrorResponse(retryResponse)
+ return {
+ data: null,
+ error: errorData,
+ status: retryResponse.status,
+ cookies: refreshResult.cookies,
+ }
+ }
+
+ return {
+ data: null,
+ error: 'Session expired',
+ status: 401,
+ cookies: clearAuthCookies(),
+ }
+ }
+
+ if (!response.ok) {
+ const errorData = await parseErrorResponse(response)
+ return {
+ data: null,
+ error: errorData,
+ status: response.status,
+ cookies: [],
+ }
+ }
+
+ const contentType = response.headers.get('content-type')
+ if (!contentType?.includes('application/json')) {
+ return {
+ data: null,
+ error: null,
+ status: response.status,
+ cookies: [],
+ }
+ }
+
+ const data = (await response.json()) as T
+ return {
+ data,
+ error: null,
+ status: response.status,
+ cookies: [],
+ }
+ } catch (error) {
+ console.error('[serverFetch] Request failed:', error)
+ return {
+ data: null,
+ error: error instanceof Error ? error.message : 'Network error',
+ status: 500,
+ cookies: [],
+ }
+ }
+}
+
+export async function streamingServerFetch(
+ request: Request,
+ endpoint: string,
+ options: ServerFetchOptions = {},
+): Promise<Response> {
+ const { method = 'GET', body, headers: customHeaders = {}, skipAuth = false } = options
+
+ const apiUrl = getApiUrl()
+ const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint
+ const url = `${apiUrl}${cleanEndpoint}`
+
+ const fetchHeaders: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ ...customHeaders,
+ }
+
+ const clientIP = getClientIP(request)
+ if (clientIP) {
+ fetchHeaders['X-Client-IP-Address'] = clientIP
+ }
+
+ const userAgent = request.headers.get('user-agent')
+ if (userAgent) {
+ fetchHeaders['User-Agent'] = userAgent
+ }
+
+ if (!skipAuth) {
+ const accessToken = getAccessToken(request)
+ if (accessToken) {
+ fetchHeaders['Authorization'] = `Bearer ${accessToken}`
+ }
+ }
+
+ const response = await fetch(url, {
+ method,
+ headers: fetchHeaders,
+ body: body ? JSON.stringify(body) : undefined,
+ })
+
+ // If 401/403, try to refresh the token and retry
+ if ((response.status === 401 || response.status === 403) && !skipAuth) {
+ const refreshResult = await tryRefreshToken(request)
+
+ if (refreshResult.success && refreshResult.tokens) {
+ fetchHeaders['Authorization'] = `Bearer ${refreshResult.tokens.accessToken}`
+
+ const retryResponse = await fetch(url, {
+ method,
+ headers: fetchHeaders,
+ body: body ? JSON.stringify(body) : undefined,
+ })
+
+ // If the response is not ok, we still want to propagate the refreshed cookies
+ const finalResponse = new Response(retryResponse.body, retryResponse)
+ for (const cookie of refreshResult.cookies) {
+ finalResponse.headers.append('Set-Cookie', cookie)
+ }
+
+ return finalResponse
+ }
+
+ // Token refresh failed - clear auth cookies to prevent stale auth state
+ const clearCookies = clearAuthCookies()
+ const failedResponse = new Response(response.body, response)
+ for (const cookie of clearCookies) {
+ failedResponse.headers.append('Set-Cookie', cookie)
+ }
+ return failedResponse
+ }
+
+ return response
+}
+
+async function tryRefreshToken(
+ request: Request,
+): Promise<{ success: boolean; tokens?: AuthTokens; cookies: string[] }> {
+ const refreshToken = getRefreshToken(request)
+
+ if (!refreshToken) {
+ return { success: false, cookies: [] }
+ }
+
+ const apiUrl = getApiUrl()
+
+ try {
+ const response = await fetch(`${apiUrl}v1/auth/refresh-token`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${refreshToken}`,
+ },
+ })
+
+ if (!response.ok) {
+ return { success: false, cookies: clearAuthCookies() }
+ }
+
+ const data = (await response.json()) as { accessToken: string }
+
+ const tokens: AuthTokens = {
+ accessToken: data.accessToken,
+ refreshToken: refreshToken,
+ }
+
+ const remember = isPersistentSession(request)
+ const cookies = createAuthCookies(tokens, remember)
+
+ return { success: true, tokens, cookies }
+ } catch {
+ return { success: false, cookies: clearAuthCookies() }
+ }
+}
+
+async function parseErrorResponse(response: Response): Promise<string | string[]> {
+ try {
+ const contentType = response.headers.get('content-type')
+ if (!contentType?.includes('application/json')) {
+ return response.statusText || 'Request failed'
+ }
+
+ const data = await response.json()
+
+ // Handle various error response formats
+ if (data.message) {
+ return data.message
+ }
+
+ if (data.error) {
+ return data.error
+ }
+
+ return 'Request failed'
+ } catch {
+ return response.statusText || 'Request failed'
+ }
+}
+
+// ============================================================================
+// MARK: Auth utils
+// ============================================================================
+
+interface AuthenticatedUser {
+ user: User
+ totalMonthlyEvents: number
+}
+
+export async function getAuthenticatedUser(
+ request: Request,
+): Promise<{ user: AuthenticatedUser; cookies: string[] } | null> {
+ const accessToken = getAccessToken(request)
+
+ if (!accessToken) {
+ return null
+ }
+
+ const result = await serverFetch<AuthenticatedUser>(request, 'user/me')
+
+ if (result.error || !result.data) {
+ return null
+ }
+
+ return { user: result.data, cookies: result.cookies }
+}
+
+export async function loginUser(
+ request: Request,
+ credentials: { email: string; password: string },
+ remember: boolean,
+): Promise<{
+ success: boolean
+ data?: Auth
+ error?: string | string[]
+ cookies: string[]
+ requires2FA?: boolean
+}> {
+ const result = await serverFetch<Auth>(request, 'v1/auth/login', {
+ method: 'POST',
+ body: credentials,
+ skipAuth: true,
+ })
+
+ if (result.error || !result.data) {
+ return {
+ success: false,
+ error: result.error || 'Login failed',
+ cookies: [],
+ }
+ }
+
+ const { accessToken, refreshToken, user } = result.data
+
+ if (user.isTwoFactorAuthenticationEnabled) {
+ const cookies = createAuthCookies({ accessToken, refreshToken }, false) // Session cookies for 2FA
+ return {
+ success: true,
+ data: result.data,
+ cookies,
+ requires2FA: true,
+ }
+ }
+
+ const cookies = createAuthCookies({ accessToken, refreshToken }, remember)
+
+ return {
+ success: true,
+ data: result.data,
+ cookies,
+ }
+}
+
+export async function registerUser(
+ request: Request,
+ data: { email: string; password: string; checkIfLeaked?: boolean },
+ remember: boolean,
+): Promise<{
+ success: boolean
+ data?: Auth
+ error?: string | string[]
+ cookies: string[]
+}> {
+ const result = await serverFetch<Auth>(request, 'v1/auth/register', {
+ method: 'POST',
+ body: data,
+ skipAuth: true,
+ })
+
+ if (result.error || !result.data) {
+ return {
+ success: false,
+ error: result.error || 'Registration failed',
+ cookies: [],
+ }
+ }
+
+ const { accessToken, refreshToken } = result.data
+
+ const cookies = createAuthCookies({ accessToken, refreshToken }, remember)
+
+ return {
+ success: true,
+ data: result.data,
+ cookies,
+ }
+}
+
+export async function logoutUser(
+ request: Request,
+ options: { logoutAll?: boolean } = {},
+): Promise<{ cookies: string[] }> {
+ const { logoutAll = false } = options
+
+ if (logoutAll) {
+ // Logout all sessions - uses access token
+ await serverFetch(request, 'v1/auth/logout-all', {
+ method: 'POST',
+ }).catch(() => {
+ // Ignore errors - we're logging out anyway
+ })
+ } else {
+ // Logout single session - uses refresh token
+ const refreshToken = getRefreshToken(request)
+
+ if (refreshToken) {
+ await serverFetch(request, 'v1/auth/logout', {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${refreshToken}`,
+ },
+ skipAuth: true,
+ }).catch(() => {
+ // Ignore errors - we're logging out anyway
+ })
+ }
+ }
+
+ return {
+ cookies: clearAuthCookies(),
+ }
+}
+
+// ============================================================================
+// MARK: Blog API
+// ============================================================================
+
+interface BlogPost {
+ slug: string
+ title: string
+ date: string
+ hidden?: boolean
+ intro?: string
+}
+
+interface BlogPostContent {
+ body: string
+ attributes?: {
+ title?: string
+ hidden?: boolean
+ intro?: string
+ date?: string
+ author?: string
+ twitter_handle?: string
+ standalone?: boolean
+ }
+}
+
+export async function getBlogPosts(request: Request): Promise<BlogPost[] | null> {
+ const result = await serverFetch<BlogPost[]>(request, 'v1/blog', { skipAuth: true })
+
+ if (result.error || !result.data) {
+ return null
+ }
+
+ return result.data
+}
+
+export async function getBlogPost(request: Request, slug: string): Promise<BlogPostContent | null> {
+ const result = await serverFetch<BlogPostContent>(request, `v1/blog/${slug}`, { skipAuth: true })
+
+ if (result.error || !result.data) {
+ return null
+ }
+
+ return result.data
+}
+
+export async function getBlogPostWithCategory(
+ request: Request,
+ category: string,
+ slug: string,
+): Promise<BlogPostContent | null> {
+ const result = await serverFetch<BlogPostContent>(request, `v1/blog/${category}/${slug}`, { skipAuth: true })
+
+ if (result.error || !result.data) {
+ return null
+ }
+
+ return result.data
+}
+
+// ============================================================================
+// MARK: Auth API
+// ============================================================================
+
+export interface AuthMeResponse {
+ user: User
+ totalMonthlyEvents: number
+}
+
+export async function authMeServer(request: Request): Promise<ServerFetchResult<AuthMeResponse>> {
+ return serverFetch<AuthMeResponse>(request, 'user/me')
+}
+
+// ============================================================================
+// MARK: General Stats API
+// ============================================================================
+
+interface GeneralStats {
+ users: number
+ projects: number
+ events: number
+}
+
+export async function getGeneralStats(request: Request): Promise<GeneralStats | null> {
+ const result = await serverFetch<GeneralStats>(request, 'log/generalStats', { skipAuth: true })
+
+ if (result.error || !result.data) {
+ return null
+ }
+
+ return result.data
+}
+
+// ============================================================================
+// MARK: Analytics Data API (Deferred Loading)
+// ============================================================================
+
+export interface AnalyticsFilter {
+ column: string
+ filter: string
+ isExclusive: boolean
+ isContains?: boolean
+}
+
+export interface TrafficLogResponse {
+ params?: Record<string, { name: string; count: number }[]>
+ chart: {
+ x: string[]
+ visits: number[]
+ uniques: number[]
+ sdur: number[]
+ }
+ customs: Record<string, number>
+ properties: Record<string, number>
+ appliedFilters?: AnalyticsFilter[]
+ timeBucket?: string[]
+ meta?: { key: string; current: { sum: number; avg: number }; previous: { sum: number; avg: number } }[]
+}
+
+interface OverallPeriodStats {
+ all: number
+ unique?: number
+ users?: number
+ bounceRate?: number
+ sdur?: number
+}
+
+export interface OverallObject {
+ current: OverallPeriodStats
+ previous: OverallPeriodStats
+ change: number
+ uniqueChange?: number
+ usersChange?: number
+ bounceRateChange?: number
+ sdurChange?: number
+ customEVFilterApplied?: boolean
+ chart?: { x: string[]; visits: number[] }
+}
+
+export interface AnalyticsParams {
+ timeBucket: string
+ period: string
+ filters: AnalyticsFilter[]
+ from?: string
+ to?: string
+ timezone: string
+ mode?: 'periodical' | 'cumulative'
+ password?: string
+}
+
+function serializeFiltersForUrl(filters: AnalyticsFilter[]): string {
+ return JSON.stringify(filters)
+}
+
+export async function getProjectDataServer(
+ request: Request,
+ pid: string,
+ params: AnalyticsParams,
+): Promise<ServerFetchResult<TrafficLogResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('timeBucket', params.timeBucket)
+ queryParams.append('period', params.period)
+ queryParams.append('filters', serializeFiltersForUrl(params.filters))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+ if (params.mode) queryParams.append('mode', params.mode)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<TrafficLogResponse>(request, `log?${queryParams.toString()}`, { headers })
+}
+
+export async function getOverallStatsServer(
+ request: Request,
+ pids: string[],
+ params: AnalyticsParams & { includeChart?: boolean },
+): Promise<ServerFetchResult<Record<string, OverallObject>>> {
+ const pidsParam = `[${pids.map((pid) => `"${pid}"`).join(',')}]`
+
+ const queryParams = new URLSearchParams()
+ queryParams.append('pids', pidsParam)
+ queryParams.append('timeBucket', params.timeBucket)
+ queryParams.append('period', params.period)
+ queryParams.append('filters', serializeFiltersForUrl(params.filters))
+ queryParams.append('includeChart', params.includeChart !== false ? 'true' : 'false')
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<Record<string, OverallObject>>(request, `log/birdseye?${queryParams.toString()}`, { headers })
+}
+
+interface CustomEventsChartResponse {
+ chart?: {
+ events?: Record<string, unknown>
+ }
+}
+
+export async function getCustomEventsDataServer(
+ request: Request,
+ pid: string,
+ params: AnalyticsParams,
+ customEvents: string[],
+): Promise<ServerFetchResult<CustomEventsChartResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('timeBucket', params.timeBucket)
+ queryParams.append('period', params.period)
+ queryParams.append('filters', serializeFiltersForUrl(params.filters))
+ queryParams.append('customEvents', JSON.stringify(customEvents))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<CustomEventsChartResponse>(request, `log/customEvents?${queryParams.toString()}`, { headers })
+}
+
+export interface PerformanceDataResponse {
+ params: Record<string, { name: string; count: number }[]>
+ chart: {
+ x: string[]
+ dns: number[]
+ tls: number[]
+ conn: number[]
+ response: number[]
+ render: number[]
+ domLoad: number[]
+ pageLoad: number[]
+ ttfb: number[]
+ }
+ appliedFilters: AnalyticsFilter[]
+ timeBucket?: string[]
+}
+
+export async function getPerfDataServer(
+ request: Request,
+ pid: string,
+ params: AnalyticsParams & { measure?: string },
+): Promise<ServerFetchResult<PerformanceDataResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('timeBucket', params.timeBucket)
+ queryParams.append('period', params.period)
+ queryParams.append('filters', serializeFiltersForUrl(params.filters))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+ if (params.measure) queryParams.append('measure', params.measure)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<PerformanceDataResponse>(request, `log/performance?${queryParams.toString()}`, { headers })
+}
+
+export interface PerformanceOverallObject {
+ current: { frontend: number; backend: number; network: number }
+ previous: { frontend: number; backend: number; network: number }
+ frontendChange: number
+ backendChange: number
+ networkChange: number
+}
+
+export async function getPerformanceOverallStatsServer(
+ request: Request,
+ pids: string[],
+ params: AnalyticsParams & { measure?: string },
+): Promise<ServerFetchResult<Record<string, PerformanceOverallObject>>> {
+ const pidsParam = `[${pids.map((pid) => `"${pid}"`).join(',')}]`
+
+ const queryParams = new URLSearchParams()
+ queryParams.append('pids', pidsParam)
+ queryParams.append('period', params.period)
+ queryParams.append('filters', serializeFiltersForUrl(params.filters))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+ if (params.measure) queryParams.append('measure', params.measure)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<Record<string, PerformanceOverallObject>>(
+ request,
+ `log/performance/birdseye?${queryParams.toString()}`,
+ { headers },
+ )
+}
+
+interface Session {
+ psid: string
+ cc: string | null
+ os: string | null
+ br: string | null
+ pageviews: number
+ customEvents: number
+ errors: number
+ revenue?: number
+ refunds?: number
+ created: string
+ isLive: 1 | 0
+ sdur?: number
+ sessionStart: string
+ lastActivity: string
+ profileId: string | null
+ isIdentified: 1 | 0
+ isFirstSession: 1 | 0
+}
+
+export interface SessionsResponse {
+ sessions: Session[]
+ take: number
+ skip: number
+ appliedFilters: AnalyticsFilter[]
+}
+
+export async function getSessionsServer(
+ request: Request,
+ pid: string,
+ params: AnalyticsParams & { take?: number; skip?: number },
+): Promise<ServerFetchResult<SessionsResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('period', params.period)
+ queryParams.append('filters', serializeFiltersForUrl(params.filters))
+ queryParams.append('take', String(params.take || 30))
+ queryParams.append('skip', String(params.skip || 0))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<SessionsResponse>(request, `log/sessions?${queryParams.toString()}`, { headers })
+}
+
+interface PageflowItem {
+ type: 'pageview' | 'event' | 'error'
+ value: string
+ created: string
+ metadata?: { key: string; value: string }[]
+}
+
+export interface SessionDetailsResponse {
+ details: {
+ psid: string
+ cc: string | null
+ os: string | null
+ br: string | null
+ dv: string | null
+ pageviews: number
+ customEvents: number
+ errors: number
+ revenue?: number
+ refunds?: number
+ created: string
+ sdur?: number
+ profileId: string | null
+ isIdentified: 1 | 0
+ isFirstSession: 1 | 0
+ }
+ chart?: {
+ x: string[]
+ pageviews?: number[]
+ customEvents?: number[]
+ errors?: number[]
+ }
+ pages?: PageflowItem[]
+ timeBucket?: string
+}
+
+export async function getSessionServer(
+ request: Request,
+ pid: string,
+ psid: string,
+ timezone: string,
+ password?: string,
+): Promise<ServerFetchResult<SessionDetailsResponse>> {
+ const queryParams = new URLSearchParams({
+ pid,
+ psid,
+ timezone,
+ })
+
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<SessionDetailsResponse>(request, `log/session?${queryParams.toString()}`, { headers })
+}
+
+interface SwetrixError {
+ eid: string
+ name: string
+ message: string
+ filename: string
+ count: number
+ last_seen: string
+ status: 'active' | 'regressed' | 'fixed' | 'resolved'
+ users: number
+ sessions: number
+}
+
+export interface ErrorsResponse {
+ errors: SwetrixError[]
+}
+
+export async function getErrorsServer(
+ request: Request,
+ pid: string,
+ params: AnalyticsParams & { take?: number; skip?: number; options?: Record<string, unknown> },
+): Promise<ServerFetchResult<ErrorsResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('timeBucket', params.timeBucket)
+ queryParams.append('period', params.period)
+ queryParams.append('filters', serializeFiltersForUrl(params.filters))
+ queryParams.append('options', JSON.stringify(params.options || {}))
+ queryParams.append('take', String(params.take || 30))
+ queryParams.append('skip', String(params.skip || 0))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<ErrorsResponse>(request, `log/errors?${queryParams.toString()}`, { headers })
+}
+
+export interface ErrorDetailsResponse {
+ details: {
+ eid: string
+ name: string
+ message: string
+ filename: string
+ lineno: number
+ colno: number
+ count: number
+ last_seen: string
+ first_seen: string
+ status: 'active' | 'regressed' | 'fixed' | 'resolved'
+ users: number
+ sessions: number
+ stackTrace?: string
+ }
+ chart?: {
+ x: string[]
+ occurrences: number[]
+ affectedUsers: number[]
+ }
+ params?: Record<string, { name: string; count: number }[]>
+ metadata?: { key: string; value: string; count: number }[]
+ timeBucket?: string
+}
+
+export async function getErrorServer(
+ request: Request,
+ pid: string,
+ eid: string,
+ params: AnalyticsParams & { options?: Record<string, unknown> },
+): Promise<ServerFetchResult<ErrorDetailsResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('eid', eid)
+ queryParams.append('timeBucket', params.timeBucket)
+ queryParams.append('period', params.period)
+ queryParams.append('filters', serializeFiltersForUrl(params.filters))
+ queryParams.append('options', JSON.stringify(params.options || {}))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<ErrorDetailsResponse>(request, `log/error?${queryParams.toString()}`, { headers })
+}
+
+export interface ErrorOverviewResponse {
+ chart?: {
+ x: string[]
+ occurrences: number[]
+ affectedUsers: number[]
+ }
+ stats?: {
+ totalErrors: number
+ uniqueErrors: number
+ affectedUsers: number
+ errorRate?: number
+ affectedSessions?: number
+ }
+ appliedFilters?: AnalyticsFilter[]
+}
+
+export async function getErrorOverviewServer(
+ request: Request,
+ pid: string,
+ params: AnalyticsParams & { options?: Record<string, unknown> },
+): Promise<ServerFetchResult<ErrorOverviewResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('timeBucket', params.timeBucket)
+ queryParams.append('period', params.period)
+ queryParams.append('filters', serializeFiltersForUrl(params.filters))
+ queryParams.append('options', JSON.stringify(params.options || {}))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<ErrorOverviewResponse>(request, `log/error-overview?${queryParams.toString()}`, { headers })
+}
+
+// ============================================================================
+// MARK: Feature Flags API (Deferred Loading)
+// ============================================================================
+
+export interface TargetingRule {
+ column: string
+ filter: string
+ isExclusive: boolean
+}
+
+export interface ProjectFeatureFlag {
+ id: string
+ key: string
+ description: string | null
+ flagType: 'boolean' | 'rollout'
+ rolloutPercentage: number
+ targetingRules: TargetingRule[] | null
+ enabled: boolean
+ pid: string
+ created: string
+}
+
+export interface FeatureFlagsResponse {
+ results: ProjectFeatureFlag[]
+ total: number
+}
+
+export async function getProjectFeatureFlagsServer(
+ request: Request,
+ projectId: string,
+ take = 20,
+ skip = 0,
+ search?: string,
+): Promise<ServerFetchResult<FeatureFlagsResponse>> {
+ const params = new URLSearchParams({
+ take: String(take),
+ skip: String(skip),
+ })
+
+ if (search?.trim()) {
+ params.append('search', search.trim())
+ }
+
+ return serverFetch<FeatureFlagsResponse>(request, `feature-flag/project/${projectId}?${params.toString()}`)
+}
+
+export interface FeatureFlagStats {
+ evaluations: number
+ profileCount: number
+ trueCount: number
+ falseCount: number
+ truePercentage: number
+}
+
+export async function getFeatureFlagStatsServer(
+ request: Request,
+ flagId: string,
+ period: string,
+ from = '',
+ to = '',
+ timezone?: string,
+): Promise<ServerFetchResult<FeatureFlagStats>> {
+ const params = new URLSearchParams({ period })
+ if (from) params.append('from', from)
+ if (to) params.append('to', to)
+ if (timezone) params.append('timezone', timezone)
+
+ return serverFetch<FeatureFlagStats>(request, `feature-flag/${flagId}/stats?${params.toString()}`)
+}
+
+export interface FeatureFlagProfile {
+ profileId: string
+ isIdentified: boolean
+ lastResult: boolean
+ evaluationCount: number
+ lastEvaluated: string
+}
+
+export interface FeatureFlagProfilesResponse {
+ profiles: FeatureFlagProfile[]
+ total: number
+}
+
+export async function getFeatureFlagProfilesServer(
+ request: Request,
+ flagId: string,
+ period: string,
+ from = '',
+ to = '',
+ timezone?: string,
+ take = 15,
+ skip = 0,
+ resultFilter?: string,
+): Promise<ServerFetchResult<FeatureFlagProfilesResponse>> {
+ const params = new URLSearchParams({
+ period,
+ take: String(take),
+ skip: String(skip),
+ })
+ if (from) params.append('from', from)
+ if (to) params.append('to', to)
+ if (timezone) params.append('timezone', timezone)
+ if (resultFilter && resultFilter !== 'all') params.append('result', resultFilter)
+
+ return serverFetch<FeatureFlagProfilesResponse>(request, `feature-flag/${flagId}/profiles?${params.toString()}`)
+}
+
+// ============================================================================
+// MARK: Goals API (Deferred Loading)
+// ============================================================================
+
+export interface Goal {
+ id: string
+ name: string
+ type: 'pageview' | 'custom_event'
+ matchType: 'exact' | 'contains'
+ value: string | null
+ metadataFilters: { key: string; value: string }[] | null
+ active: boolean
+ pid: string
+ created: string
+}
+
+export interface GoalsResponse {
+ results: Goal[]
+ total: number
+}
+
+export async function getProjectGoalsServer(
+ request: Request,
+ projectId: string,
+ take = 20,
+ skip = 0,
+ search?: string,
+): Promise<ServerFetchResult<GoalsResponse>> {
+ const params = new URLSearchParams({
+ take: String(take),
+ skip: String(skip),
+ })
+
+ if (search?.trim()) {
+ params.append('search', search.trim())
+ }
+
+ return serverFetch<GoalsResponse>(request, `goal/project/${projectId}?${params.toString()}`)
+}
+
+export interface GoalStats {
+ conversions: number
+ uniqueSessions: number
+ conversionRate: number
+ previousConversions: number
+ trend: number
+}
+
+export async function getGoalStatsServer(
+ request: Request,
+ goalId: string,
+ period: string,
+ from = '',
+ to = '',
+ timezone?: string,
+): Promise<ServerFetchResult<GoalStats>> {
+ const params = new URLSearchParams({ period })
+ if (from) params.append('from', from)
+ if (to) params.append('to', to)
+ if (timezone) params.append('timezone', timezone)
+
+ return serverFetch<GoalStats>(request, `goal/${goalId}/stats?${params.toString()}`)
+}
+
+export interface GoalChartData {
+ x: string[]
+ conversions: number[]
+ uniqueSessions: number[]
+}
+
+export async function getGoalChartServer(
+ request: Request,
+ goalId: string,
+ period: string,
+ from = '',
+ to = '',
+ timeBucket = 'day',
+ timezone?: string,
+): Promise<ServerFetchResult<{ chart: GoalChartData }>> {
+ const params = new URLSearchParams({ period, timeBucket })
+ if (from) params.append('from', from)
+ if (to) params.append('to', to)
+ if (timezone) params.append('timezone', timezone)
+
+ return serverFetch<{ chart: GoalChartData }>(request, `goal/${goalId}/chart?${params.toString()}`)
+}
+
+// ============================================================================
+// MARK: Alerts API (Deferred Loading)
+// ============================================================================
+
+export interface AlertsResponse {
+ results: Alerts[]
+ total: number
+}
+
+export async function getProjectAlertsServer(
+ request: Request,
+ projectId: string,
+ take = 25,
+ skip = 0,
+): Promise<ServerFetchResult<AlertsResponse>> {
+ const params = new URLSearchParams({
+ take: String(take),
+ skip: String(skip),
+ })
+
+ return serverFetch<AlertsResponse>(request, `alert/project/${projectId}?${params.toString()}`)
+}
+
+// ============================================================================
+// MARK: Funnels API (Deferred Loading)
+// ============================================================================
+
+export interface FunnelDataResponse {
+ funnel: {
+ value: string
+ events: number
+ eventsPerc: number
+ eventsPercStep: number
+ dropoff: number
+ dropoffPerc: number
+ dropoffPercStep: number
+ }[]
+ totalPageviews: number
+}
+
+export async function getFunnelDataServer(
+ request: Request,
+ pid: string,
+ funnelId: string,
+ period: string,
+ from: string,
+ to: string,
+ timezone: string,
+ password?: string,
+): Promise<ServerFetchResult<FunnelDataResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('period', period)
+ queryParams.append('funnelId', funnelId)
+ if (from) queryParams.append('from', from)
+ if (to) queryParams.append('to', to)
+ if (timezone) queryParams.append('timezone', timezone)
+
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<FunnelDataResponse>(request, `log/funnel?${queryParams.toString()}`, { headers })
+}
+
+// ============================================================================
+// MARK: Captcha API (Deferred Loading)
+// ============================================================================
+
+interface CaptchaPanelData {
+ name: string
+ count: number
+ cc?: string
+}
+
+interface CaptchaChartData {
+ x: string[]
+ results: number[]
+}
+
+export interface CaptchaDataResponse {
+ params: Record<string, CaptchaPanelData[]>
+ chart?: CaptchaChartData
+}
+
+export async function getCaptchaDataServer(
+ request: Request,
+ pid: string,
+ timeBucket = 'hour',
+ period = '3d',
+ filters: AnalyticsFilter[] = [],
+ from = '',
+ to = '',
+ password?: string,
+): Promise<ServerFetchResult<CaptchaDataResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('timeBucket', timeBucket)
+ queryParams.append('period', period)
+ queryParams.append('filters', JSON.stringify(filters))
+ if (from) queryParams.append('from', from)
+ if (to) queryParams.append('to', to)
+
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<CaptchaDataResponse>(request, `log/captcha?${queryParams.toString()}`, { headers })
+}
+
+// ============================================================================
+// MARK: Experiments API (Deferred Loading)
+// ============================================================================
+
+type ExperimentStatus = 'draft' | 'running' | 'paused' | 'completed'
+
+export type ExposureTrigger = 'feature_flag' | 'custom_event'
+
+export type MultipleVariantHandling = 'exclude' | 'first_exposure'
+
+export type FeatureFlagMode = 'create' | 'link'
+
+export interface ExperimentVariant {
+ id?: string
+ name: string
+ key: string
+ description?: string | null
+ rolloutPercentage: number
+ isControl: boolean
+}
+
+export interface Experiment {
+ id: string
+ name: string
+ description: string | null
+ hypothesis?: string | null
+ status: ExperimentStatus
+ startedAt: string | null
+ endedAt: string | null
+ featureFlagKey: string | null
+ exposureTrigger: ExposureTrigger
+ customEventName?: string | null
+ multipleVariantHandling: MultipleVariantHandling
+ filterInternalUsers: boolean
+ featureFlagMode: FeatureFlagMode
+ featureFlagId: string | null
+ goalId: string | null
+ variants: ExperimentVariant[]
+ pid: string
+ created: string
+}
+
+export async function getExperimentServer(
+ request: Request,
+ experimentId: string,
+): Promise<ServerFetchResult<Experiment>> {
+ return serverFetch<Experiment>(request, `experiment/${experimentId}`)
+}
+
+export interface ExperimentVariantResult {
+ key: string
+ name: string
+ isControl: boolean
+ exposures: number
+ conversions: number
+ conversionRate: number
+ improvement: number
+ probabilityOfBeingBest: number
+}
+
+export interface ExperimentChartData {
+ x: string[]
+ winProbability: Record<string, number[]>
+}
+
+export interface ExperimentResults {
+ experimentId: string
+ status: ExperimentStatus
+ hasWinner: boolean
+ winnerKey: string | null
+ totalExposures: number
+ totalConversions: number
+ confidenceLevel: number
+ variants: ExperimentVariantResult[]
+ chart?: ExperimentChartData
+}
+
+export async function getExperimentResultsServer(
+ request: Request,
+ experimentId: string,
+ period: string,
+ timeBucket: string,
+ from = '',
+ to = '',
+ timezone?: string,
+): Promise<ServerFetchResult<ExperimentResults>> {
+ const params = new URLSearchParams({ period, timeBucket })
+ if (from) params.append('from', from)
+ if (to) params.append('to', to)
+ if (timezone) params.append('timezone', timezone)
+
+ return serverFetch<ExperimentResults>(request, `experiment/${experimentId}/results?${params.toString()}`)
+}
+
+export async function getGoalServer(request: Request, goalId: string): Promise<ServerFetchResult<Goal>> {
+ return serverFetch<Goal>(request, `goal/${goalId}`)
+}
+
+// ============================================================================
+// MARK: Profiles API (Deferred Loading)
+// ============================================================================
+
+export interface ApiProfile {
+ profileId: string
+ isIdentified: boolean
+ sessionsCount: number
+ pageviewsCount: number
+ eventsCount: number
+ errorsCount: number
+ firstSeen: string
+ lastSeen: string
+ cc: string | null
+ os: string | null
+ br: string | null
+ dv: string | null
+}
+
+export interface ProfilesResponse {
+ profiles: ApiProfile[]
+}
+
+export async function getProfilesServer(
+ request: Request,
+ pid: string,
+ period = '3d',
+ filters: AnalyticsFilter[] = [],
+ from = '',
+ to = '',
+ take = 30,
+ skip = 0,
+ timezone = '',
+ profileType: 'all' | 'anonymous' | 'identified' = 'all',
+ password?: string,
+): Promise<ServerFetchResult<ProfilesResponse>> {
+ const params = new URLSearchParams()
+ params.append('pid', pid)
+ params.append('take', String(take))
+ params.append('skip', String(skip))
+ params.append('period', period)
+ params.append('filters', JSON.stringify(filters))
+ params.append('profileType', profileType)
+ if (from) params.append('from', from)
+ if (to) params.append('to', to)
+ if (timezone) params.append('timezone', timezone)
+
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<ProfilesResponse>(request, `log/profiles?${params.toString()}`, { headers })
+}
+
+interface ProfileDetails {
+ profileId: string
+ isAnonymous: boolean
+ created: string
+ pageviews: number
+ sessions: number
+ customEvents: number
+ errors: number
+ revenue?: number
+ refunds?: number
+ revenueCurrency?: string
+ lastSeen: string
+ country?: string
+ city?: string
+ region?: string
+ locale?: string
+ os?: string
+ browser?: string
+ device?: string
+ properties?: Record<string, unknown>
+ eventsInPeriod?: number
+ sessionsInPeriod?: number
+}
+
+export interface ProfileDetailsResponse extends ProfileDetails {
+ chart: unknown
+ timeBucket: string
+}
+
+export async function getProfileServer(
+ request: Request,
+ pid: string,
+ profileId: string,
+ period = '7d',
+ from = '',
+ to = '',
+ timezone = '',
+ password?: string,
+): Promise<ServerFetchResult<ProfileDetailsResponse>> {
+ const params = new URLSearchParams()
+ params.append('pid', pid)
+ params.append('profileId', profileId)
+ params.append('period', period)
+ if (from) params.append('from', from)
+ if (to) params.append('to', to)
+ if (timezone) params.append('timezone', timezone)
+
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<ProfileDetailsResponse>(request, `log/profile?${params.toString()}`, { headers })
+}
+
+interface ProfileSession {
+ psid: string
+ cc: string | null
+ os: string | null
+ br: string | null
+ dv: string | null
+ pageviews: number
+ customEvents: number
+ errors: number
+ revenue?: number
+ refunds?: number
+ created: string
+ duration?: number
+ active?: boolean
+ isLive?: boolean
+}
+
+export interface ProfileSessionsResponse {
+ sessions: ProfileSession[]
+}
+
+export async function getProfileSessionsServer(
+ request: Request,
+ pid: string,
+ profileId: string,
+ period = '3d',
+ filters: AnalyticsFilter[] = [],
+ from = '',
+ to = '',
+ take = 30,
+ skip = 0,
+ timezone = '',
+ password?: string,
+): Promise<ServerFetchResult<ProfileSessionsResponse>> {
+ const params = new URLSearchParams()
+ params.append('pid', pid)
+ params.append('profileId', profileId)
+ params.append('take', String(take))
+ params.append('skip', String(skip))
+ params.append('period', period)
+ params.append('filters', JSON.stringify(filters))
+ if (from) params.append('from', from)
+ if (to) params.append('to', to)
+ if (timezone) params.append('timezone', timezone)
+
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<ProfileSessionsResponse>(request, `log/profile/sessions?${params.toString()}`, { headers })
+}
+
+// ============================================================================
+// MARK: Projects API
+// ============================================================================
+
+export interface Project {
+ id: string
+ name: string
+ origins: string[] | null
+ ipBlacklist: string[] | null
+ active: boolean
+ public: boolean
+ isPasswordProtected: boolean
+ passwordHash: string | null
+ admin: {
+ id: string
+ email: string
+ }
+ created: string
+ isOwner: boolean
+ isLocked: boolean
+ isCaptchaProject: boolean
+ isCaptchaEnabled: boolean
+ isAnalyticsProject: boolean
+ captchaSecretKey: string | null
+ role: string
+ botsProtectionLevel: string
+ isTransferring: boolean
+ share?: {
+ id: string
+ confirmed: boolean
+ role: string
+ }
+ funnels?: { id: string; name: string }[]
+}
+
+export async function getProjectServer(
+ request: Request,
+ pid: string,
+ password?: string,
+): Promise<ServerFetchResult<Project>> {
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<Project>(request, `project/${pid}`, { headers })
+}
+
+// ============================================================================
+// MARK: Custom Events Metadata API
+// ============================================================================
+
+export interface CustomEventsMetadataResponse {
+ result: Array<{ key: string; value: string; count: number }>
+}
+
+export async function getCustomEventsMetadataServer(
+ request: Request,
+ pid: string,
+ event: string,
+ params: {
+ timeBucket?: string
+ period?: string
+ from?: string
+ to?: string
+ timezone?: string
+ password?: string
+ } = {},
+): Promise<ServerFetchResult<CustomEventsMetadataResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('event', event)
+ queryParams.append('timeBucket', params.timeBucket || 'hour')
+ queryParams.append('period', params.period || '1d')
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<CustomEventsMetadataResponse>(request, `log/meta?${queryParams.toString()}`, { headers })
+}
+
+// ============================================================================
+// MARK: Property Metadata API
+// ============================================================================
+
+export interface PropertyMetadataResponse {
+ result: Array<{ key: string; value: string; count: number }>
+}
+
+export async function getPropertyMetadataServer(
+ request: Request,
+ pid: string,
+ property: string,
+ params: {
+ timeBucket?: string
+ period?: string
+ from?: string
+ to?: string
+ filters?: AnalyticsFilter[]
+ timezone?: string
+ password?: string
+ } = {},
+): Promise<ServerFetchResult<PropertyMetadataResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('property', property)
+ queryParams.append('timeBucket', params.timeBucket || 'hour')
+ queryParams.append('period', params.period || '1d')
+ queryParams.append('filters', JSON.stringify(params.filters || []))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<PropertyMetadataResponse>(request, `log/property?${queryParams.toString()}`, { headers })
+}
+
+// ============================================================================
+// MARK: Error Sessions API
+// ============================================================================
+
+export interface ErrorAffectedSession {
+ psid: string
+ profileId: string | null
+ cc: string | null
+ br: string | null
+ os: string | null
+ firstErrorAt: string
+ lastErrorAt: string
+ errorCount: number
+}
+
+export interface ErrorSessionsResponse {
+ sessions: ErrorAffectedSession[]
+ total: number
+}
+
+export async function getErrorSessionsServer(
+ request: Request,
+ pid: string,
+ eid: string,
+ params: {
+ timeBucket?: string
+ period?: string
+ from?: string
+ to?: string
+ take?: number
+ skip?: number
+ password?: string
+ } = {},
+): Promise<ServerFetchResult<ErrorSessionsResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('eid', eid)
+ queryParams.append('timeBucket', params.timeBucket || 'hour')
+ queryParams.append('period', params.period || '7d')
+ queryParams.append('take', String(params.take || 10))
+ queryParams.append('skip', String(params.skip || 0))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<ErrorSessionsResponse>(request, `log/error-sessions?${queryParams.toString()}`, { headers })
+}
+
+// ============================================================================
+// MARK: Live Visitors API
+// ============================================================================
+
+export interface LiveStats {
+ [pid: string]: number
+}
+
+export async function getLiveVisitorsServer(
+ request: Request,
+ pids: string[],
+ password?: string,
+): Promise<ServerFetchResult<LiveStats>> {
+ const pidsParam = `[${pids.map((pid) => `"${pid}"`).join(',')}]`
+
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<LiveStats>(request, `log/hb?pids=${pidsParam}`, { headers })
+}
+
+export interface LiveVisitorInfo {
+ psid: string
+ dv: string
+ br: string
+ os: string
+ cc: string
+}
+
+export async function getLiveVisitorsInfoServer(
+ request: Request,
+ pid: string,
+ password?: string,
+): Promise<ServerFetchResult<LiveVisitorInfo[]>> {
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<LiveVisitorInfo[]>(request, `log/live-visitors?pid=${pid}`, { headers })
+}
+
+// ============================================================================
+// MARK: Custom Events Chart API
+// ============================================================================
+
+export interface ProjectDataCustomEventsResponse {
+ chart?: {
+ events?: Record<string, { x: string[]; y: number[] }>
+ }
+ customs?: Record<string, number>
+}
+
+export async function getProjectDataCustomEventsServer(
+ request: Request,
+ pid: string,
+ params: {
+ timeBucket?: string
+ period?: string
+ filters?: AnalyticsFilter[]
+ from?: string
+ to?: string
+ timezone?: string
+ customEvents?: string[]
+ password?: string
+ } = {},
+): Promise<ServerFetchResult<ProjectDataCustomEventsResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('timeBucket', params.timeBucket || 'hour')
+ queryParams.append('period', params.period || '3d')
+ queryParams.append('filters', JSON.stringify(params.filters || []))
+ queryParams.append('customEvents', JSON.stringify(params.customEvents || []))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<ProjectDataCustomEventsResponse>(request, `log/custom-events?${queryParams.toString()}`, {
+ headers,
+ })
+}
+
+// ============================================================================
+// MARK: SSO API
+// ============================================================================
+
+export type SSOProvider = 'google' | 'github' | 'openid-connect'
+
+export interface SSOAuthURLResponse {
+ uuid: string
+ auth_url: string
+ expires_in: number
+}
+
+export async function generateSSOAuthURLServer(
+ request: Request,
+ provider: SSOProvider,
+ redirectUrl?: string,
+): Promise<ServerFetchResult<SSOAuthURLResponse>> {
+ const payload: { provider: SSOProvider; redirectUrl?: string } = { provider }
+ if (redirectUrl) {
+ payload.redirectUrl = redirectUrl
+ }
+
+ const endpoint = provider === 'openid-connect' ? 'v1/auth/oidc/initiate' : 'v1/auth/sso/generate'
+
+ return serverFetch<SSOAuthURLResponse>(request, endpoint, {
+ method: 'POST',
+ body: payload,
+ skipAuth: true,
+ })
+}
+
+export interface SSOHashResponse {
+ accessToken: string
+ refreshToken: string
+ user: User
+ totalMonthlyEvents: number
+}
+
+export async function getJWTBySSOHashServer(
+ request: Request,
+ hash: string,
+ provider: SSOProvider,
+): Promise<ServerFetchResult<SSOHashResponse>> {
+ const endpoint = provider === 'openid-connect' ? 'v1/auth/oidc/hash' : 'v1/auth/sso/hash'
+ const body = provider === 'openid-connect' ? { hash } : { hash, provider }
+
+ return serverFetch<SSOHashResponse>(request, endpoint, {
+ method: 'POST',
+ body,
+ skipAuth: true,
+ })
+}
+
+export async function processSSOTokenCommunityEditionServer(
+ request: Request,
+ code: string,
+ hash: string,
+ redirectUrl: string,
+): Promise<ServerFetchResult<unknown>> {
+ return serverFetch<unknown>(request, 'v1/auth/oidc/process-token', {
+ method: 'POST',
+ body: { code, hash, redirectUrl },
+ skipAuth: true,
+ })
+}
+
+export async function linkBySSOHashServer(
+ request: Request,
+ hash: string,
+ provider: SSOProvider,
+): Promise<ServerFetchResult<unknown>> {
+ return serverFetch<unknown>(request, 'v1/auth/sso/link_by_hash', {
+ method: 'POST',
+ body: { hash, provider },
+ })
+}
+
+export async function processSSOTokenServer(
+ request: Request,
+ token: string,
+ hash: string,
+): Promise<ServerFetchResult<unknown>> {
+ return serverFetch<unknown>(request, 'v1/auth/sso/process-token', {
+ method: 'POST',
+ body: { token, hash },
+ skipAuth: true,
+ })
+}
+
+// ============================================================================
+// MARK: User Flow API
+// ============================================================================
+
+interface UserFlowNode {
+ id: string
+ name: string
+ count: number
+}
+
+interface UserFlowLink {
+ source: string
+ target: string
+ value: number
+}
+
+export interface UserFlowResponse {
+ nodes: UserFlowNode[]
+ links: UserFlowLink[]
+}
+
+export async function getUserFlowServer(
+ request: Request,
+ pid: string,
+ params: {
+ timeBucket?: string
+ period?: string
+ filters?: AnalyticsFilter[]
+ from?: string
+ to?: string
+ timezone?: string
+ password?: string
+ } = {},
+): Promise<ServerFetchResult<UserFlowResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('timeBucket', params.timeBucket || 'hour')
+ queryParams.append('period', params.period || '3d')
+ queryParams.append('filters', JSON.stringify(params.filters || []))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<UserFlowResponse>(request, `log/user-flow?${queryParams.toString()}`, { headers })
+}
+
+// ============================================================================
+// MARK: Filters API
+// ============================================================================
+
+export async function getFiltersServer(
+ request: Request,
+ pid: string,
+ type: string,
+ password?: string,
+): Promise<ServerFetchResult<string[]>> {
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<string[]>(request, `log/filters?pid=${pid}&type=${type}`, { headers })
+}
+
+export async function getErrorsFiltersServer(
+ request: Request,
+ pid: string,
+ type: string,
+ password?: string,
+): Promise<ServerFetchResult<string[]>> {
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<string[]>(request, `log/errors-filters?pid=${pid}&type=${type}`, { headers })
+}
+
+export interface VersionFilter {
+ name: string
+ version: string
+}
+
+export async function getVersionFiltersServer(
+ request: Request,
+ pid: string,
+ type: 'traffic' | 'errors',
+ column: 'br' | 'os',
+ password?: string,
+): Promise<ServerFetchResult<VersionFilter[]>> {
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<VersionFilter[]>(request, `log/filters/versions?pid=${pid}&type=${type}&column=${column}`, {
+ headers,
+ })
+}
+
+// ============================================================================
+// MARK: Google Search Console API
+// ============================================================================
+
+export async function processGSCTokenServer(
+ request: Request,
+ code: string,
+ state: string,
+): Promise<ServerFetchResult<{ pid: string }>> {
+ return serverFetch<{ pid: string }>(request, 'v1/project/gsc/process-token', {
+ method: 'POST',
+ body: { code, state },
+ })
+}
+
+interface GSCKeyword {
+ name: string
+ count: number
+ impressions: number
+ position: number
+ ctr: number
+}
+
+export interface GSCKeywordsResponse {
+ keywords: GSCKeyword[]
+ notConnected?: boolean
+}
+
+export async function getGSCKeywordsServer(
+ request: Request,
+ pid: string,
+ params: {
+ period?: string
+ from?: string
+ to?: string
+ timezone?: string
+ password?: string
+ } = {},
+): Promise<ServerFetchResult<GSCKeywordsResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('period', params.period || '3d')
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<GSCKeywordsResponse>(request, `log/keywords?${queryParams.toString()}`, { headers })
+}
+
+// ============================================================================
+// MARK: Revenue API
+// ============================================================================
+
+export interface RevenueStatus {
+ connected: boolean
+ provider?: string
+ currency?: string
+ lastSyncAt?: string
+}
+
+export async function getRevenueStatusServer(request: Request, pid: string): Promise<ServerFetchResult<RevenueStatus>> {
+ return serverFetch<RevenueStatus>(request, `project/${pid}/revenue/status`)
+}
+
+interface RevenueStats {
+ totalRevenue: number
+ salesCount: number
+ refundsCount: number
+ refundsAmount: number
+ averageOrderValue: number
+ currency: string
+ mrr: number
+ revenueChange: number
+}
+
+interface RevenueChart {
+ x: string[]
+ revenue: number[]
+ salesCount: number[]
+ refundsAmount: number[]
+}
+
+export interface RevenueDataResponse {
+ stats: RevenueStats
+ chart: RevenueChart
+}
+
+export async function getRevenueDataServer(
+ request: Request,
+ pid: string,
+ params: {
+ period: string
+ from?: string
+ to?: string
+ timezone?: string
+ timeBucket?: string
+ },
+): Promise<ServerFetchResult<RevenueDataResponse>> {
+ const queryParams = new URLSearchParams({
+ pid,
+ period: params.period,
+ })
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+ if (params.timeBucket) queryParams.append('timeBucket', params.timeBucket)
+
+ return serverFetch<RevenueDataResponse>(request, `log/revenue?${queryParams.toString()}`)
+}
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index 0321f2872..a36b72395 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -1,2199 +1,3 @@
-import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
-import createAuthRefreshInterceptor from 'axios-auth-refresh'
-import _isArray from 'lodash/isArray'
-import _isEmpty from 'lodash/isEmpty'
-import _map from 'lodash/map'
-
-import { DEFAULT_ALERTS_TAKE, API_URL } from '~/lib/constants'
-import { Alerts } from '~/lib/models/Alerts'
-import { Auth, SSOProvider } from '~/lib/models/Auth'
-import { Metainfo } from '~/lib/models/Metainfo'
-import { Role } from '~/lib/models/Organisation'
-import {
- Project,
- Overall,
- LiveStats,
- Funnel,
- SwetrixError,
- SwetrixErrorDetails,
- SessionDetails,
- Session,
- Profile,
- ProfileDetails,
-} from '~/lib/models/Project'
-import { Stats } from '~/lib/models/Stats'
-import { Subscriber } from '~/lib/models/Subscriber'
-import { User } from '~/lib/models/User'
-import { Filter, ProjectViewCustomEvent } from '~/pages/Project/View/interfaces/traffic'
-import { getAccessToken, setAccessToken } from '~/utils/accessToken'
-import { logout } from '~/utils/auth'
-import { getRefreshToken } from '~/utils/refreshToken'
-
-const api = axios.create({
- baseURL: API_URL,
-})
-
-// Function that will be called to refresh authorization
-const refreshAuthLogic = (failedRequest: { response: AxiosResponse }) =>
- axios
- .post(`${API_URL}v1/auth/refresh-token`, null, {
- headers: {
- Authorization: `Bearer ${getRefreshToken()}`,
- },
- })
- .then((tokenRefreshResponse) => {
- const { accessToken } = tokenRefreshResponse.data
- setAccessToken(accessToken)
-
- failedRequest.response.config.headers.Authorization = `Bearer ${accessToken}`
- return Promise.resolve()
- })
- .catch((error) => {
- logout()
- // If user session is invalid, this rejection will be thrown to authMe in AuthProvider and will reset user there too
- return Promise.reject(error)
- })
-
-// Instantiate the interceptor
-createAuthRefreshInterceptor(api, refreshAuthLogic, {
- statusCodes: [401, 403],
-})
-
-api.interceptors.request.use(
- (config) => {
- const token = getAccessToken()
- if (token) {
- config.headers.Authorization = `Bearer ${token}`
- }
- return config
- },
- (error) => {
- return Promise.reject(error)
- },
-)
-
-export const authMe = (config?: AxiosRequestConfig) =>
- api.get('user/me', config).then(
- (
- response,
- ): {
- user: User
- totalMonthlyEvents: number
- } => response.data,
- )
-
-export const logoutApi = (refreshToken: string | null) =>
- axios
- .post(`${API_URL}v1/auth/logout`, null, {
- headers: {
- Authorization: `Bearer ${refreshToken}`,
- },
- })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const logoutAllApi = () =>
- api
- .post(`${API_URL}v1/auth/logout-all`)
- .then((response) => response.data)
- .catch((error) => {
- throw new Error(error.respon)
- })
-
-export const login = (credentials: { email: string; password: string }) =>
- api
- .post('v1/auth/login', credentials)
- .then((response): Auth => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const signup = (data: { email: string; password: string; checkIfLeaked?: boolean }) =>
- api
- .post('v1/auth/register', data)
- .then((response): Auth => response.data)
- .catch((error) => {
- const errorsArray = error.response.data.message
- if (_isArray(errorsArray)) {
- throw errorsArray
- }
- throw new Error(errorsArray)
- })
-
-export const deleteUser = (deletionFeedback?: string) =>
- api
- .delete('/user', {
- data: {
- feedback: deletionFeedback,
- },
- })
- .then((response) => response.data)
- .catch((error) => {
- throw new Error(JSON.stringify(error.response.data))
- })
-
-export const changeUserDetails = (data: User) =>
- api
- .put('/user', data)
- .then((response): User => response.data)
- .catch((error) => {
- const errorsArray = error.response.data.message
- if (_isArray(errorsArray)) {
- throw errorsArray
- }
- throw new Error(errorsArray)
- })
-
-export const setShowLiveVisitorsInTitle = (show: boolean) =>
- api
- .put('/user/live-visitors', { show })
- .then((response): Partial<User> => response.data)
- .catch((error) => {
- const errorsArray = error.response.data.message
- if (_isArray(errorsArray)) {
- throw errorsArray
- }
- throw new Error(errorsArray)
- })
-
-export const forgotPassword = (email: { email: string }) =>
- api
- .post('v1/auth/reset-password', email)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const confirmEmail = () =>
- api
- .post('/user/confirm_email')
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const createNewPassword = (id: string, password: string) =>
- api
- .post(`v1/auth/reset-password/confirm/${id}`, { newPassword: password })
- .then((response) => response.data)
- .catch((error) => {
- const errorsArray = error.response.data.message
- if (_isArray(errorsArray)) {
- throw errorsArray
- }
- throw new Error(errorsArray)
- })
-
-export const verifyEmail = ({ id }: { id: string }) =>
- api
- .get(`v1/auth/verify-email/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const confirmChangeEmail = ({ id }: { id: string }) =>
- api
- .get(`v1/auth/change-email/confirm/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const verifyShare = ({ path, id }: { path: string; id: string }) =>
- api
- .get(`/project/${path}/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getProjects = (take = 0, skip = 0, search = '', period = '7d', sort = 'alpha_asc') =>
- api
- .get(`/project?take=${take}&skip=${skip}&search=${search}&period=${period}&sort=${sort}`)
- .then(
- (
- response,
- ): {
- results: Project[]
- total: number
- page_total: number
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getProjectsAvailableForOrganisation = (take = 0, skip = 0, search?: string) =>
- api
- .get(`/project/available-for-organisation?take=${take}&skip=${skip}&search=${search}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getOrganisations = (take = 0, skip = 0, search?: string) =>
- api
- .get(`/organisation?take=${take}&skip=${skip}&search=${search}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getOrganisation = (id: string) =>
- api
- .get(`/organisation/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteOrganisation = (id: string) =>
- api
- .delete(`/organisation/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const assignProjectToOrganisation = (projectId: string, organisationId?: string) =>
- api
- .patch(`/project/${projectId}/organisation`, { organisationId })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const createOrganisation = (name: string) =>
- api
- .post('/organisation', { name })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateOrganisation = (organisationId: string, data: { name: string }) =>
- api
- .patch(`/organisation/${organisationId}`, data)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const addProjectToOrganisation = (organisationId: string, projectId: string) =>
- api
- .post(`/project/organisation/${organisationId}`, { projectId })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const removeProjectFromOrganisation = (organisationId: string, projectId: string) =>
- api
- .delete(`/project/organisation/${organisationId}/${projectId}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const changeOrganisationRole = (memberId: string, role: Role) =>
- api
- .patch(`/organisation/member/${memberId}`, { role })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const inviteOrganisationMember = (organisationId: string, data: { email: string; role: Role }) =>
- api
- .post(`/organisation/${organisationId}/invite`, data)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const acceptOrganisationInvitation = (tokenId: string) =>
- api
- .post(`/user/organisation/${tokenId}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const rejectOrganisationInvitation = (tokenId: string) =>
- api
- .delete(`/user/organisation/${tokenId}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const removeOrganisationMember = (memberId: string) =>
- api
- .delete(`/organisation/member/${memberId}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getProject = (pid: string, password?: string) =>
- api
- .get(`/project/${pid}`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response): Project => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const createProject = (data: { name: string; organisationId?: string }) =>
- api
- .post('/project', data)
- .then((response): Project => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateProject = (id: string, data: Partial<Project>) =>
- api
- .put(`/project/${id}`, data)
- .then((response): Project => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteProject = (id: string) =>
- api
- .delete(`/project/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const pinProject = (id: string) =>
- api
- .post(`/project/${id}/pin`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const unpinProject = (id: string) =>
- api
- .delete(`/project/${id}/pin`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const resetProject = (id: string) =>
- api
- .delete(`/project/reset/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getProjectData = (
- pid: string,
- tb = 'hour',
- period = '1d',
- filters: Filter[] = [],
- metrics: ProjectViewCustomEvent[] = [],
- from = '',
- to = '',
- timezone = '',
- password: string | undefined = '',
- mode: 'periodical' | 'cumulative' = 'periodical',
-) =>
- api
- .get(
- `log?pid=${pid}&timeBucket=${tb}&period=${period}&metrics=${JSON.stringify(metrics)}&filters=${JSON.stringify(
- filters,
- )}&from=${from}&to=${to}&timezone=${timezone}&mode=${mode}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getCustomEventsMetadata = (
- pid: string,
- event: string,
- tb = 'hour',
- period = '1d',
- from = '',
- to = '',
- timezone = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/meta?pid=${pid}&timeBucket=${tb}&period=${period}&from=${from}&to=${to}&timezone=${timezone}&event=${event}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getPropertyMetadata = (
- pid: string,
- property: string,
- tb = 'hour',
- period = '1d',
- from = '',
- to = '',
- filters: any[] = [],
- timezone = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/property?pid=${pid}&timeBucket=${tb}&period=${period}&from=${from}&to=${to}&timezone=${timezone}&property=${property}&filters=${JSON.stringify(
- filters,
- )}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getTrafficCompareData = (
- pid: string,
- tb = 'hour',
- period = '3d',
- filters: any[] = [],
- from = '',
- to = '',
- timezone = '',
- password: string | undefined = '',
- mode: 'periodical' | 'cumulative' = 'periodical',
-) =>
- api
- .get(
- `log/chart?pid=${pid}&timeBucket=${tb}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&from=${from}&to=${to}&timezone=${timezone}&mode=${mode}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getPerformanceCompareData = (
- pid: string,
- tb = 'hour',
- period = '3d',
- filters: any[] = [],
- from = '',
- to = '',
- timezone = '',
- measure = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/performance/chart?pid=${pid}&timeBucket=${tb}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&from=${from}&to=${to}&timezone=${timezone}&measure=${measure}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getPerfData = (
- pid: string,
- tb = 'hour',
- period = '3d',
- filters: any[] = [],
- from = '',
- to = '',
- timezone = '',
- measure = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/performance?pid=${pid}&timeBucket=${tb}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&from=${from}&to=${to}&timezone=${timezone}&measure=${measure}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getSessions = (
- pid: string,
- period = '3d',
- filters: any[] = [],
- from = '',
- to = '',
- take = 30,
- skip = 0,
- timezone = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/sessions?pid=${pid}&take=${take}&skip=${skip}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&from=${from}&to=${to}&timezone=${timezone}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response): { sessions: Session[]; take: number; skip: number; appliedFilters: Filter[] } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getErrors = (
- pid: string,
- timeBucket: string,
- period = '3d',
- filters: any[] = [],
- options: any = {},
- from = '',
- to = '',
- take = 30,
- skip = 0,
- timezone = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/errors?pid=${pid}&timeBucket=${timeBucket}&take=${take}&skip=${skip}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&options=${JSON.stringify(options)}&from=${from}&to=${to}&timezone=${timezone}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response): { errors: SwetrixError[] } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getSession = (pid: string, psid: string, timezone = '', password: string | undefined = '') =>
- api
- .get(`log/session?pid=${pid}&psid=${psid}&timezone=${timezone}`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response): { details: SessionDetails; [key: string]: any } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getProfiles = (
- pid: string,
- period = '3d',
- filters: any[] = [],
- from = '',
- to = '',
- take = 30,
- skip = 0,
- timezone = '',
- profileType: 'all' | 'anonymous' | 'identified' = 'all',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/profiles?pid=${pid}&take=${take}&skip=${skip}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&from=${from}&to=${to}&timezone=${timezone}&profileType=${profileType}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response): { profiles: Profile[]; take: number; skip: number; appliedFilters: Filter[] } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getProfile = (
- pid: string,
- profileId: string,
- period = '7d',
- from = '',
- to = '',
- timezone = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/profile?pid=${pid}&profileId=${encodeURIComponent(profileId)}&period=${period}&from=${from}&to=${to}&timezone=${timezone}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response): ProfileDetails & { chart: any; timeBucket: string } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getProfileSessions = (
- pid: string,
- profileId: string,
- period = '3d',
- filters: any[] = [],
- from = '',
- to = '',
- take = 30,
- skip = 0,
- timezone = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/profile/sessions?pid=${pid}&profileId=${encodeURIComponent(profileId)}&take=${take}&skip=${skip}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&from=${from}&to=${to}&timezone=${timezone}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response): { sessions: Session[]; take: number; skip: number; appliedFilters: Filter[] } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getError = (
- pid: string,
- eid: string,
- timeBucket = 'hour',
- period = '7d',
- filters: any[] = [],
- from = '',
- to = '',
- timezone = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/get-error?pid=${pid}&eid=${eid}&timeBucket=${timeBucket}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&from=${from}&to=${to}&timezone=${timezone}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response): { details: SwetrixErrorDetails; [key: string]: any } => response.data)
- .catch((error) => {
- throw error.response
- })
-
-interface ErrorOverviewStats {
- totalErrors: number
- uniqueErrors: number
- affectedSessions: number
- affectedUsers: number
- errorRate: number
-}
-
-interface MostFrequentError {
- eid: string
- name: string
- message: string
- count: number
- usersAffected: number
- lastSeen: string
-}
-
-interface ErrorOverviewChart {
- x: string[]
- occurrences: number[]
- affectedUsers: number[]
-}
-
-export interface ErrorOverviewResponse {
- stats: ErrorOverviewStats
- mostFrequentError: MostFrequentError | null
- chart: ErrorOverviewChart
- timeBucket: string
-}
-
-export const getErrorOverview = (
- pid: string,
- timeBucket = 'hour',
- period = '7d',
- filters: any[] = [],
- options: any = {},
- from = '',
- to = '',
- timezone = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/error-overview?pid=${pid}&timeBucket=${timeBucket}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&options=${JSON.stringify(options)}&from=${from}&to=${to}&timezone=${timezone}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response): ErrorOverviewResponse => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-
-export interface ErrorAffectedSession {
- psid: string
- profileId: string | null
- cc: string | null
- br: string | null
- os: string | null
- firstErrorAt: string
- lastErrorAt: string
- errorCount: number
-}
-
-export const getErrorSessions = (
- pid: string,
- eid: string,
- timeBucket = 'hour',
- period = '7d',
- from = '',
- to = '',
- take = 10,
- skip = 0,
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/error-sessions?pid=${pid}&eid=${eid}&timeBucket=${timeBucket}&period=${period}&from=${from}&to=${to}&take=${take}&skip=${skip}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response): { sessions: ErrorAffectedSession[]; total: number } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-
-export const getFunnelData = (
- pid: string,
- period = '3d',
- from = '',
- to = '',
- timezone = '',
- funnelId = '',
- password: string | undefined = '',
-) =>
- api
- .get(`log/funnel?pid=${pid}&period=${period}&from=${from}&to=${to}&timezone=${timezone}&funnelId=${funnelId}`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getFunnels = (pid: string, password: string | undefined = '') =>
- api
- .get(`project/funnels/${pid}`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response): Funnel[] => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getProjectViews = (pid: string, password: string | undefined = '') =>
- api
- .get(`project/${pid}/views`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const createProjectView = (
- pid: string,
- name: string,
- type: 'traffic' | 'performance',
- filters: Filter[],
- customEvents: Partial<ProjectViewCustomEvent>[],
-) =>
- api
- .post(`project/${pid}/views`, { name, type, filters, customEvents })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateProjectView = (
- pid: string,
- viewId: string,
- name: string,
- filters: Filter[],
- customEvents: Partial<ProjectViewCustomEvent>[],
-) =>
- api
- .patch(`project/${pid}/views/${viewId}`, { name, filters, customEvents })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteProjectView = (pid: string, viewId: string) =>
- api
- .delete(`project/${pid}/views/${viewId}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getCaptchaData = (pid: string, tb = 'hour', period = '3d', filters: any[] = [], from = '', to = '') =>
- api
- .get(
- `log/captcha?pid=${pid}&timeBucket=${tb}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&from=${from}&to=${to}`,
- )
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getOverallStats = (
- pids: string[],
- tb: string,
- period: string,
- from = '',
- to = '',
- timezone = 'Etc/GMT',
- filters: any = '',
- password?: string,
- includeChart = false,
-) =>
- api
- .get(
- `log/birdseye?pids=[${_map(pids, (pid) => `"${pid}"`).join(
- ',',
- )}]&timeBucket=${tb}&period=${period}&from=${from}&to=${to}&timezone=${timezone}&filters=${JSON.stringify(filters)}&includeChart=${includeChart}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response): Overall => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getPerformanceOverallStats = (
- pids: string[],
- period: string,
- from = '',
- to = '',
- timezone = 'Etc/GMT',
- filters: any = '',
- measure: any = '',
- password?: string,
-) =>
- api
- .get(
- `log/performance/birdseye?pids=[${_map(pids, (pid) => `"${pid}"`).join(
- ',',
- )}]&period=${period}&from=${from}&to=${to}&timezone=${timezone}&filters=${JSON.stringify(filters)}&measure=${measure}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response): Overall => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getLiveVisitors = (pids: string[], password?: string): Promise<LiveStats> =>
- api
- .get(`log/hb?pids=[${_map(pids, (pid) => `"${pid}"`).join(',')}]`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getGeneralStats = () =>
- api
- .get('log/generalStats')
- .then((response): Stats => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const shareProject = (
- pid: string,
- data: {
- email: string
- role: string
- },
-) =>
- api
- .post(`/project/${pid}/share`, data)
- .then((response): Project => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteShareProjectUsers = (pid: string, userId: string) =>
- api
- .delete(`/project/${pid}/${userId}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const rejectProjectShare = (actionId: string) =>
- api
- .delete(`/user/share/${actionId}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const acceptProjectShare = (actionId: string) =>
- api
- .get(`/user/share/${actionId}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const changeShareRole = (
- id: string,
- data: {
- role: string
- },
-) =>
- api
- .put(`project/share/${id}`, data)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const generate2FA = () =>
- api
- .post('2fa/generate')
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const enable2FA = (twoFactorAuthenticationCode: string) =>
- api
- .post('2fa/enable', { twoFactorAuthenticationCode })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const disable2FA = (twoFactorAuthenticationCode: string) =>
- api
- .post('2fa/disable', { twoFactorAuthenticationCode })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const submit2FA = (twoFactorAuthenticationCode: string) =>
- api
- .post('2fa/authenticate', { twoFactorAuthenticationCode })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const generateApiKey = () =>
- api
- .post('user/api-key')
- .then(
- (
- response,
- ): {
- apiKey: string
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteApiKey = () =>
- api
- .delete('user/api-key')
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export interface GetLiveVisitorsInfo {
- psid: string
- dv: string
- br: string
- os: string
- cc: string
-}
-
-export const getLiveVisitorsInfo = (pid: string, password?: string) =>
- api
- .get(`log/live-visitors?pid=${pid}`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response): GetLiveVisitorsInfo[] => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const removeTgIntegration = (tgID: string) =>
- api
- .delete(`user/tg/${tgID}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getProjectAlerts = (projectId: string, take: number = DEFAULT_ALERTS_TAKE, skip = 0) =>
- api
- .get(`/alert/project/${projectId}?take=${take}&skip=${skip}`)
- .then(
- (
- response,
- ): {
- results: Alerts[]
- total: number
- page_total: number
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getAlert = (alertId: string) =>
- api
- .get(`/alert/${alertId}`)
- .then((response): Alerts => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export type CreateAlert = Omit<Alerts, 'id' | 'lastTrigger' | 'lastTriggered' | 'created'>
-
-export const createAlert = (data: CreateAlert) =>
- api
- .post('alert', data)
- .then((response): Alerts => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateAlert = (id: string, data: Partial<Alerts>) =>
- api
- .put(`alert/${id}`, data)
- .then((response): Alerts => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteAlert = (id: string) =>
- api
- .delete(`alert/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-// Goals API
-export interface Goal {
- id: string
- name: string
- type: 'pageview' | 'custom_event'
- matchType: 'exact' | 'contains'
- value: string | null
- metadataFilters: { key: string; value: string }[] | null
- active: boolean
- pid: string
- created: string
-}
-
-export interface GoalStats {
- conversions: number
- uniqueSessions: number
- conversionRate: number
- previousConversions: number
- trend: number
-}
-
-export interface GoalChartData {
- x: string[]
- conversions: number[]
- uniqueSessions: number[]
-}
-
-export const DEFAULT_GOALS_TAKE = 20
-
-export const getProjectGoals = (projectId: string, take: number = DEFAULT_GOALS_TAKE, skip = 0, search?: string) => {
- const params = new URLSearchParams({
- take: String(take),
- skip: String(skip),
- })
-
- if (search?.trim()) {
- params.append('search', search.trim())
- }
-
- return api
- .get(`/goal/project/${projectId}?${params.toString()}`)
- .then(
- (
- response,
- ): {
- results: Goal[]
- total: number
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-}
-
-export const getGoal = (goalId: string) =>
- api
- .get(`/goal/${goalId}`)
- .then((response): Goal => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export type CreateGoal = {
- pid: string
- name: string
- type: 'pageview' | 'custom_event'
- matchType: 'exact' | 'contains'
- value?: string
- metadataFilters?: { key: string; value: string }[]
-}
-
-export const createGoal = (data: CreateGoal) =>
- api
- .post('goal', data)
- .then((response): Goal => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateGoal = (id: string, data: Partial<Goal>) =>
- api
- .put(`goal/${id}`, data)
- .then((response): Goal => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteGoal = (id: string) =>
- api
- .delete(`goal/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getGoalStats = (goalId: string, period: string, from: string = '', to: string = '', timezone?: string) =>
- api
- .get(`/goal/${goalId}/stats`, {
- params: { period, from, to, timezone },
- })
- .then((response): GoalStats => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getGoalChart = (
- goalId: string,
- period: string,
- from: string = '',
- to: string = '',
- timeBucket: string = 'day',
- timezone?: string,
-) =>
- api
- .get(`/goal/${goalId}/chart`, {
- params: { period, from, to, timeBucket, timezone },
- })
- .then((response): { chart: GoalChartData } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-// Feature Flags API
-export interface TargetingRule {
- column: string
- filter: string
- isExclusive: boolean
-}
-
-export interface ProjectFeatureFlag {
- id: string
- key: string
- description: string | null
- flagType: 'boolean' | 'rollout'
- rolloutPercentage: number
- targetingRules: TargetingRule[] | null
- enabled: boolean
- pid: string
- created: string
-}
-
-export interface FeatureFlagStats {
- evaluations: number
- profileCount: number
- trueCount: number
- falseCount: number
- truePercentage: number
-}
-
-export type CreateFeatureFlag = {
- pid: string
- key: string
- description?: string
- flagType?: 'boolean' | 'rollout'
- rolloutPercentage?: number
- targetingRules?: TargetingRule[]
- enabled?: boolean
-}
-
-export const DEFAULT_FEATURE_FLAGS_TAKE = 20
-
-export const getProjectFeatureFlags = (
- projectId: string,
- take: number = DEFAULT_FEATURE_FLAGS_TAKE,
- skip = 0,
- search?: string,
-) => {
- const params = new URLSearchParams({
- take: String(take),
- skip: String(skip),
- })
-
- if (search?.trim()) {
- params.append('search', search.trim())
- }
-
- return api
- .get(`/feature-flag/project/${projectId}?${params.toString()}`)
- .then(
- (
- response,
- ): {
- results: ProjectFeatureFlag[]
- total: number
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-}
-
-export const getFeatureFlag = (flagId: string) =>
- api
- .get(`/feature-flag/${flagId}`)
- .then((response): ProjectFeatureFlag => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const createFeatureFlag = (data: CreateFeatureFlag) =>
- api
- .post('feature-flag', data)
- .then((response): ProjectFeatureFlag => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateFeatureFlag = (id: string, data: Partial<ProjectFeatureFlag>) =>
- api
- .put(`feature-flag/${id}`, data)
- .then((response): ProjectFeatureFlag => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteFeatureFlag = (id: string) =>
- api
- .delete(`feature-flag/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getFeatureFlagStats = (
- flagId: string,
- period: string,
- from: string = '',
- to: string = '',
- timezone?: string,
-) =>
- api
- .get(`/feature-flag/${flagId}/stats`, {
- params: { period, from, to, timezone },
- })
- .then((response): FeatureFlagStats => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export interface FeatureFlagProfile {
- profileId: string
- isIdentified: boolean
- lastResult: boolean
- evaluationCount: number
- lastEvaluated: string
-}
-
-export const DEFAULT_FEATURE_FLAG_PROFILES_TAKE = 15
-
-type FeatureFlagResultFilter = 'all' | 'true' | 'false'
-
-export const getFeatureFlagProfiles = (
- flagId: string,
- period: string,
- from: string = '',
- to: string = '',
- timezone?: string,
- take: number = DEFAULT_FEATURE_FLAG_PROFILES_TAKE,
- skip: number = 0,
- resultFilter: FeatureFlagResultFilter = 'all',
-) =>
- api
- .get(`/feature-flag/${flagId}/profiles`, {
- params: {
- period,
- from,
- to,
- timezone,
- take,
- skip,
- result: resultFilter === 'all' ? undefined : resultFilter,
- },
- })
- .then((response): { profiles: FeatureFlagProfile[]; total: number } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-// Experiments (A/B Testing) API
-
-export type ExperimentStatus = 'draft' | 'running' | 'paused' | 'completed'
-
-export type ExposureTrigger = 'feature_flag' | 'custom_event'
-
-export type MultipleVariantHandling = 'exclude' | 'first_exposure'
-
-export type FeatureFlagMode = 'create' | 'link'
-
-export interface ExperimentVariant {
- id?: string
- name: string
- key: string
- description?: string | null
- rolloutPercentage: number
- isControl: boolean
-}
-
-export interface Experiment {
- id: string
- name: string
- description: string | null
- hypothesis: string | null
- status: ExperimentStatus
- // Exposure criteria
- exposureTrigger: ExposureTrigger
- customEventName: string | null
- multipleVariantHandling: MultipleVariantHandling
- filterInternalUsers: boolean
- // Feature flag configuration
- featureFlagMode: FeatureFlagMode
- featureFlagKey: string | null
- startedAt: string | null
- endedAt: string | null
- pid: string
- goalId: string | null
- featureFlagId: string | null
- variants: ExperimentVariant[]
- created: string
-}
-
-export interface ExperimentVariantResult {
- key: string
- name: string
- isControl: boolean
- exposures: number
- conversions: number
- conversionRate: number
- probabilityOfBeingBest: number
- improvement: number
-}
-
-export interface ExperimentChartData {
- x: string[]
- winProbability: Record<string, number[]>
-}
-
-export interface ExperimentResults {
- experimentId: string
- status: ExperimentStatus
- variants: ExperimentVariantResult[]
- totalExposures: number
- totalConversions: number
- hasWinner: boolean
- winnerKey: string | null
- confidenceLevel: number
- chart?: ExperimentChartData
- timeBucket?: string[]
-}
-
-interface CreateExperiment {
- pid: string
- name: string
- description?: string
- hypothesis?: string
- // Exposure criteria
- exposureTrigger?: ExposureTrigger
- customEventName?: string
- multipleVariantHandling?: MultipleVariantHandling
- filterInternalUsers?: boolean
- // Feature flag configuration
- featureFlagMode?: FeatureFlagMode
- featureFlagKey?: string
- existingFeatureFlagId?: string
- goalId?: string
- variants: ExperimentVariant[]
-}
-
-export const DEFAULT_EXPERIMENTS_TAKE = 20
-
-export const getProjectExperiments = (
- projectId: string,
- take: number = DEFAULT_EXPERIMENTS_TAKE,
- skip = 0,
- search?: string,
-) => {
- const params = new URLSearchParams({
- take: String(take),
- skip: String(skip),
- })
-
- if (search) {
- params.set('search', search)
- }
-
- return api
- .get(`/experiment/project/${projectId}?${params.toString()}`)
- .then(
- (
- response,
- ): {
- results: Experiment[]
- total: number
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-}
-
-export const getExperiment = (experimentId: string) =>
- api
- .get(`/experiment/${experimentId}`)
- .then((response): Experiment => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const createExperiment = (data: CreateExperiment) =>
- api
- .post('experiment', data)
- .then((response): Experiment => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateExperiment = (id: string, data: Partial<CreateExperiment>) =>
- api
- .put(`experiment/${id}`, data)
- .then((response): Experiment => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteExperiment = (id: string) =>
- api
- .delete(`experiment/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const startExperiment = (id: string) =>
- api
- .post(`experiment/${id}/start`)
- .then((response): Experiment => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const pauseExperiment = (id: string) =>
- api
- .post(`experiment/${id}/pause`)
- .then((response): Experiment => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const completeExperiment = (id: string) =>
- api
- .post(`experiment/${id}/complete`)
- .then((response): Experiment => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getExperimentResults = (
- experimentId: string,
- period: string,
- timeBucket: string,
- from: string = '',
- to: string = '',
- timezone?: string,
-) =>
- api
- .get(`/experiment/${experimentId}/results`, {
- params: { period, timeBucket, from, to, timezone },
- })
- .then((response): ExperimentResults => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const reGenerateCaptchaSecretKey = (pid: string) =>
- api
- .post(`project/secret-gen/${pid}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const addSubscriber = (
- id: string,
- data: {
- email: string
- reportFrequency: string
- },
-) =>
- api
- .post(`project/${id}/subscribers`, data)
- .then((response): Subscriber => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const addFunnel = (pid: string, name: string, steps: string[]) =>
- api
- .post('project/funnel', { pid, name, steps })
- .then((response): any => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateFunnel = (id: string, pid: string, name: string, steps: string[]) =>
- api
- .patch('project/funnel', { id, name, steps, pid })
- .then((response): any => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteFunnel = (id: string, pid: string) =>
- api
- .delete(`project/funnel/${id}/${pid}`)
- .then((response): any => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getAnnotations = (pid: string, password: string | undefined = '') =>
- api
- .get(`project/annotations/${pid}`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response): any[] => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const createAnnotation = (pid: string, date: string, text: string) =>
- api
- .post('project/annotation', { pid, date, text })
- .then((response): any => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateAnnotation = (id: string, pid: string, date: string, text: string) =>
- api
- .patch('project/annotation', { id, pid, date, text })
- .then((response): any => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteAnnotation = (id: string, pid: string) =>
- api
- .delete(`project/annotation/${id}/${pid}`)
- .then((response): any => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getSubscribers = (id: string, offset: number, limit: number) =>
- api
- .get(`project/${id}/subscribers?offset=${offset}&limit=${limit}`)
- .then(
- (
- response,
- ): {
- subscribers: Subscriber[]
- count: number
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateSubscriber = (
- id: string,
- subscriberId: string,
- data: {
- reportFrequency: string
- },
-) =>
- api
- .patch(`project/${id}/subscribers/${subscriberId}`, data)
- .then((response): Subscriber => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const removeSubscriber = (id: string, subscriberId: string) =>
- api
- .delete(`project/${id}/subscribers/${subscriberId}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const confirmSubscriberInvite = (id: string, token: string) =>
- api
- .get(`project/${id}/subscribers/invite?token=${token}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getProjectDataCustomEvents = (
- pid: string,
- tb = 'hour',
- period = '3d',
- filters: any[] = [],
- from = '',
- to = '',
- timezone = '',
- customEvents: string[] = [],
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/custom-events?pid=${pid}&timeBucket=${tb}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&from=${from}&to=${to}&timezone=${timezone}&customEvents=${JSON.stringify(customEvents)}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const transferProject = (uuid: string, email: string) =>
- api
- .post('project/transfer', {
- projectId: uuid,
- email,
- })
- .then((response): unknown => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const rejectTransferProject = (uuid: string) =>
- api
- .delete(`project/transfer?token=${uuid}`)
- .then((response): unknown => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const confirmTransferProject = (uuid: string) =>
- api
- .get(`project/transfer?token=${uuid}`)
- .then((response): unknown => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const generateSSOAuthURL = async (provider: SSOProvider, redirectUrl?: string) => {
- const payload = {
- provider,
- redirectUrl,
- }
-
- let authInitiateRequest
-
- if (provider === 'openid-connect') {
- authInitiateRequest = api.post('v1/auth/oidc/initiate', payload)
- } else {
- authInitiateRequest = api.post('v1/auth/sso/generate', payload)
- }
-
- return authInitiateRequest
- .then(
- (
- response,
- ): {
- uuid: string
- auth_url: string
- expires_in: number
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-}
-
-export const getJWTBySSOHash = async (hash: string, provider: SSOProvider) => {
- let axiosPost
-
- if (provider === 'openid-connect') {
- axiosPost = api.post('v1/auth/oidc/hash', { hash })
- } else {
- axiosPost = api.post('v1/auth/sso/hash', { hash, provider })
- }
-
- return axiosPost
- .then(
- (
- response,
- ): {
- accessToken: string
- refreshToken: string
- user: User
- totalMonthlyEvents: number
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-}
-
-export const processSSOTokenCommunityEdition = (code: string, hash: string, redirectUrl: string) =>
- api
- .post('v1/auth/oidc/process-token', { code, hash, redirectUrl })
- .then((response): unknown => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const linkBySSOHash = (hash: string, provider: SSOProvider) =>
- api
- .post('v1/auth/sso/link_by_hash', { hash, provider })
- .then((response): unknown => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const unlinkSSO = (provider: SSOProvider) =>
- api
- .delete('v1/auth/sso/unlink', { data: { provider } })
- .then((response): unknown => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const processSSOToken = (token: string, hash: string) =>
- api
- .post('v1/auth/sso/process-token', { token, hash })
- .then((response): unknown => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deletePartially = (
- id: string,
- data: {
- from: string
- to: string
- },
-) =>
- api
- .delete(`project/partially/${id}?from=${data.from}&to=${data.to}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getUserFlow = (
- pid: string,
- tb = 'hour',
- period = '3d',
- filters: any[] = [],
- from = '',
- to = '',
- timezone = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/user-flow?pid=${pid}&timeBucket=${tb}&period=${period}&filters=${JSON.stringify(
- filters,
- )}&from=${from}&to=${to}&timezone=${timezone}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const checkPassword = (pid: string, password: string) =>
- api
- .get(`project/password/${pid}`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response): boolean => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getPaymentMetainfo = (config?: AxiosRequestConfig) =>
- api
- .get('user/metainfo', config)
- .then((response): Metainfo => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getUsageInfo = () =>
- api
- .get('user/usageinfo')
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getFilters = (pid: string, type: string, password = '') =>
- api
- .get(`log/filters?pid=${pid}&type=${type}`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response): string[] => response.data)
- .catch((error) => {
- throw error
- })
-
-export const getErrorsFilters = (pid: string, type: string, password = '') =>
- api
- .get(`log/errors-filters?pid=${pid}&type=${type}`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response): string[] => response.data)
- .catch((error) => {
- throw error
- })
-
-export const getVersionFilters = (pid: string, type: 'traffic' | 'errors', column: 'br' | 'os', password = '') =>
- api
- .get(`log/filters/versions?pid=${pid}&type=${type}&column=${column}`, {
- headers: {
- 'x-password': password,
- },
- })
- .then((response): Array<{ name: string; version: string }> => response.data)
- .catch((error) => {
- throw error
- })
-
-export const resetFilters = (pid: string, type: string, filters: string[]) =>
- api
- .delete(`project/reset-filters/${pid}?type=${type}&filters=${JSON.stringify(filters)}`)
- .then((response) => response.data)
- .catch((error) => {
- throw error
- })
-
-export const receiveLoginNotification = (receiveLoginNotifications: boolean) =>
- api
- .post('user/recieve-login-notifications', { receiveLoginNotifications })
- .then((response) => response.data)
- .catch((error) => {
- throw error
- })
-
-export const previewSubscriptionUpdate = (planId: number) =>
- api
- .post('user/preview-plan', { planId })
- .then((response) => response.data)
- .catch((error) => {
- throw error
- })
-
-export const changeSubscriptionPlan = (planId: number) =>
- api
- .post('user/change-plan', { planId })
- .then((response) => response.data)
- .catch((error) => {
- throw error
- })
-
-export const getBlogPosts = () =>
- api
- .get('v1/blog')
- .then((response) => response.data)
- .catch((error) => {
- throw error
- })
-
-export const getBlogPost = (slug: string) =>
- api
- .get(`v1/blog/${slug}`)
- .then((response) => response.data)
- .catch((error) => {
- throw error
- })
-
-export const getSitemap = () =>
- api
- .get('v1/blog/sitemap')
- .then((response) => response.data)
- .catch((error) => {
- throw error
- })
-
-export const getBlogPostWithCategory = (category: string, slug: string) =>
- api
- .get(`v1/blog/${category}/${slug}`)
- .then((response) => response.data)
- .catch((error) => {
- throw error
- })
-
-export const unsubscribeFromEmailReports = (token: string) =>
- api
- .get(`user/unsubscribe/${token}`)
- .then((response) => response.data)
- .catch((error) => {
- throw error
- })
-
-export const unsubscribeFromEmailReports3rdParty = (token: string) =>
- api
- .get(`project/unsubscribe/${token}`)
- .then((response) => response.data)
- .catch((error) => {
- throw error
- })
-
-export const updateErrorStatus = (pid: string, status: 'resolved' | 'active', eid?: string, eids?: string[]) =>
- api
- .patch('log/error-status', { pid, eid, eids, status })
- .then((response): any => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateOnboardingStep = (step: string) =>
- api
- .post('/user/onboarding/step', { step })
- .then((response): User => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const completeOnboarding = () =>
- api
- .post('/user/onboarding/complete')
- .then((response): User => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-// Google Search Console integration
-export const generateGSCAuthURL = (pid: string) =>
- api
- .post(`v1/project/gsc/${pid}/connect`)
- .then((response): { url: string } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getGSCStatus = (pid: string) =>
- api
- .get(`v1/project/gsc/${pid}/status`)
- .then((response): { connected: boolean; email?: string | null } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const processGSCToken = (code: string, state: string) =>
- api
- .post(`v1/project/gsc/process-token`, { code, state })
- .then((response): { pid: string } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getGSCProperties = (pid: string) =>
- api
- .get(`v1/project/gsc/${pid}/properties`)
- .then((response): { siteUrl: string; permissionLevel?: string }[] => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const setGSCProperty = (pid: string, propertyUri: string) =>
- api
- .post(`v1/project/gsc/${pid}/property`, { propertyUri })
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const disconnectGSC = (pid: string) =>
- api
- .delete(`v1/project/gsc/${pid}/disconnect`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getGSCKeywords = (
- pid: string,
- period = '3d',
- from = '',
- to = '',
- timezone = '',
- password: string | undefined = '',
-) =>
- api
- .get(`log/keywords?pid=${pid}&period=${period}&from=${from}&to=${to}&timezone=${timezone}`, {
- headers: { 'x-password': password },
- })
- .then(
- (
- response,
- ): {
- keywords: { name: string; count: number; impressions: number; position: number; ctr: number }[]
- notConnected?: boolean
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-// AI Chat API with SSE streaming
interface AIChatMessage {
role: 'user' | 'assistant'
content: string
@@ -2215,22 +19,19 @@ export const askAI = async (
callbacks: AIStreamCallbacks,
signal?: AbortSignal,
) => {
- const token = getAccessToken()
-
try {
- const response = await fetch(`${API_URL}ai/${pid}/chat`, {
+ const response = await fetch('/api/ai', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
- Authorization: token ? `Bearer ${token}` : '',
},
- body: JSON.stringify({ messages, timezone }),
+ body: JSON.stringify({ pid, messages, timezone }),
signal,
})
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
- throw new Error(errorData.message || `HTTP error! status: ${response.status}`)
+ throw new Error(errorData.message || errorData.error || `HTTP error! status: ${response.status}`)
}
const reader = response.body?.getReader()
@@ -2288,174 +89,3 @@ export const askAI = async (
callbacks.onError(error as Error)
}
}
-
-// AI Chat History API
-export interface AIChatSummary {
- id: string
- name: string | null
- created: string
- updated: string
-}
-
-interface AIChat extends AIChatSummary {
- messages: AIChatMessage[]
- isOwner?: boolean
- branched?: boolean
-}
-
-export const getRecentAIChats = async (pid: string, limit: number = 5): Promise<AIChatSummary[]> => {
- return api
- .get(`ai/${pid}/chats`, {
- params: { limit },
- })
- .then((response): AIChatSummary[] => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-}
-
-export const getAllAIChats = async (
- pid: string,
- skip: number = 0,
- take: number = 20,
-): Promise<{ chats: AIChatSummary[]; total: number }> => {
- return api
- .get(`ai/${pid}/chats/all`, {
- params: { skip, take },
- })
- .then((response): { chats: AIChatSummary[]; total: number } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-}
-
-export const getAIChat = async (pid: string, chatId: string): Promise<AIChat> => {
- return api
- .get(`ai/${pid}/chats/${chatId}`)
- .then((response): AIChat => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-}
-
-export const createAIChat = async (pid: string, messages: AIChatMessage[], name?: string): Promise<AIChat> => {
- return api
- .post(
- `ai/${pid}/chats`,
- { messages, name },
- { headers: { Authorization: getAccessToken() ? `Bearer ${getAccessToken()}` : '' } },
- )
- .then((response): AIChat => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-}
-
-export const updateAIChat = async (
- pid: string,
- chatId: string,
- data: { messages?: AIChatMessage[]; name?: string },
-): Promise<AIChat> => {
- return api
- .post(`ai/${pid}/chats/${chatId}`, data)
- .then((response): AIChat => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-}
-
-export const deleteAIChat = async (pid: string, chatId: string): Promise<{ success: boolean }> => {
- return api
- .delete(`ai/${pid}/chats/${chatId}`)
- .then((response): { success: boolean } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-}
-
-// Revenue API
-interface RevenueStatus {
- connected: boolean
- provider?: string
- currency?: string
- lastSyncAt?: string
-}
-
-interface RevenueStats {
- totalRevenue: number
- salesCount: number
- refundsCount: number
- refundsAmount: number
- averageOrderValue: number
- currency: string
- mrr: number
- revenueChange: number
-}
-
-interface RevenueChart {
- x: string[]
- revenue: number[]
- salesCount: number[]
- refundsAmount: number[]
-}
-
-export const getRevenueStatus = async (pid: string): Promise<RevenueStatus> => {
- return api
- .get(`project/${pid}/revenue/status`)
- .then((response): RevenueStatus => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-}
-
-export type RevenueProvider = 'stripe' | 'paddle'
-
-export const connectRevenue = async (
- pid: string,
- provider: RevenueProvider,
- apiKey: string,
- currency: string = 'USD',
-): Promise<{ success: boolean }> => {
- return api
- .post(`project/${pid}/revenue/connect`, { provider, apiKey, currency })
- .then((response): { success: boolean } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-}
-
-export const disconnectRevenue = async (pid: string): Promise<void> => {
- return api
- .delete(`project/${pid}/revenue/disconnect`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-}
-
-export const updateRevenueCurrency = async (pid: string, currency: string): Promise<{ success: boolean }> => {
- return api
- .post(`project/${pid}/revenue/currency`, { currency })
- .then((response): { success: boolean } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-}
-
-export const getRevenueData = async (
- pid: string,
- period: string,
- from?: string,
- to?: string,
- timezone?: string,
- timeBucket?: string,
-): Promise<{ stats: RevenueStats; chart: RevenueChart }> => {
- return api
- .get('log/revenue', {
- params: { pid, period, from, to, timezone, timeBucket },
- })
- .then((response): { stats: RevenueStats; chart: RevenueChart } => response.data)
- .catch((error) => {
- throw _isEmpty(error.response?.data?.message) ? error.response?.data : error.response?.data?.message
- })
-}
diff --git a/web/app/components/pricing/BillingPricing.tsx b/web/app/components/pricing/BillingPricing.tsx
index ae6d2a7b8..f47f59ab2 100644
--- a/web/app/components/pricing/BillingPricing.tsx
+++ b/web/app/components/pricing/BillingPricing.tsx
@@ -7,9 +7,9 @@ import _map from 'lodash/map'
import { CircleHelpIcon } from 'lucide-react'
import React, { memo, useEffect, useMemo, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { changeSubscriptionPlan, getPaymentMetainfo, previewSubscriptionUpdate } from '~/api'
import {
BillingFrequency,
CURRENCIES,
@@ -19,9 +19,10 @@ import {
PURCHASABLE_LEGACY_PLANS,
paddleLanguageMapping,
} from '~/lib/constants'
-import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
+import { Metainfo, DEFAULT_METAINFO } from '~/lib/models/Metainfo'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
+import type { BillingActionData } from '~/routes/billing'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
@@ -32,11 +33,12 @@ import routes from '~/utils/routes'
interface BillingPricingProps {
lastEvent?: { event: string } | null
+ metainfo?: Metainfo
}
const formatEventsLong = (value: number): string => value.toLocaleString('en-US')
-const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
+const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPricingProps) => {
const {
t,
i18n: { language },
@@ -44,12 +46,12 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
const { isAuthenticated, user, loadUser } = useAuth()
const { theme } = useTheme()
- const [metainfo, setMetainfo] = useState<Metainfo>(DEFAULT_METAINFO)
+ const previewFetcher = useFetcher<BillingActionData>()
+ const changePlanFetcher = useFetcher<BillingActionData>()
+
const [planCodeLoading, setPlanCodeLoading] = useState<string | null>(null)
const [isNewPlanConfirmationModalOpened, setIsNewPlanConfirmationModalOpened] = useState(false)
- const [subUpdatePreview, setSubUpdatePreview] = useState<any>(null)
const [newPlanId, setNewPlanId] = useState<number | null>(null)
- const [isSubUpdating, setIsSubUpdating] = useState(false)
const [downgradeTo, setDowngradeTo] = useState<{
planCode: string
name: string
@@ -60,15 +62,54 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
const [billingFrequency, setBillingFrequency] = useState(user?.billingFrequency || BillingFrequency.monthly)
const [enableLegacyPlans, setEnableLegacyPlans] = useState(false)
+ const subUpdatePreview = useMemo(() => {
+ if (previewFetcher.state === 'loading' || previewFetcher.state === 'submitting') {
+ return null
+ }
+ if (previewFetcher.data?.success && previewFetcher.data.data) {
+ return previewFetcher.data.data
+ }
+ if (previewFetcher.data?.error) {
+ return false
+ }
+ return null
+ }, [previewFetcher.data, previewFetcher.state])
+
+ const isSubUpdating = changePlanFetcher.state === 'submitting' || changePlanFetcher.state === 'loading'
+
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search)
const legacyParam = urlParams.get('__ENABLE_LEGACY_PLANS')
if (legacyParam === 'true') {
- // eslint-disable-next-line react-hooks/set-state-in-effect -- Reading URL param once on mount
setEnableLegacyPlans(true)
}
}, [])
+ // Handle change plan fetcher response
+ useEffect(() => {
+ if (changePlanFetcher.data?.success) {
+ loadUser()
+ toast.success(t('apiNotifications.subscriptionUpdated'))
+ closeUpdateModal(true)
+ } else if (changePlanFetcher.data?.error) {
+ console.error('[ERROR] An error occured while updating subscription:', changePlanFetcher.data.error)
+ toast.error('An error occured while updating subscription')
+ closeUpdateModal(true)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [changePlanFetcher.data])
+
+ // Handle preview fetcher error
+ useEffect(() => {
+ if (previewFetcher.data?.error) {
+ console.error(
+ '[ERROR] An error occured while loading subscription update pricing preview:',
+ previewFetcher.data.error,
+ )
+ toast.error('An error occured while loading subscription update pricing preview')
+ }
+ }, [previewFetcher.data?.error])
+
const PLAN_CODES_ARRAY = useMemo(() => {
let basePlans = STANDARD_PLANS
@@ -80,7 +121,6 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
const userPlan = user?.planCode
- // Hide non-purchasable pseudo-plans from the list
if (userPlan === 'trial' || userPlan === 'none') {
return basePlans
}
@@ -91,14 +131,6 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
const currencyCode = user?.tierCurrency || metainfo.code
const currency = CURRENCIES[currencyCode]
- useEffect(() => {
- const abortController = new AbortController()
- getPaymentMetainfo({ signal: abortController.signal })
- .then(setMetainfo)
- .catch(() => {})
- return () => abortController.abort()
- }, [])
-
useEffect(() => {
if (!lastEvent) return
@@ -119,16 +151,12 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
lastEventHandler(lastEvent)
}, [lastEvent, t, loadUser])
- const loadSubUpdatePreview = async (planId: number) => {
+ const loadSubUpdatePreview = (planId: number) => {
setIsNewPlanConfirmationModalOpened(true)
- try {
- const preview = await previewSubscriptionUpdate(planId)
- setSubUpdatePreview(preview)
- } catch (reason) {
- console.error('[ERROR] An error occured while loading subscription update pricing preview:', reason)
- toast.error('An error occured while loading subscription update pricing preview')
- setSubUpdatePreview(false)
- }
+ previewFetcher.submit(
+ { intent: 'preview-subscription-update', planId: String(planId) },
+ { method: 'POST', action: '/billing' },
+ )
}
const onPlanChange = async (tier: any) => {
@@ -144,7 +172,7 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
if (user.subID && !user.cancellationEffectiveDate && user.planCode !== 'none') {
const planId = Number(billingFrequency === BillingFrequency.monthly ? tier.pid : tier.ypid)
setNewPlanId(planId)
- await loadSubUpdatePreview(planId)
+ loadSubUpdatePreview(planId)
return
}
@@ -170,23 +198,14 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
const closeUpdateModal = (force?: boolean) => {
if (isSubUpdating && !force) return
setIsNewPlanConfirmationModalOpened(false)
- setSubUpdatePreview(null)
setNewPlanId(null)
- setIsSubUpdating(false)
}
- const updateSubscription = async () => {
- setIsSubUpdating(true)
- try {
- await changeSubscriptionPlan(newPlanId as number)
- await loadUser()
- toast.success(t('apiNotifications.subscriptionUpdated'))
- closeUpdateModal(true)
- } catch (reason) {
- console.error('[ERROR] An error occured while updating subscription:', reason)
- toast.error('An error occured while updating subscription')
- closeUpdateModal(true)
- }
+ const updateSubscription = () => {
+ changePlanFetcher.submit(
+ { intent: 'change-subscription-plan', planId: String(newPlanId) },
+ { method: 'POST', action: '/billing' },
+ )
}
const downgradeHandler = (tier: any) => {
@@ -415,7 +434,7 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
/>
</p>
) : null}
- {subUpdatePreview ? (
+ {subUpdatePreview && typeof subUpdatePreview === 'object' ? (
<div>
<h2 className='text-base font-bold'>{t('billing.dueNow')}</h2>
<p className='text-sm'>{t('billing.dueNowDescription')}</p>
@@ -440,27 +459,35 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
<tbody className='divide-y divide-gray-200 bg-white dark:divide-gray-600 dark:bg-slate-800'>
<tr>
<td className='px-3 py-4 text-sm whitespace-nowrap text-gray-900 sm:pl-6 dark:text-gray-50'>
- {`${subUpdatePreview.immediatePayment.symbol}${subUpdatePreview.immediatePayment.amount}`}
+ {`${(subUpdatePreview as any).immediatePayment.symbol}${(subUpdatePreview as any).immediatePayment.amount}`}
</td>
<td className='px-3 py-4 text-sm whitespace-nowrap text-gray-900 dark:text-gray-50'>
{language === 'en'
- ? dayjs(subUpdatePreview.immediatePayment.date).locale(language).format('MMMM D, YYYY')
- : dayjs(subUpdatePreview.immediatePayment.date).locale(language).format('D MMMM, YYYY')}
+ ? dayjs((subUpdatePreview as any).immediatePayment.date)
+ .locale(language)
+ .format('MMMM D, YYYY')
+ : dayjs((subUpdatePreview as any).immediatePayment.date)
+ .locale(language)
+ .format('D MMMM, YYYY')}
</td>
</tr>
</tbody>
</table>
</div>
- {subUpdatePreview.immediatePayment.amount < 0 ? (
+ {(subUpdatePreview as any).immediatePayment.amount < 0 ? (
<p className='mt-2 italic'>
{t('billing.negativePayment', {
- currency: subUpdatePreview.immediatePayment.symbol,
- dueNowAmount: -subUpdatePreview.immediatePayment.amount,
+ currency: (subUpdatePreview as any).immediatePayment.symbol,
+ dueNowAmount: -(subUpdatePreview as any).immediatePayment.amount,
dueNowDate:
language === 'en'
- ? dayjs(subUpdatePreview.immediatePayment.date).locale(language).format('MMMM D, YYYY')
- : dayjs(subUpdatePreview.immediatePayment.date).locale(language).format('D MMMM, YYYY'),
- nextPaymentAmount: subUpdatePreview.nextPayment.amount,
+ ? dayjs((subUpdatePreview as any).immediatePayment.date)
+ .locale(language)
+ .format('MMMM D, YYYY')
+ : dayjs((subUpdatePreview as any).immediatePayment.date)
+ .locale(language)
+ .format('D MMMM, YYYY'),
+ nextPaymentAmount: (subUpdatePreview as any).nextPayment.amount,
})}
</p>
) : null}
@@ -486,12 +513,16 @@ const BillingPricing = ({ lastEvent }: BillingPricingProps) => {
<tbody className='divide-y divide-gray-200 bg-white dark:divide-gray-600 dark:bg-slate-800'>
<tr>
<td className='px-3 py-4 text-sm whitespace-nowrap text-gray-900 sm:pl-6 dark:text-gray-50'>
- {`${subUpdatePreview.nextPayment.symbol}${subUpdatePreview.nextPayment.amount}`}
+ {`${(subUpdatePreview as any).nextPayment.symbol}${(subUpdatePreview as any).nextPayment.amount}`}
</td>
<td className='px-3 py-4 text-sm whitespace-nowrap text-gray-900 dark:text-gray-50'>
{language === 'en'
- ? dayjs(subUpdatePreview.nextPayment.date).locale(language).format('MMMM D, YYYY')
- : dayjs(subUpdatePreview.nextPayment.date).locale(language).format('D MMMM, YYYY')}
+ ? dayjs((subUpdatePreview as any).nextPayment.date)
+ .locale(language)
+ .format('MMMM D, YYYY')
+ : dayjs((subUpdatePreview as any).nextPayment.date)
+ .locale(language)
+ .format('D MMMM, YYYY')}
</td>
</tr>
</tbody>
diff --git a/web/app/components/pricing/MarketingPricing.tsx b/web/app/components/pricing/MarketingPricing.tsx
index 1e4427038..e8dc44b0e 100644
--- a/web/app/components/pricing/MarketingPricing.tsx
+++ b/web/app/components/pricing/MarketingPricing.tsx
@@ -3,11 +3,10 @@ import { CheckIcon } from '@heroicons/react/24/solid'
import cx from 'clsx'
import _map from 'lodash/map'
import { ArrowRightIcon, CircleHelpIcon } from 'lucide-react'
-import { useEffect, useState } from 'react'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router'
-import { getPaymentMetainfo } from '~/api'
import { CURRENCIES, PLAN_LIMITS, STANDARD_PLANS, BillingFrequency, TRIAL_DAYS } from '~/lib/constants'
import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
import { useAuth } from '~/providers/AuthProvider'
@@ -16,20 +15,15 @@ import routes from '~/utils/routes'
const formatEventsLong = (value: number) => value.toLocaleString('en-US')
-const MarketingPricing = () => {
+interface MarketingPricingProps {
+ metainfo?: Metainfo
+}
+
+const MarketingPricing = ({ metainfo = DEFAULT_METAINFO }: MarketingPricingProps) => {
const { isAuthenticated } = useAuth()
const { t } = useTranslation('common')
- const [metainfo, setMetainfo] = useState<Metainfo>(DEFAULT_METAINFO)
const [billingFrequency, setBillingFrequency] = useState(BillingFrequency.monthly)
- useEffect(() => {
- const abortController = new AbortController()
- getPaymentMetainfo({ signal: abortController.signal })
- .then(setMetainfo)
- .catch(() => {})
- return () => abortController.abort()
- }, [])
-
const currencyCode = metainfo.code
const currency = CURRENCIES[currencyCode]
diff --git a/web/app/hoc/protected.tsx b/web/app/hoc/protected.tsx
deleted file mode 100644
index beed80d04..000000000
--- a/web/app/hoc/protected.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { useEffect } from 'react'
-import { useNavigate } from 'react-router'
-
-import { useAuth } from '~/providers/AuthProvider'
-import routes from '~/utils/routes'
-
-interface AuthParamType {
- shouldBeAuthenticated: boolean
- redirectPath: string
-}
-
-type PropsType = Record<string, any>
-
-export const auth = {
- authenticated: {
- shouldBeAuthenticated: true,
- redirectPath: routes.signin,
- },
- notAuthenticated: {
- shouldBeAuthenticated: false,
- redirectPath: routes.dashboard,
- },
-}
-
-export const withAuthentication = <P extends PropsType>(WrappedComponent: any, authParam: AuthParamType) => {
- const WithAuthentication = (props: P) => {
- const { shouldBeAuthenticated, redirectPath } = authParam
- const navigate = useNavigate()
- const { isAuthenticated, isLoading } = useAuth()
-
- useEffect(() => {
- if (isLoading) {
- return
- }
-
- if (shouldBeAuthenticated !== isAuthenticated) {
- navigate(redirectPath)
- }
- // TODO: Investigate this later. https://github.com/remix-run/react-router/discussions/8465
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isAuthenticated, shouldBeAuthenticated, isLoading])
-
- return <WrappedComponent {...props} />
- }
-
- return WithAuthentication
-}
diff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.ts
new file mode 100644
index 000000000..52957cc9d
--- /dev/null
+++ b/web/app/hooks/useAnalyticsProxy.ts
@@ -0,0 +1,748 @@
+import { useCallback, useState } from 'react'
+
+import type {
+ SessionsResponse,
+ ErrorsResponse,
+ FeatureFlagStats,
+ FeatureFlagProfilesResponse,
+ GoalStats,
+ GoalChartData,
+ CaptchaDataResponse,
+ ExperimentResults,
+ Experiment,
+ Goal,
+ GoalsResponse,
+ FeatureFlagsResponse,
+ ProfilesResponse,
+ ProfileDetailsResponse,
+ ProfileSessionsResponse,
+ VersionFilter,
+ CustomEventsMetadataResponse,
+ PropertyMetadataResponse,
+ ErrorSessionsResponse,
+ LiveStats,
+ LiveVisitorInfo,
+ ProjectDataCustomEventsResponse,
+ UserFlowResponse,
+ GSCKeywordsResponse,
+ RevenueStatus,
+ RevenueDataResponse,
+ OverallObject,
+ AnalyticsParams as ServerAnalyticsParams,
+} from '~/api/api.server'
+
+type ClientAnalyticsParams = Partial<Omit<ServerAnalyticsParams, 'password'>> & {
+ take?: number
+ skip?: number
+ options?: Record<string, unknown>
+ resultFilter?: string
+ search?: string
+}
+
+interface ProxyResponse<T> {
+ data: T | null
+ error: string | null
+}
+
+async function postAnalytics<T>(payload: unknown): Promise<ProxyResponse<T>> {
+ const response = await fetch('/api/analytics', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ })
+
+ let result: ProxyResponse<T>
+ try {
+ result = (await response.json()) as ProxyResponse<T>
+ } catch {
+ throw new Error(`Invalid JSON from /api/analytics (status ${response.status})`)
+ }
+
+ if (!response.ok) {
+ throw new Error(result.error || `Request failed (status ${response.status})`)
+ }
+ return result
+}
+
+export function useSessionsProxy() {
+ const [data, setData] = useState<SessionsResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchSessions = useCallback(async (projectId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<SessionsResponse>({ action: 'getSessions', projectId, params })
+ setData(result.data)
+ setError(result.error)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchSessions, data, error, isLoading }
+}
+
+export function useErrorsProxy() {
+ const [data, setData] = useState<ErrorsResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchErrors = useCallback(async (projectId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<ErrorsResponse>({ action: 'getErrors', projectId, params })
+ setData(result.data)
+ setError(result.error)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchErrors, data, error, isLoading }
+}
+
+export function useFeatureFlagStatsProxy() {
+ const [data, setData] = useState<FeatureFlagStats | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchStats = useCallback(async (flagId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<FeatureFlagStats>({ action: 'getFeatureFlagStats', flagId, params })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchStats, data, error, isLoading }
+}
+
+export function useFeatureFlagProfilesProxy() {
+ const [data, setData] = useState<FeatureFlagProfilesResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchProfiles = useCallback(async (flagId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<FeatureFlagProfilesResponse>({
+ action: 'getFeatureFlagProfiles',
+ flagId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchProfiles, data, error, isLoading }
+}
+
+export function useGoalStatsProxy() {
+ const [data, setData] = useState<GoalStats | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchStats = useCallback(async (goalId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<GoalStats>({ action: 'getGoalStats', goalId, params })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchStats, data, error, isLoading }
+}
+
+export function useGoalChartProxy() {
+ const [data, setData] = useState<{ chart: GoalChartData } | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchChart = useCallback(async (goalId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<{ chart: GoalChartData }>({ action: 'getGoalChart', goalId, params })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchChart, data, error, isLoading }
+}
+
+export function useCaptchaProxy() {
+ const [data, setData] = useState<CaptchaDataResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchCaptcha = useCallback(async (projectId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<CaptchaDataResponse>({ action: 'getCaptchaData', projectId, params })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchCaptcha, data, error, isLoading }
+}
+
+export function useExperimentResultsProxy() {
+ const [data, setData] = useState<ExperimentResults | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchResults = useCallback(async (experimentId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<ExperimentResults>({ action: 'getExperimentResults', experimentId, params })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchResults, data, error, isLoading }
+}
+
+export function useExperimentProxy() {
+ const [data, setData] = useState<Experiment | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchExperiment = useCallback(async (experimentId: string) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<Experiment>({ action: 'getExperiment', experimentId, params: {} })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchExperiment, data, error, isLoading }
+}
+
+export function useGoalProxy() {
+ const [data, setData] = useState<Goal | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchGoal = useCallback(async (goalId: string) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<Goal>({ action: 'getGoal', goalId, params: {} })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchGoal, data, error, isLoading }
+}
+
+export function useProjectGoalsProxy() {
+ const [data, setData] = useState<GoalsResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchGoals = useCallback(async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<GoalsResponse>({ action: 'getProjectGoals', projectId, params })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchGoals, data, error, isLoading }
+}
+
+export function useProjectFeatureFlagsProxy() {
+ const [data, setData] = useState<FeatureFlagsResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchFeatureFlags = useCallback(async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<FeatureFlagsResponse>({ action: 'getProjectFeatureFlags', projectId, params })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchFeatureFlags, data, error, isLoading }
+}
+
+export function useProfilesProxy() {
+ const [data, setData] = useState<ProfilesResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchProfiles = useCallback(
+ async (
+ projectId: string,
+ params: ClientAnalyticsParams & { profileType?: 'all' | 'anonymous' | 'identified' } = {},
+ ) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<ProfilesResponse>({ action: 'getProfiles', projectId, params })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
+
+ return { fetchProfiles, data, error, isLoading }
+}
+
+export function useProfileProxy() {
+ const [data, setData] = useState<ProfileDetailsResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchProfile = useCallback(async (projectId: string, profileId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<ProfileDetailsResponse>({ action: 'getProfile', projectId, profileId, params })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchProfile, data, error, isLoading }
+}
+
+export function useProfileSessionsProxy() {
+ const [data, setData] = useState<ProfileSessionsResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchProfileSessions = useCallback(
+ async (projectId: string, profileId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<ProfileSessionsResponse>({
+ action: 'getProfileSessions',
+ projectId,
+ profileId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
+
+ return { fetchProfileSessions, data, error, isLoading }
+}
+
+export function useFiltersProxy() {
+ const fetchFilters = useCallback(async (projectId: string, filterType: string): Promise<string[] | null> => {
+ try {
+ const result = await postAnalytics<string[]>({ action: 'getFilters', projectId, filterType, params: {} })
+ return result.data
+ } catch (err) {
+ console.error('[useFiltersProxy] Error:', err)
+ throw err
+ }
+ }, [])
+
+ const fetchErrorsFilters = useCallback(async (projectId: string, filterType: string): Promise<string[] | null> => {
+ try {
+ const result = await postAnalytics<string[]>({ action: 'getErrorsFilters', projectId, filterType, params: {} })
+ return result.data
+ } catch (err) {
+ console.error('[useFiltersProxy] Error:', err)
+ throw err
+ }
+ }, [])
+
+ const fetchVersionFilters = useCallback(
+ async (
+ projectId: string,
+ dataType: 'traffic' | 'errors',
+ filterColumn: 'br' | 'os',
+ ): Promise<VersionFilter[] | null> => {
+ try {
+ const result = await postAnalytics<VersionFilter[]>({
+ action: 'getVersionFilters',
+ projectId,
+ dataType,
+ filterColumn,
+ params: {},
+ })
+ return result.data
+ } catch (err) {
+ console.error('[useFiltersProxy] Error:', err)
+ throw err
+ }
+ },
+ [],
+ )
+
+ return { fetchFilters, fetchErrorsFilters, fetchVersionFilters }
+}
+
+export function useCustomEventsMetadataProxy() {
+ const fetchMetadata = useCallback(
+ async (
+ projectId: string,
+ event: string,
+ params: ClientAnalyticsParams = {},
+ ): Promise<CustomEventsMetadataResponse | null> => {
+ try {
+ const result = await postAnalytics<CustomEventsMetadataResponse>({
+ action: 'getCustomEventsMetadata',
+ projectId,
+ event,
+ params,
+ })
+ return result.data
+ } catch (err) {
+ console.error('[useCustomEventsMetadataProxy] Error:', err)
+ throw err
+ }
+ },
+ [],
+ )
+
+ return { fetchMetadata }
+}
+
+export function usePropertyMetadataProxy() {
+ const fetchMetadata = useCallback(
+ async (
+ projectId: string,
+ property: string,
+ params: ClientAnalyticsParams = {},
+ ): Promise<PropertyMetadataResponse | null> => {
+ try {
+ const result = await postAnalytics<PropertyMetadataResponse>({
+ action: 'getPropertyMetadata',
+ projectId,
+ property,
+ params,
+ })
+ return result.data
+ } catch (err) {
+ console.error('[usePropertyMetadataProxy] Error:', err)
+ throw err
+ }
+ },
+ [],
+ )
+
+ return { fetchMetadata }
+}
+
+export function useErrorSessionsProxy() {
+ const [data, setData] = useState<ErrorSessionsResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchErrorSessions = useCallback(
+ async (projectId: string, errorId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<ErrorSessionsResponse>({
+ action: 'getErrorSessions',
+ projectId,
+ errorId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
+
+ return { fetchErrorSessions, data, error, isLoading }
+}
+
+export function useLiveVisitorsProxy() {
+ const fetchLiveVisitors = useCallback(async (pids: string[]): Promise<LiveStats | null> => {
+ if (!pids || pids.length === 0) {
+ return null
+ }
+
+ try {
+ const result = await postAnalytics<LiveStats>({ action: 'getLiveVisitors', pids, params: {} })
+ return result.data
+ } catch (err) {
+ console.error('[useLiveVisitorsProxy] Error:', err)
+ throw err
+ }
+ }, [])
+
+ const fetchLiveVisitorsInfo = useCallback(async (projectId: string): Promise<LiveVisitorInfo[] | null> => {
+ try {
+ const result = await postAnalytics<LiveVisitorInfo[]>({ action: 'getLiveVisitorsInfo', projectId, params: {} })
+ return result.data
+ } catch (err) {
+ console.error('[useLiveVisitorsProxy] Error:', err)
+ throw err
+ }
+ }, [])
+
+ return { fetchLiveVisitors, fetchLiveVisitorsInfo }
+}
+
+export function useProjectDataCustomEventsProxy() {
+ const fetchCustomEvents = useCallback(
+ async (
+ projectId: string,
+ customEvents: string[],
+ params: ClientAnalyticsParams = {},
+ ): Promise<ProjectDataCustomEventsResponse | null> => {
+ try {
+ const result = await postAnalytics<ProjectDataCustomEventsResponse>({
+ action: 'getProjectDataCustomEvents',
+ projectId,
+ customEvents,
+ params,
+ })
+ return result.data
+ } catch (err) {
+ console.error('[useProjectDataCustomEventsProxy] Error:', err)
+ throw err
+ }
+ },
+ [],
+ )
+
+ return { fetchCustomEvents }
+}
+
+export function useUserFlowProxy() {
+ const [data, setData] = useState<UserFlowResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchUserFlow = useCallback(async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<UserFlowResponse>({ action: 'getUserFlow', projectId, params })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchUserFlow, data, error, isLoading }
+}
+
+export function useGSCKeywordsProxy() {
+ const [data, setData] = useState<GSCKeywordsResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchKeywords = useCallback(async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<GSCKeywordsResponse>({ action: 'getGSCKeywords', projectId, params })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchKeywords, data, error, isLoading }
+}
+
+export function useRevenueProxy() {
+ const [statusData, setStatusData] = useState<RevenueStatus | null>(null)
+ const [revenueData, setRevenueData] = useState<RevenueDataResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchRevenueStatus = useCallback(async (projectId: string): Promise<RevenueStatus | null> => {
+ try {
+ const result = await postAnalytics<RevenueStatus>({ action: 'getRevenueStatus', projectId, params: {} })
+ setStatusData(result.data)
+ return result.data
+ } catch (err) {
+ console.error('[useRevenueProxy] Error:', err)
+ throw err
+ }
+ }, [])
+
+ const fetchRevenueData = useCallback(async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<RevenueDataResponse>({ action: 'getRevenueData', projectId, params })
+ setRevenueData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ return { fetchRevenueStatus, fetchRevenueData, statusData, revenueData, error, isLoading }
+}
+
+export function useOverallStatsProxy() {
+ const fetchOverallStats = useCallback(
+ async (pids: string[], params: ClientAnalyticsParams = {}): Promise<Record<string, OverallObject> | null> => {
+ try {
+ const result = await postAnalytics<Record<string, OverallObject>>({
+ action: 'getOverallStats',
+ pids,
+ params,
+ })
+ return result.data
+ } catch (err) {
+ console.error('[useOverallStatsProxy] Error:', err)
+ return null
+ }
+ },
+ [],
+ )
+
+ return { fetchOverallStats }
+}
diff --git a/web/app/hooks/useAnnotations.ts b/web/app/hooks/useAnnotations.ts
index 6fd7b329d..edffe8fb4 100644
--- a/web/app/hooks/useAnnotations.ts
+++ b/web/app/hooks/useAnnotations.ts
@@ -1,29 +1,20 @@
import dayjs from 'dayjs'
import { useState, useCallback, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { getAnnotations, createAnnotation, updateAnnotation, deleteAnnotation } from '~/api'
import { Annotation } from '~/lib/models/Project'
import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import { ProjectViewActionData } from '~/routes/projects.$id'
-/**
- * Pixel distance threshold for snapping to nearby annotations when clicking on the chart.
- * If a click is within this many pixels of an annotation line, that annotation will be selected.
- */
const ANNOTATION_CLICK_THRESHOLD_PX = 30
-/** Chart metrics derived from SVG/DOM layout */
interface ChartMetrics {
- /** X coordinate where the chart plotting area begins (left edge of x-axis) */
chartAreaStart: number
- /** Width of the chart plotting area */
chartAreaWidth: number
}
-/**
- * Traverses up the DOM tree from a target element to find an annotation line element.
- */
const findAnnotationLineElement = (target: Element, boundary: Element): Element | null => {
let element: Element | null = target
@@ -37,9 +28,6 @@ const findAnnotationLineElement = (target: Element, boundary: Element): Element
return null
}
-/**
- * Extracts the annotation ID from an annotation line element's class list.
- */
const getAnnotationIdFromElement = (element: Element): string | null => {
const classes = element.classList
for (const className of classes) {
@@ -50,17 +38,12 @@ const getAnnotationIdFromElement = (element: Element): string | null => {
return null
}
-/**
- * Calculates the chart area metrics by examining the SVG's x-axis domain path.
- */
const calculateChartMetrics = (svg: SVGSVGElement, chartContainer: HTMLElement): ChartMetrics => {
const svgRect = svg.getBoundingClientRect()
- // Default fallbacks based on typical billboard.js chart layout
let chartAreaStart = 50
let chartAreaWidth = svgRect.width - 70
- // Try to get exact boundaries from the x-axis domain path (the axis line)
const xAxisPath = chartContainer.querySelector('.bb-axis-x path.domain') as SVGPathElement | null
if (xAxisPath) {
const pathBBox = xAxisPath.getBBox()
@@ -71,9 +54,6 @@ const calculateChartMetrics = (svg: SVGSVGElement, chartContainer: HTMLElement):
return { chartAreaStart, chartAreaWidth }
}
-/**
- * Calculates the date corresponding to a click position on the chart.
- */
const calculateDateFromPosition = (
clientX: number,
svgRect: DOMRect,
@@ -83,20 +63,15 @@ const calculateDateFromPosition = (
const clickX = clientX - svgRect.left
const { chartAreaStart, chartAreaWidth } = chartMetrics
- // Calculate relative position within the chart area (clamped to [0, 1])
const relativeX = Math.max(0, clickX - chartAreaStart)
const percentage = Math.min(1, relativeX / chartAreaWidth)
- // Map percentage to index in xAxisData
const index = Math.round(percentage * (xAxisData.length - 1))
const clampedIndex = Math.max(0, Math.min(xAxisData.length - 1, index))
return dayjs(xAxisData[clampedIndex]).format('YYYY-MM-DD')
}
-/**
- * Finds the closest annotation to a click position within the pixel threshold.
- */
const findClosestAnnotation = (
clickX: number,
annotations: Annotation[],
@@ -112,11 +87,9 @@ const findClosestAnnotation = (
for (const annotation of annotations) {
const annotationDate = dayjs(annotation.date).format('YYYY-MM-DD')
- // Find the index of this annotation's date in xAxisData
const annotationIndex = xAxisData.findIndex((xDate) => dayjs(xDate).format('YYYY-MM-DD') === annotationDate)
if (annotationIndex !== -1) {
- // Calculate the x position of this annotation on the chart
const annotationPercentage = annotationIndex / (xAxisData.length - 1)
const annotationX = chartAreaStart + annotationPercentage * chartAreaWidth
const distance = Math.abs(clickX - annotationX)
@@ -132,7 +105,6 @@ const findClosestAnnotation = (
}
interface UseAnnotationsReturn {
- // State
annotations: Annotation[]
annotationsLoading: boolean
isAnnotationModalOpen: boolean
@@ -147,11 +119,10 @@ interface UseAnnotationsReturn {
annotation: Annotation | null
}
- // Actions
- loadAnnotations: () => Promise<void>
- onAnnotationCreate: (date: string, text: string) => Promise<void>
- onAnnotationUpdate: (date: string, text: string) => Promise<void>
- onAnnotationDelete: (annotation?: Annotation) => Promise<void>
+ loadAnnotations: () => void
+ onAnnotationCreate: (date: string, text: string) => void
+ onAnnotationUpdate: (date: string, text: string) => void
+ onAnnotationDelete: (annotation?: Annotation) => void
openAnnotationModal: (date?: string, annotation?: Annotation) => void
closeAnnotationModal: () => void
handleChartContextMenu: (event: React.MouseEvent, xAxisData: string[] | undefined) => void
@@ -163,15 +134,16 @@ export const useAnnotations = (): UseAnnotationsReturn => {
const projectPassword = useProjectPassword(id)
const { t } = useTranslation('common')
- // Annotations state
+ const fetcher = useFetcher<ProjectViewActionData>()
+ const loadFetcher = useFetcher<ProjectViewActionData>()
+
const [annotations, setAnnotations] = useState<Annotation[]>([])
const [annotationsLoading, setAnnotationsLoading] = useState(false)
const [isAnnotationModalOpen, setIsAnnotationModalOpen] = useState(false)
const [annotationToEdit, setAnnotationToEdit] = useState<Annotation | undefined>()
const [annotationModalDate, setAnnotationModalDate] = useState<string | undefined>()
- const [annotationActionLoading, setAnnotationActionLoading] = useState(false)
+ const [pendingAction, setPendingAction] = useState<'create' | 'update' | 'delete' | null>(null)
- // Chart context menu state
const [contextMenu, setContextMenu] = useState<{
isOpen: boolean
x: number
@@ -186,90 +158,113 @@ export const useAnnotations = (): UseAnnotationsReturn => {
annotation: null,
})
- const loadAnnotations = useCallback(async () => {
- if (annotationsLoading) {
+ const loadAnnotations = useCallback(() => {
+ if (loadFetcher.state !== 'idle') {
return
}
setAnnotationsLoading(true)
+ const formData = new FormData()
+ formData.append('intent', 'get-annotations')
+ if (projectPassword) {
+ formData.append('password', projectPassword)
+ }
- try {
- const data = await getAnnotations(id, projectPassword)
- setAnnotations(data || [])
- } catch (reason: any) {
- console.error('[ERROR] (loadAnnotations)', reason)
+ loadFetcher.submit(formData, { method: 'POST' })
+ }, [loadFetcher, projectPassword])
+
+ useEffect(() => {
+ if (loadFetcher.state === 'idle') {
+ setAnnotationsLoading(false)
+ if (loadFetcher.data) {
+ if (loadFetcher.data.success && loadFetcher.data.data) {
+ setAnnotations((loadFetcher.data.data as Annotation[]) || [])
+ } else if (loadFetcher.data.error) {
+ toast.error(loadFetcher.data.error)
+ } else {
+ setAnnotations([])
+ }
+ }
}
+ }, [loadFetcher.state, loadFetcher.data])
- setAnnotationsLoading(false)
- }, [id, projectPassword, annotationsLoading])
+ const closeAnnotationModal = useCallback(() => {
+ setIsAnnotationModalOpen(false)
+ setAnnotationToEdit(undefined)
+ setAnnotationModalDate(undefined)
+ }, [])
+
+ useEffect(() => {
+ if (fetcher.state === 'idle' && fetcher.data && pendingAction) {
+ if (fetcher.data.success) {
+ if (pendingAction === 'create') {
+ toast.success(t('apiNotifications.annotationCreated'))
+ } else if (pendingAction === 'update') {
+ toast.success(t('apiNotifications.annotationUpdated'))
+ } else if (pendingAction === 'delete') {
+ toast.success(t('apiNotifications.annotationDeleted'))
+ }
+ loadAnnotations()
+ closeAnnotationModal()
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ setPendingAction(null)
+ setAnnotationToEdit(undefined)
+ }
+ }, [fetcher.state, fetcher.data, pendingAction, loadAnnotations, t, closeAnnotationModal])
const onAnnotationCreate = useCallback(
- async (date: string, text: string) => {
- if (annotationActionLoading) {
+ (date: string, text: string) => {
+ if (fetcher.state !== 'idle') {
return
}
- setAnnotationActionLoading(true)
-
- try {
- await createAnnotation(id, date, text)
- await loadAnnotations()
- toast.success(t('apiNotifications.annotationCreated'))
- } catch (reason: any) {
- console.error('[ERROR] (onAnnotationCreate)', reason)
- toast.error(reason)
- }
+ setPendingAction('create')
+ const formData = new FormData()
+ formData.append('intent', 'create-annotation')
+ formData.append('date', date)
+ formData.append('text', text)
- setAnnotationActionLoading(false)
+ fetcher.submit(formData, { method: 'POST' })
},
- [id, annotationActionLoading, loadAnnotations, t],
+ [fetcher],
)
const onAnnotationUpdate = useCallback(
- async (date: string, text: string) => {
- if (annotationActionLoading || !annotationToEdit) {
+ (date: string, text: string) => {
+ if (fetcher.state !== 'idle' || !annotationToEdit) {
return
}
- setAnnotationActionLoading(true)
-
- try {
- await updateAnnotation(annotationToEdit.id, id, date, text)
- await loadAnnotations()
- toast.success(t('apiNotifications.annotationUpdated'))
- } catch (reason: any) {
- console.error('[ERROR] (onAnnotationUpdate)', reason)
- toast.error(reason)
- }
+ setPendingAction('update')
+ const formData = new FormData()
+ formData.append('intent', 'update-annotation')
+ formData.append('annotationId', annotationToEdit.id)
+ formData.append('date', date)
+ formData.append('text', text)
- setAnnotationActionLoading(false)
+ fetcher.submit(formData, { method: 'POST' })
},
- [id, annotationActionLoading, annotationToEdit, loadAnnotations, t],
+ [fetcher, annotationToEdit],
)
const onAnnotationDelete = useCallback(
- async (annotation?: Annotation) => {
+ (annotation?: Annotation) => {
const targetAnnotation = annotation || annotationToEdit
- if (annotationActionLoading || !targetAnnotation) {
+ if (fetcher.state !== 'idle' || !targetAnnotation) {
return
}
- setAnnotationActionLoading(true)
-
- try {
- await deleteAnnotation(targetAnnotation.id, id)
- await loadAnnotations()
- toast.success(t('apiNotifications.annotationDeleted'))
- } catch (reason: any) {
- console.error('[ERROR] (onAnnotationDelete)', reason)
- toast.error(reason)
- }
+ setPendingAction('delete')
+ const formData = new FormData()
+ formData.append('intent', 'delete-annotation')
+ formData.append('annotationId', targetAnnotation.id)
- setAnnotationActionLoading(false)
- setAnnotationToEdit(undefined)
+ fetcher.submit(formData, { method: 'POST' })
},
- [id, annotationActionLoading, annotationToEdit, loadAnnotations, t],
+ [fetcher, annotationToEdit],
)
const openAnnotationModal = useCallback((date?: string, annotation?: Annotation) => {
@@ -278,12 +273,6 @@ export const useAnnotations = (): UseAnnotationsReturn => {
setIsAnnotationModalOpen(true)
}, [])
- const closeAnnotationModal = useCallback(() => {
- setIsAnnotationModalOpen(false)
- setAnnotationToEdit(undefined)
- setAnnotationModalDate(undefined)
- }, [])
-
const handleChartContextMenu = useCallback(
(event: React.MouseEvent, xAxisData: string[] | undefined) => {
event.preventDefault()
@@ -291,11 +280,9 @@ export const useAnnotations = (): UseAnnotationsReturn => {
let existingAnnotation: Annotation | null = null
let date: string | null = null
- // Check if user clicked directly on an annotation line
const annotationLineElement = findAnnotationLineElement(event.target as Element, event.currentTarget as Element)
if (annotationLineElement) {
- // User clicked on an annotation line - find it by ID from the element's class
const annotationId = getAnnotationIdFromElement(annotationLineElement)
if (annotationId) {
existingAnnotation = annotations.find((a) => a.id === annotationId) || null
@@ -305,7 +292,6 @@ export const useAnnotations = (): UseAnnotationsReturn => {
}
}
- // If not clicking on an annotation line, calculate date from click position
if (!existingAnnotation && xAxisData && xAxisData.length > 0) {
const chartContainer = (event.currentTarget as HTMLElement).querySelector('.bb') as HTMLElement
const svg = chartContainer?.querySelector('svg') as SVGSVGElement | null
@@ -317,10 +303,8 @@ export const useAnnotations = (): UseAnnotationsReturn => {
date = calculateDateFromPosition(event.clientX, svgRect, xAxisData, chartMetrics)
- // Check for exact date match first
existingAnnotation = annotations.find((a) => dayjs(a.date).format('YYYY-MM-DD') === date) || null
- // If no exact match, try to find the closest annotation within threshold
if (!existingAnnotation && annotations.length > 0) {
const closestAnnotation = findClosestAnnotation(
clickX,
@@ -363,8 +347,9 @@ export const useAnnotations = (): UseAnnotationsReturn => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [project])
+ const annotationActionLoading = fetcher.state !== 'idle'
+
return {
- // State
annotations,
annotationsLoading,
isAnnotationModalOpen,
@@ -373,7 +358,6 @@ export const useAnnotations = (): UseAnnotationsReturn => {
annotationActionLoading,
contextMenu,
- // Actions
loadAnnotations,
onAnnotationCreate,
onAnnotationUpdate,
diff --git a/web/app/hooks/useAuthProxy.ts b/web/app/hooks/useAuthProxy.ts
new file mode 100644
index 000000000..afb976c9b
--- /dev/null
+++ b/web/app/hooks/useAuthProxy.ts
@@ -0,0 +1,121 @@
+import { useCallback } from 'react'
+
+import type { SSOProvider, SSOAuthURLResponse, SSOHashResponse, AuthMeResponse } from '~/api/api.server'
+
+interface ProxyResponse<T> {
+ data: T | null
+ error: string | null
+}
+
+export function useAuthProxy() {
+ const generateSSOAuthURL = useCallback(
+ async (provider: SSOProvider, redirectUrl?: string): Promise<SSOAuthURLResponse> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'generateSSOAuthURL', provider, redirectUrl }),
+ })
+ const result = (await response.json()) as ProxyResponse<SSOAuthURLResponse>
+ if (result.error || !result.data) {
+ throw new Error(result.error || 'Failed to generate SSO URL')
+ }
+ return result.data
+ },
+ [],
+ )
+
+ const getJWTBySSOHash = useCallback(
+ async (hash: string, provider: SSOProvider, remember = false): Promise<SSOHashResponse> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'getJWTBySSOHash', hash, provider, remember }),
+ })
+ const result = (await response.json()) as ProxyResponse<SSOHashResponse>
+ if (result.error || !result.data) {
+ throw new Error(result.error || 'Failed to get JWT by SSO hash')
+ }
+ return result.data
+ },
+ [],
+ )
+
+ const processSSOTokenCommunityEdition = useCallback(
+ async (code: string, hash: string, redirectUrl: string): Promise<unknown> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'processSSOTokenCommunityEdition', code, hash, redirectUrl }),
+ })
+ const result = (await response.json()) as ProxyResponse<unknown>
+ if (result.error) {
+ throw new Error(result.error)
+ }
+ return result.data
+ },
+ [],
+ )
+
+ const linkBySSOHash = useCallback(async (hash: string, provider: SSOProvider): Promise<unknown> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'linkBySSOHash', hash, provider }),
+ })
+ const result = (await response.json()) as ProxyResponse<unknown>
+ if (result.error) {
+ throw new Error(result.error)
+ }
+ return result.data
+ }, [])
+
+ const processSSOToken = useCallback(async (token: string, hash: string): Promise<unknown> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'processSSOToken', token, hash }),
+ })
+ const result = (await response.json()) as ProxyResponse<unknown>
+ if (result.error) {
+ throw new Error(result.error)
+ }
+ return result.data
+ }, [])
+
+ const processGSCToken = useCallback(async (code: string, state: string): Promise<{ pid: string }> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'processGSCToken', code, state }),
+ })
+ const result = (await response.json()) as ProxyResponse<{ pid: string }>
+ if (result.error || !result.data) {
+ throw new Error(result.error || 'Failed to process GSC token')
+ }
+ return result.data
+ }, [])
+
+ const authMe = useCallback(async (signal?: AbortSignal): Promise<AuthMeResponse> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'authMe' }),
+ signal,
+ })
+ const result = (await response.json()) as ProxyResponse<AuthMeResponse>
+ if (result.error || !result.data) {
+ throw new Error(result.error || 'Failed to fetch user')
+ }
+ return result.data
+ }, [])
+
+ return {
+ generateSSOAuthURL,
+ getJWTBySSOHash,
+ processSSOTokenCommunityEdition,
+ linkBySSOHash,
+ processSSOToken,
+ processGSCToken,
+ authMe,
+ }
+}
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index e96017bcb..b9c1bdec2 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -329,8 +329,6 @@ export const getOgImageUrl = (title: string) => {
// Cookies
export const CONFIRMATION_TIMEOUT = 'confirmation_timeout'
export const LOW_EVENTS_WARNING = 'low_events_warning'
-export const TOKEN = 'access_token'
-export const REFRESH_TOKEN = 'refresh_token'
// LocalStorage
export const LS_PROJECTS_PROTECTED_KEY = 'projects_protected'
diff --git a/web/app/lib/models/Alerts.ts b/web/app/lib/models/Alerts.ts
index cc283dcd8..8538ca59d 100644
--- a/web/app/lib/models/Alerts.ts
+++ b/web/app/lib/models/Alerts.ts
@@ -13,4 +13,5 @@ export interface Alerts {
lastTriggered: string | null
alertOnNewErrorsOnly?: boolean
alertOnEveryCustomEvent?: boolean
+ created: string
}
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index d764dcf08..bfffbc8c1 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -48,8 +48,6 @@ interface UserShareProject {
id: string
}
-export type LiveStats = Record<string, number>
-
export interface ShareOwnerProject {
id: string
confirmed: boolean
@@ -85,13 +83,6 @@ export interface SwetrixError {
sessions: number
}
-export interface SwetrixErrorDetails extends SwetrixError {
- colno: number
- lineno: number
- first_seen: string
- stackTrace?: string
-}
-
export interface Session {
psid: string
cc: string | null
@@ -177,6 +168,7 @@ export interface AnalyticsFunnel {
eventsPerc: number
eventsPercStep: number
dropoff: number
+ dropoffPerc: number
dropoffPercStep: number
}
diff --git a/web/app/modals/AnnotationModal.tsx b/web/app/modals/AnnotationModal.tsx
index 7bab7e10b..11c69a335 100644
--- a/web/app/modals/AnnotationModal.tsx
+++ b/web/app/modals/AnnotationModal.tsx
@@ -13,8 +13,8 @@ const MAX_ANNOTATION_LENGTH = 120
interface AnnotationModalProps {
onClose: () => void
- onSubmit: (date: string, text: string) => Promise<void>
- onDelete?: () => Promise<void>
+ onSubmit: (date: string, text: string) => void
+ onDelete?: () => void
isOpened: boolean
loading: boolean
annotation?: Annotation
@@ -57,22 +57,20 @@ const AnnotationModal = ({
onClose()
}
- const _onSubmit = async () => {
+ const _onSubmit = () => {
if (!date || !text.trim() || !allowedToManage) {
return
}
- await onSubmit(date, text.trim())
- _onClose()
+ onSubmit(date, text.trim())
}
- const _onDelete = async () => {
+ const _onDelete = () => {
if (!onDelete || !allowedToManage) {
return
}
- await onDelete()
- _onClose()
+ onDelete()
}
const isEditMode = !!annotation
diff --git a/web/app/pages/Auth/ChangeEmail/index.tsx b/web/app/pages/Auth/ChangeEmail/index.tsx
deleted file mode 100644
index 8f95121ac..000000000
--- a/web/app/pages/Auth/ChangeEmail/index.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import _isString from 'lodash/isString'
-import { useState, useEffect } from 'react'
-import { useTranslation } from 'react-i18next'
-import { useParams } from 'react-router'
-
-import { confirmChangeEmail } from '~/api'
-import StatusPage from '~/ui/StatusPage'
-import routes from '~/utils/routes'
-
-const ChangeEmail = () => {
- const { t } = useTranslation('common')
- const { id } = useParams()
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState('')
-
- useEffect(() => {
- // eslint-disable-next-line react-hooks/set-state-in-effect -- Async email verification flow
- setLoading(true)
-
- if (!_isString(id)) {
- setError(t('auth.verification.invalid'))
- setLoading(false)
- return
- }
-
- confirmChangeEmail({ id })
- .then(() => {
- setLoading(false)
- })
- .catch((reason) => {
- setError(reason.toString())
- setLoading(false)
- })
- }, [id]) // eslint-disable-line
-
- if (loading) {
- return <StatusPage loading />
- }
-
- if (error) {
- return (
- <StatusPage
- type='error'
- title={error}
- actions={[
- { label: t('common.dashboard'), to: routes.dashboard, primary: true },
- { label: t('notFoundPage.support'), to: routes.contact },
- ]}
- />
- )
- }
-
- return (
- <StatusPage
- type='success'
- title={t('auth.verification.success')}
- actions={[{ label: t('common.dashboard'), to: routes.dashboard, primary: true }]}
- />
- )
-}
-
-export default ChangeEmail
diff --git a/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx b/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx
index e96f8267b..a54318e4f 100644
--- a/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx
+++ b/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx
@@ -1,102 +1,26 @@
-import _isEmpty from 'lodash/isEmpty'
-import _keys from 'lodash/keys'
-import _size from 'lodash/size'
-import React, { useState, useEffect } from 'react'
+import React, { useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { Link, useNavigate, useParams } from 'react-router'
+import { Link, Form, useActionData, useNavigation } from 'react-router'
import { toast } from 'sonner'
-import { createNewPassword } from '~/api'
-import { withAuthentication, auth } from '~/hoc/protected'
+import type { CreateNewPasswordActionData } from '~/routes/password-reset.$id'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import routes from '~/utils/routes'
-import { isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS } from '~/utils/validator'
-
-interface FormSubmitData {
- password: string
- repeat: string
-}
+import { MIN_PASSWORD_CHARS } from '~/utils/validator'
const CreateNewPassword = () => {
const { t } = useTranslation('common')
- const navigate = useNavigate()
- const { id } = useParams()
- const [form, setForm] = useState<FormSubmitData>({
- password: '',
- repeat: '',
- })
- const [validated, setValidated] = useState(false)
- const [errors, setErrors] = useState<{
- password?: string
- repeat?: string
- }>({})
- const [beenSubmitted, setBeenSubmitted] = useState(false)
- const [isLoading, setIsLoading] = useState(false)
-
- const validate = () => {
- const allErrors = {} as {
- password?: string
- repeat?: string
- }
-
- if (!isValidPassword(form.password)) {
- allErrors.password = t('auth.common.xCharsError', { amount: MIN_PASSWORD_CHARS })
- }
-
- if (form.password !== form.repeat || form.repeat === '') {
- allErrors.repeat = t('auth.common.noMatchError')
- }
-
- if (_size(form.password) > 50) {
- allErrors.password = t('auth.common.passwordTooLong', { amount: MAX_PASSWORD_CHARS })
- }
-
- const valid = _isEmpty(_keys(allErrors))
+ const navigation = useNavigation()
+ const actionData = useActionData<CreateNewPasswordActionData>()
- setErrors(allErrors)
- setValidated(valid)
- }
+ const isSubmitting = navigation.state === 'submitting'
useEffect(() => {
- validate()
- }, [form]) // eslint-disable-line
-
- const onSubmit = async (data: FormSubmitData) => {
- if (!isLoading) {
- setIsLoading(true)
- try {
- const { password } = data
- await createNewPassword(id as string, password)
-
- toast.success(t('auth.recovery.updated'))
- navigate(routes.signin)
- } catch (reason: any) {
- toast.error(reason.toString())
- } finally {
- setIsLoading(false)
- }
- }
- }
-
- const handleInput = ({ target }: { target: HTMLInputElement }) => {
- const value = target.type === 'checkbox' ? target.checked : target.value
-
- setForm((oldForm) => ({
- ...oldForm,
- [target.name]: value,
- }))
- }
-
- const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
- e.preventDefault()
- e.stopPropagation()
- setBeenSubmitted(true)
-
- if (validated) {
- onSubmit(form)
+ if (actionData?.error) {
+ toast.error(actionData.error)
}
- }
+ }, [actionData?.error, actionData?.timestamp])
return (
<div>
@@ -108,28 +32,26 @@ const CreateNewPassword = () => {
</div>
<div className='mt-10 sm:mx-auto sm:w-full sm:max-w-[480px]'>
<div className='bg-white px-6 py-12 shadow-xs ring-1 ring-gray-200 sm:rounded-lg sm:px-12 dark:bg-slate-900 dark:ring-slate-800'>
- <form className='space-y-6' onSubmit={handleSubmit}>
+ <Form method='post' className='space-y-6'>
<Input
name='password'
type='password'
label={t('auth.recovery.newPassword')}
hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}
- value={form.password}
- onChange={handleInput}
- error={beenSubmitted ? errors.password : null}
+ error={actionData?.fieldErrors?.password}
+ disabled={isSubmitting}
/>
<Input
name='repeat'
type='password'
label={t('auth.common.repeat')}
- value={form.repeat}
- onChange={handleInput}
- error={beenSubmitted ? errors.repeat : null}
+ error={actionData?.fieldErrors?.repeat}
+ disabled={isSubmitting}
/>
- <Button className='w-full justify-center' type='submit' loading={isLoading} primary giant>
+ <Button className='w-full justify-center' type='submit' loading={isSubmitting} primary giant>
{t('auth.recovery.save')}
</Button>
- </form>
+ </Form>
</div>
<p className='mt-10 mb-4 text-center text-sm text-gray-500 dark:text-gray-200'>
<Trans
@@ -152,4 +74,4 @@ const CreateNewPassword = () => {
)
}
-export default withAuthentication(CreateNewPassword, auth.notAuthenticated)
+export default CreateNewPassword
diff --git a/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx b/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx
index 8613c2eaa..da5813ddf 100644
--- a/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx
+++ b/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx
@@ -1,87 +1,33 @@
-import _isEmpty from 'lodash/isEmpty'
-import _keys from 'lodash/keys'
-import React, { useState, useEffect } from 'react'
+import React, { useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { Link, useNavigate } from 'react-router'
+import { Link, Form, useActionData, useNavigation, useSearchParams } from 'react-router'
import { toast } from 'sonner'
-import { forgotPassword } from '~/api'
-import { withAuthentication, auth } from '~/hoc/protected'
import { isSelfhosted, TRIAL_DAYS } from '~/lib/constants'
+import type { ForgotPasswordActionData } from '~/routes/recovery'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import routes from '~/utils/routes'
-import { isValidEmail } from '~/utils/validator'
const ForgotPassword = () => {
const { t } = useTranslation('common')
- const navigate = useNavigate()
- const [form, setForm] = useState<{
- email: string
- }>({
- email: '',
- })
- const [validated, setValidated] = useState(false)
- const [errors, setErrors] = useState<{
- email?: string
- }>({})
- const [beenSubmitted, setBeenSubmitted] = useState(false)
- const [isLoading, setIsLoading] = useState(false)
+ const navigation = useNavigation()
+ const actionData = useActionData<ForgotPasswordActionData>()
+ const [searchParams] = useSearchParams()
- const validate = () => {
- const allErrors = {} as {
- email?: string
- }
-
- if (!isValidEmail(form.email)) {
- allErrors.email = t('auth.common.badEmailError')
- }
-
- const valid = _isEmpty(_keys(allErrors))
-
- setErrors(allErrors)
- setValidated(valid)
- }
+ const isSubmitting = navigation.state === 'submitting'
useEffect(() => {
- validate()
- }, [form]) // eslint-disable-line
-
- const onSubmit = async (data: { email: string }) => {
- if (!isLoading) {
- setIsLoading(true)
-
- try {
- await forgotPassword(data)
-
- toast.success(t('auth.forgot.sent'))
- navigate(routes.main)
- } catch (reason: any) {
- toast.error(reason.toString())
- } finally {
- setIsLoading(false)
- }
+ if (searchParams.get('password_reset_sent') === 'true') {
+ toast.success(t('auth.forgot.sent'))
}
- }
-
- const handleInput = ({ target }: { target: HTMLInputElement }) => {
- const value = target.type === 'checkbox' ? target.checked : target.value
+ }, [searchParams, t])
- setForm((oldForm) => ({
- ...oldForm,
- [target.name]: value,
- }))
- }
-
- const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
- e.preventDefault()
- e.stopPropagation()
- setBeenSubmitted(true)
-
- if (validated) {
- onSubmit(form)
+ useEffect(() => {
+ if (actionData?.error) {
+ toast.error(actionData.error)
}
- }
+ }, [actionData?.error, actionData?.timestamp])
return (
<div>
@@ -93,19 +39,19 @@ const ForgotPassword = () => {
</div>
<div className='mt-10 sm:mx-auto sm:w-full sm:max-w-[480px]'>
<div className='bg-white px-6 py-12 shadow-xs ring-1 ring-gray-200 sm:rounded-lg sm:px-12 dark:bg-slate-900 dark:ring-slate-800'>
- <form className='space-y-6' onSubmit={handleSubmit}>
+ <Form method='post' className='space-y-6'>
<Input
name='email'
type='email'
label={t('auth.common.email')}
- value={form.email}
- onChange={handleInput}
- error={beenSubmitted ? errors.email : null}
+ error={actionData?.fieldErrors?.email}
+ placeholder='[email protected]'
+ disabled={isSubmitting}
/>
- <Button className='w-full justify-center' type='submit' loading={isLoading} primary giant>
+ <Button className='w-full justify-center' type='submit' loading={isSubmitting} primary giant>
{t('auth.forgot.reset')}
</Button>
- </form>
+ </Form>
</div>
{isSelfhosted ? null : (
<p className='mt-10 mb-4 text-center text-sm text-gray-500 dark:text-gray-200'>
@@ -133,4 +79,4 @@ const ForgotPassword = () => {
)
}
-export default withAuthentication(ForgotPassword, auth.notAuthenticated)
+export default ForgotPassword
diff --git a/web/app/pages/Auth/Signin/Signin.tsx b/web/app/pages/Auth/Signin/Signin.tsx
index 2538ae15f..7bf4d11cd 100644
--- a/web/app/pages/Auth/Signin/Signin.tsx
+++ b/web/app/pages/Auth/Signin/Signin.tsx
@@ -1,93 +1,90 @@
-import _isEmpty from 'lodash/isEmpty'
-import _isString from 'lodash/isString'
-import _keys from 'lodash/keys'
-import _omit from 'lodash/omit'
-import React, { useState, useEffect, memo } from 'react'
+import React, { useState, memo, useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { Link, useNavigate, useSearchParams } from 'react-router'
+import { Link, useNavigate, useSearchParams, Form, useActionData, useNavigation, useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { generateSSOAuthURL, getJWTBySSOHash, login, submit2FA } from '~/api'
import GithubAuth from '~/components/GithubAuth'
import GoogleAuth from '~/components/GoogleAuth'
import OIDCAuth from '~/components/OIDCAuth'
-import { withAuthentication, auth } from '~/hoc/protected'
+import { useAuthProxy } from '~/hooks/useAuthProxy'
import { isSelfhosted, TRIAL_DAYS } from '~/lib/constants'
import { SSOProvider } from '~/lib/models/Auth'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
+import type { LoginActionData } from '~/routes/login'
import Button from '~/ui/Button'
import Checkbox from '~/ui/Checkbox'
import Input from '~/ui/Input'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
-import { setAccessToken, removeAccessToken } from '~/utils/accessToken'
import { cn, delay, openBrowserWindow } from '~/utils/generic'
-import { setRefreshToken, removeRefreshToken } from '~/utils/refreshToken'
import routes from '~/utils/routes'
-import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS } from '~/utils/validator'
-
-interface SigninForm {
- email: string
- password: string
- dontRemember: boolean
-}
+import { MIN_PASSWORD_CHARS } from '~/utils/validator'
const HASH_CHECK_FREQUENCY = 1000
const Signin = () => {
const navigate = useNavigate()
+ const navigation = useNavigation()
+ const actionData = useActionData<LoginActionData>()
+ const twoFAFetcher = useFetcher<LoginActionData>()
const [searchParams] = useSearchParams()
const { t } = useTranslation('common')
const { theme } = useTheme()
- const [form, setForm] = useState<SigninForm>({
- email: '',
- password: '',
- dontRemember: false,
- })
- const [validated, setValidated] = useState(false)
- const [errors, setErrors] = useState<{
- email?: string
- password?: string
- }>({})
- const [beenSubmitted, setBeenSubmitted] = useState(false)
- const [isLoading, setIsLoading] = useState(false)
- const [isTwoFARequired, setIsTwoFARequired] = useState(searchParams.get('show_2fa_screen') === 'true')
+
+ const [dontRemember, setDontRemember] = useState(false)
+
+ const [isSsoLoading, setIsSsoLoading] = useState(false)
+
const [twoFACode, setTwoFACode] = useState('')
- const [twoFACodeError, setTwoFACodeError] = useState<string | null>(null)
+ // State for SSO-triggered 2FA (client-side flow)
+ const [sso2FARequired, setSso2FARequired] = useState(false)
+
+ const [clearedErrors, setClearedErrors] = useState<Set<string>>(new Set())
+
const { setUser, setTotalMonthlyEvents, setIsAuthenticated } = useAuth()
+ const { generateSSOAuthURL, getJWTBySSOHash } = useAuthProxy()
- const validate = () => {
- const allErrors = {} as {
- email?: string
- password?: string
- }
+ const isFormSubmitting = navigation.state === 'submitting'
+ const is2FALoading = twoFAFetcher.state === 'submitting'
+ const isLoading = isFormSubmitting || isSsoLoading || is2FALoading
- if (!isValidEmail(form.email)) {
- allErrors.email = t('auth.common.badEmailError')
- }
+ // 2FA is required from URL params, action data, or SSO flow
+ const isTwoFARequired =
+ searchParams.get('show_2fa_screen') === 'true' || actionData?.requires2FA === true || sso2FARequired
- if (!isValidPassword(form.password)) {
- allErrors.password = t('auth.common.xCharsError', { amount: MIN_PASSWORD_CHARS })
+ // Derive 2FA error from fetcher data
+ const twoFACodeError = twoFAFetcher.data?.fieldErrors?.twoFACode || null
+
+ useEffect(() => {
+ if (actionData?.error && !actionData?.fieldErrors) {
+ const errorMessage = Array.isArray(actionData.error) ? actionData.error[0] : actionData.error
+ toast.error(errorMessage)
}
+ }, [actionData?.error, actionData?.fieldErrors, actionData?.timestamp])
- const valid = _isEmpty(_keys(allErrors))
+ const clearFieldError = (fieldName: string) => {
+ if (actionData?.fieldErrors?.[fieldName as keyof typeof actionData.fieldErrors]) {
+ setClearedErrors((prev) => new Set(prev).add(fieldName))
+ }
+ }
- setErrors(allErrors)
- setValidated(valid)
+ const getFieldError = (fieldName: string) => {
+ if (clearedErrors.has(fieldName)) {
+ return undefined
+ }
+ return actionData?.fieldErrors?.[fieldName as keyof typeof actionData.fieldErrors]
}
- useEffect(() => {
- // eslint-disable-next-line react-hooks/set-state-in-effect -- Form validation on input change
- validate()
- }, [form]) // eslint-disable-line
+ const handleFormSubmit = () => {
+ setClearedErrors(new Set())
+ }
const handle2FAInput = (event: React.ChangeEvent<HTMLInputElement>) => {
const {
target: { value },
} = event
setTwoFACode(value)
- setTwoFACodeError(null)
}
const onSsoLogin = async (provider: SSOProvider) => {
@@ -95,10 +92,12 @@ const Signin = () => {
if (!authWindow) {
toast.error(t('apiNotifications.socialisationAuthGenericError'))
- setIsLoading(false)
+ setIsSsoLoading(false)
return
}
+ setIsSsoLoading(true)
+
try {
const {
uuid,
@@ -134,7 +133,7 @@ const Signin = () => {
if (!safeAuthUrl) {
toast.error(t('apiNotifications.socialisationAuthGenericError'))
- setIsLoading(false)
+ setIsSsoLoading(false)
authWindow.close()
return
}
@@ -148,23 +147,19 @@ const Signin = () => {
await delay(HASH_CHECK_FREQUENCY)
try {
- const { accessToken, refreshToken, user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider)
+ const { user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider, !dontRemember)
authWindow.close()
if (user.isTwoFactorAuthenticationEnabled) {
- setAccessToken(accessToken, true)
- setRefreshToken(refreshToken)
setUser(user)
- setIsTwoFARequired(true)
- setIsLoading(false)
+ setSso2FARequired(true)
+ setIsSsoLoading(false)
return
}
setUser(user)
setIsAuthenticated(true)
setTotalMonthlyEvents(totalMonthlyEvents)
- setAccessToken(accessToken, false)
- setRefreshToken(refreshToken)
// Redirect to onboarding if user hasn't completed it
if (!user.hasCompletedOnboarding) {
@@ -179,312 +174,195 @@ const Signin = () => {
}
if (authWindow.closed) {
- setIsLoading(false)
+ setIsSsoLoading(false)
return
}
}
} catch (reason) {
toast.error(typeof reason === 'string' ? reason : t('apiNotifications.socialisationGenericError'))
- setIsLoading(false)
+ setIsSsoLoading(false)
return
}
}
- const onSubmit = async (data: SigninForm) => {
- if (isLoading) {
- return
- }
-
- setIsLoading(true)
-
- try {
- const { dontRemember } = data
-
- const { user, accessToken, refreshToken, totalMonthlyEvents } = await login(_omit(data, ['dontRemember']))
-
- if (user.isTwoFactorAuthenticationEnabled) {
- setAccessToken(accessToken, true)
- setRefreshToken(refreshToken, true)
- setUser(user)
- setIsTwoFARequired(true)
- setIsLoading(false)
- return
- }
-
- setUser(user)
- setIsAuthenticated(true)
- setTotalMonthlyEvents(totalMonthlyEvents)
- setAccessToken(accessToken, dontRemember)
- setRefreshToken(refreshToken)
-
- setIsLoading(false)
-
- // Redirect to onboarding if user hasn't completed it
- if (!user.hasCompletedOnboarding) {
- navigate(routes.onboarding)
- } else {
- navigate(routes.dashboard)
- }
- } catch (reason) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- setIsLoading(false)
- }
- }
-
- const _submit2FA = async (e: React.FormEvent<HTMLFormElement>) => {
+ const _submit2FA = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
e.stopPropagation()
- if (isLoading) {
+ if (is2FALoading) {
return
}
- setIsLoading(true)
+ const formData = new FormData()
+ formData.set('intent', 'submit-2fa')
+ formData.set('twoFACode', twoFACode)
+ formData.set('dontRemember', dontRemember.toString())
- try {
- const { accessToken, refreshToken, user } = await submit2FA(twoFACode)
- removeAccessToken()
- removeRefreshToken()
- setAccessToken(accessToken)
- setRefreshToken(refreshToken)
- setUser(user)
- setIsAuthenticated(true)
- } catch (reason) {
- if (_isString(reason)) {
- toast.error(reason)
- }
- console.error(`[ERROR] Failed to authenticate with 2FA: ${reason}`)
- setTwoFACodeError(t('profileSettings.invalid2fa'))
- }
-
- setTwoFACode('')
- setIsLoading(false)
- }
-
- const handleInput = ({ target }: { target: HTMLInputElement }) => {
- setForm((oldForm) => ({
- ...oldForm,
- [target.name]: target.value,
- }))
- }
-
- const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
- e.preventDefault()
- e.stopPropagation()
- setBeenSubmitted(true)
-
- if (validated) {
- onSubmit(form)
- }
- }
-
- if (isTwoFARequired) {
- return (
- <div className='flex min-h-min-footer bg-gray-50 dark:bg-slate-900'>
- {/* Left side - 2FA Form */}
- <div className='flex w-full flex-col justify-center bg-gray-50 px-4 py-12 sm:px-6 lg:w-1/2 lg:px-12 xl:px-24 dark:bg-slate-900'>
- <div className='mx-auto w-full max-w-md'>
- <div className='mb-8'>
- <Text as='h1' size='3xl' weight='bold' className='tracking-tight'>
- {t('auth.signin.2fa')}
- </Text>
- <Text as='p' colour='muted' className='mt-2 whitespace-pre-line'>
- {t('auth.signin.2faDesc')}
- </Text>
- </div>
-
- <form onSubmit={_submit2FA}>
- <Input
- label={t('profileSettings.enter2faToDisable')}
- value={twoFACode}
- placeholder={t('auth.signin.6digitCode')}
- onChange={handle2FAInput}
- disabled={isLoading}
- error={twoFACodeError}
- />
- <div className='mt-6 flex items-center justify-between'>
- <Text as='div' size='sm' colour='muted' className='whitespace-pre-line'>
- {!isSelfhosted ? (
- <Trans
- t={t}
- i18nKey='auth.signin.2faUnavailable'
- components={{
- ctl: (
- <Link
- to={routes.contact}
- className='text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300'
- />
- ),
- }}
- />
- ) : null}
- </Text>
- <Button type='submit' loading={isLoading} primary large>
- {t('common.continue')}
- </Button>
- </div>
- </form>
- </div>
- </div>
-
- {/* Right side - Visual */}
- <div className='relative hidden overflow-hidden bg-linear-to-br from-slate-800 via-slate-900 to-slate-950 lg:flex lg:w-1/2 lg:flex-col lg:items-center lg:justify-center dark:from-slate-900 dark:via-slate-950 dark:to-black'>
- {/* Decorative gradient orbs */}
- <div className='absolute -top-24 -right-24 size-64 rounded-full bg-indigo-500/20 blur-3xl' />
- <div className='absolute -bottom-24 -left-24 size-64 rounded-full bg-slate-500/20 blur-3xl' />
- <div className='relative z-10 px-12 text-center'>
- <div className='mx-auto mb-8 flex size-20 items-center justify-center rounded-2xl bg-indigo-600/20 ring-1 ring-indigo-500/30'>
- <svg
- className='size-10 text-indigo-400'
- fill='none'
- viewBox='0 0 24 24'
- strokeWidth={1.5}
- stroke='currentColor'
- >
- <path
- strokeLinecap='round'
- strokeLinejoin='round'
- d='M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z'
- />
- </svg>
- </div>
- <Text as='h2' size='2xl' weight='bold' className='text-white'>
- {t('auth.signin.secureAuth')}
- </Text>
- <Text as='p' className='mt-3 text-slate-400'>
- {t('auth.signin.secureAuthDesc')}
- </Text>
- </div>
- </div>
- </div>
- )
+ twoFAFetcher.submit(formData, { method: 'post' })
}
return (
<div className='flex min-h-min-footer bg-gray-50 dark:bg-slate-900'>
- {/* Left side - Form */}
<div className='flex w-full flex-col justify-center bg-gray-50 px-4 py-12 sm:px-6 lg:w-3/5 lg:px-12 xl:px-24 dark:bg-slate-900'>
<div className='mx-auto w-full max-w-md'>
- {/* Header */}
- <div className='mb-8'>
- <Text as='h1' size='3xl' weight='bold' className='tracking-tight'>
- {t('auth.signin.title')}
- </Text>
- <Text as='p' colour='muted' className='mt-2'>
- {t('auth.signin.welcomeBack')}
- </Text>
- </div>
+ {isTwoFARequired ? (
+ <>
+ <div className='mb-8'>
+ <Text as='h1' size='3xl' weight='bold' className='tracking-tight'>
+ {t('auth.signin.2fa')}
+ </Text>
+ <Text as='p' colour='muted' className='mt-2 whitespace-pre-line'>
+ {t('auth.signin.2faDesc')}
+ </Text>
+ </div>
- {/* SSO Buttons */}
- <div className={cn('grid gap-3', isSelfhosted ? 'grid-cols-1' : 'grid-cols-2')}>
- {isSelfhosted ? (
- <OIDCAuth onClick={() => onSsoLogin('openid-connect')} disabled={isLoading} className='w-full' />
- ) : (
- <>
- <GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />
- <GithubAuth onClick={() => onSsoLogin('github')} disabled={isLoading} />
- </>
- )}
- </div>
+ <form onSubmit={_submit2FA}>
+ <Input
+ label={t('profileSettings.enter2faToDisable')}
+ value={twoFACode}
+ placeholder={t('auth.signin.6digitCode')}
+ onChange={handle2FAInput}
+ disabled={is2FALoading}
+ error={twoFACodeError}
+ />
+ <div className='mt-6 flex items-center justify-between'>
+ <Text as='div' size='sm' colour='muted' className='whitespace-pre-line'>
+ {!isSelfhosted ? (
+ <Trans
+ t={t}
+ i18nKey='auth.signin.2faUnavailable'
+ components={{
+ ctl: (
+ <Link
+ to={routes.contact}
+ className='text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300'
+ />
+ ),
+ }}
+ />
+ ) : null}
+ </Text>
+ <Button type='submit' loading={is2FALoading} primary large>
+ {t('common.continue')}
+ </Button>
+ </div>
+ </form>
+ </>
+ ) : (
+ <>
+ <div className='mb-8'>
+ <Text as='h1' size='3xl' weight='bold' className='tracking-tight'>
+ {t('auth.signin.title')}
+ </Text>
+ <Text as='p' colour='muted' className='mt-2'>
+ {t('auth.signin.welcomeBack')}
+ </Text>
+ </div>
- {/* Divider */}
- <div className='relative my-6'>
- <div className='absolute inset-0 flex items-center' aria-hidden='true'>
- <div className='w-full border-t border-gray-200 dark:border-gray-700' />
- </div>
- <div className='relative flex justify-center text-sm'>
- <Text as='span' colour='muted' size='sm' className='bg-gray-50 px-4 dark:bg-slate-900'>
- {t('auth.common.orContinueWith')} email
- </Text>
- </div>
- </div>
+ <div className={cn('grid gap-3', isSelfhosted ? 'grid-cols-1' : 'grid-cols-2')}>
+ {isSelfhosted ? (
+ <OIDCAuth onClick={() => onSsoLogin('openid-connect')} disabled={isLoading} className='w-full' />
+ ) : (
+ <>
+ <GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />
+ <GithubAuth onClick={() => onSsoLogin('github')} disabled={isLoading} />
+ </>
+ )}
+ </div>
- {/* Form */}
- <form className='space-y-4' onSubmit={handleSubmit}>
- <Input
- name='email'
- type='email'
- label={t('auth.common.email')}
- value={form.email}
- onChange={handleInput}
- error={beenSubmitted ? errors.email : ''}
- placeholder='[email protected]'
- />
- <Input
- name='password'
- type='password'
- label={t('auth.common.password')}
- labelCorner={
- <Link
- to={routes.reset_password}
- className='text-sm font-medium text-gray-900 underline decoration-dashed hover:decoration-solid dark:text-gray-300'
- tabIndex={-1}
- >
- {t('auth.signin.forgot')}
- </Link>
- }
- hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}
- value={form.password}
- onChange={handleInput}
- error={beenSubmitted ? errors.password : ''}
- />
-
- <div className='flex items-center justify-between'>
- <Checkbox
- checked={form.dontRemember}
- onChange={(checked) =>
- setForm((prev) => ({
- ...prev,
- dontRemember: checked,
- }))
- }
- name='dontRemember'
- label={
- <span className='flex items-center gap-1'>
- <Text size='sm'>{t('auth.common.noRemember')}</Text>
- <Tooltip text={t('auth.common.noRememberHint')} className='relative' />
- </span>
- }
- />
- </div>
+ <div className='relative my-6'>
+ <div className='absolute inset-0 flex items-center' aria-hidden='true'>
+ <div className='w-full border-t border-gray-200 dark:border-gray-700' />
+ </div>
+ <div className='relative flex justify-center text-sm'>
+ <Text as='span' colour='muted' size='sm' className='bg-gray-50 px-4 dark:bg-slate-900'>
+ {t('auth.common.orContinueWith')} email
+ </Text>
+ </div>
+ </div>
- <Button className='mt-6 w-full justify-center' type='submit' loading={isLoading} primary giant>
- {t('auth.signin.button')}
- </Button>
- </form>
-
- {/* Sign up link */}
- {!isSelfhosted ? (
- <Text as='p' size='sm' colour='muted' className='mt-6 text-center'>
- <Trans
- t={t}
- i18nKey='auth.signin.notAMember'
- components={{
- url: (
+ <Form method='post' className='space-y-4' onSubmit={handleFormSubmit}>
+ <Input
+ name='email'
+ type='email'
+ label={t('auth.common.email')}
+ error={getFieldError('email')}
+ placeholder='[email protected]'
+ disabled={isLoading}
+ onChange={() => clearFieldError('email')}
+ />
+ <Input
+ name='password'
+ type='password'
+ label={t('auth.common.password')}
+ labelCorner={
<Link
- to={routes.signup}
- className='font-medium text-gray-900 underline decoration-dashed hover:decoration-solid dark:text-gray-300'
- aria-label={t('titles.signup')}
- />
- ),
- }}
- values={{
- amount: TRIAL_DAYS,
- }}
- />
- </Text>
- ) : null}
+ to={routes.reset_password}
+ className='text-sm font-medium text-gray-900 underline decoration-dashed hover:decoration-solid dark:text-gray-300'
+ tabIndex={-1}
+ >
+ {t('auth.signin.forgot')}
+ </Link>
+ }
+ hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}
+ error={getFieldError('password')}
+ disabled={isLoading}
+ onChange={() => clearFieldError('password')}
+ />
+
+ {/* Hidden input for form submission since Headless UI Checkbox doesn't submit natively */}
+ <input type='hidden' name='dontRemember' value={dontRemember ? 'true' : 'false'} />
+
+ <div className='flex items-center justify-between'>
+ <Checkbox
+ checked={dontRemember}
+ onChange={setDontRemember}
+ disabled={isLoading}
+ label={
+ <span className='flex items-center gap-1'>
+ <Text size='sm'>{t('auth.common.noRemember')}</Text>
+ <Tooltip text={t('auth.common.noRememberHint')} className='relative' />
+ </span>
+ }
+ />
+ </div>
+
+ <Button className='mt-6 w-full justify-center' type='submit' loading={isFormSubmitting} primary giant>
+ {t('auth.signin.button')}
+ </Button>
+ </Form>
+
+ {/* Sign up link */}
+ {!isSelfhosted ? (
+ <Text as='p' size='sm' colour='muted' className='mt-6 text-center'>
+ <Trans
+ t={t}
+ i18nKey='auth.signin.notAMember'
+ components={{
+ url: (
+ <Link
+ to={routes.signup}
+ className='font-medium text-gray-900 underline decoration-dashed hover:decoration-solid dark:text-gray-300'
+ aria-label={t('titles.signup')}
+ />
+ ),
+ }}
+ values={{
+ amount: TRIAL_DAYS,
+ }}
+ />
+ </Text>
+ ) : null}
+ </>
+ )}
</div>
</div>
- {/* Right side - Visual showcase */}
<div className='relative hidden overflow-hidden bg-linear-to-br from-slate-800 via-slate-900 to-slate-950 lg:flex lg:w-2/5 lg:flex-col lg:justify-between dark:from-slate-900 dark:via-slate-950 dark:to-black'>
- {/* Decorative gradient orbs */}
<div className='absolute -top-24 -right-24 size-96 rounded-full bg-indigo-500/20 blur-3xl' />
<div className='absolute -bottom-24 -left-24 size-96 rounded-full bg-slate-500/20 blur-3xl' />
<div className='relative z-10 flex flex-1 flex-col justify-center px-10 py-10'>
- {/* Welcome message */}
<div className='mb-8'>
<Text as='h2' size='2xl' weight='bold' className='mb-2 text-white'>
{t('auth.signin.dashboardAwaits')}
@@ -494,7 +372,6 @@ const Signin = () => {
</Text>
</div>
- {/* Dashboard preview */}
<div className='relative'>
<div className='overflow-hidden rounded-xl shadow-2xl ring-1 ring-white/10'>
<img
@@ -507,7 +384,6 @@ const Signin = () => {
</div>
</div>
- {/* Testimonial */}
<div className='relative z-10 border-t border-white/10 bg-white/5 px-10 py-6 backdrop-blur-sm'>
<blockquote>
<Text as='p' size='sm' className='text-white/90'>
@@ -535,4 +411,4 @@ const Signin = () => {
)
}
-export default memo(withAuthentication(Signin, auth.notAuthenticated))
+export default memo(Signin)
diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsx
index ccc05f653..8a266e9e0 100644
--- a/web/app/pages/Auth/Signup/Signup.tsx
+++ b/web/app/pages/Auth/Signup/Signup.tsx
@@ -1,39 +1,26 @@
-import _isEmpty from 'lodash/isEmpty'
-import _keys from 'lodash/keys'
-import _size from 'lodash/size'
import { BarChart3Icon, MousePointerClickIcon, ShieldCheckIcon, SparklesIcon } from 'lucide-react'
-import React, { useState, useEffect } from 'react'
+import React, { useState, useEffect, memo } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { Link, useNavigate } from 'react-router'
+import { Link, useNavigate, Form, useActionData, useNavigation } from 'react-router'
import { toast } from 'sonner'
-import { generateSSOAuthURL, getJWTBySSOHash, signup } from '~/api'
import GithubAuth from '~/components/GithubAuth'
import GoogleAuth from '~/components/GoogleAuth'
import OIDCAuth from '~/components/OIDCAuth'
+import { useAuthProxy } from '~/hooks/useAuthProxy'
import { HAVE_I_BEEN_PWNED_URL, isSelfhosted, TRIAL_DAYS } from '~/lib/constants'
import { SSOProvider } from '~/lib/models/Auth'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
+import type { SignupActionData } from '~/routes/signup'
import Button from '~/ui/Button'
import Checkbox from '~/ui/Checkbox'
import Input from '~/ui/Input'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
-import { setAccessToken } from '~/utils/accessToken'
import { cn, delay, openBrowserWindow } from '~/utils/generic'
-import { setRefreshToken } from '~/utils/refreshToken'
import routes from '~/utils/routes'
-import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS } from '~/utils/validator'
-
-interface SignupForm {
- email: string
- password: string
- repeat: string
- tos: boolean
- dontRemember: boolean
- checkIfLeaked: boolean
-}
+import { MIN_PASSWORD_CHARS } from '~/utils/validator'
const HASH_CHECK_FREQUENCY = 1000
@@ -44,98 +31,45 @@ const featureKeys = ['realTimeAnalytics', 'eventTracking', 'privacyFirst', 'intu
const Signup = () => {
const { t } = useTranslation('common')
const { theme } = useTheme()
- const [form, setForm] = useState<SignupForm>({
- email: '',
- password: '',
- repeat: '',
- tos: false,
- dontRemember: false,
- checkIfLeaked: true,
- })
- const [validated, setValidated] = useState(false)
- const [errors, setErrors] = useState<{
- email?: string
- password?: string
- repeat?: string
- tos?: string
- }>({})
- const [beenSubmitted, setBeenSubmitted] = useState(false)
- const [isLoading, setIsLoading] = useState(false)
const navigate = useNavigate()
- const { isAuthenticated, setUser, setTotalMonthlyEvents, setIsAuthenticated } = useAuth()
-
- const validate = () => {
- const allErrors = {} as {
- email?: string
- password?: string
- repeat?: string
- tos?: string
- }
+ const navigation = useNavigation()
+ const actionData = useActionData<SignupActionData>()
- if (!isValidEmail(form.email)) {
- allErrors.email = t('auth.common.badEmailError')
- }
+ const [tos, setTos] = useState(false)
+ const [checkIfLeaked, setCheckIfLeaked] = useState(true)
- if (!isValidPassword(form.password)) {
- allErrors.password = t('auth.common.xCharsError', { amount: MIN_PASSWORD_CHARS })
- }
+ const [isSsoLoading, setIsSsoLoading] = useState(false)
- if (form.password !== form.repeat || form.repeat === '') {
- allErrors.repeat = t('auth.common.noMatchError')
- }
+ const [clearedErrors, setClearedErrors] = useState<Set<string>>(new Set())
- if (_size(form.password) > 50) {
- allErrors.password = t('auth.common.passwordTooLong', { amount: MAX_PASSWORD_CHARS })
- }
-
- if (!form.tos && !isSelfhosted) {
- allErrors.tos = t('auth.common.tosError')
- }
+ const { setUser, setTotalMonthlyEvents, setIsAuthenticated } = useAuth()
+ const { generateSSOAuthURL, getJWTBySSOHash } = useAuthProxy()
- const valid = _isEmpty(_keys(allErrors))
-
- setErrors(allErrors)
- setValidated(valid)
- }
-
- useEffect(() => {
- validate()
- }, [form]) // eslint-disable-line
+ const isFormSubmitting = navigation.state === 'submitting'
+ const isLoading = isFormSubmitting || isSsoLoading
useEffect(() => {
- if (isAuthenticated && !beenSubmitted) {
- navigate(routes.dashboard)
+ if (actionData?.error && !actionData?.fieldErrors) {
+ const errorMessage = Array.isArray(actionData.error) ? actionData.error[0] : actionData.error
+ toast.error(errorMessage)
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isAuthenticated, beenSubmitted])
+ }, [actionData?.error, actionData?.fieldErrors, actionData?.timestamp])
- const onSubmit = async (data: SignupForm) => {
- if (isLoading) {
- return
+ const clearFieldError = (fieldName: string) => {
+ if (actionData?.fieldErrors?.[fieldName as keyof typeof actionData.fieldErrors]) {
+ setClearedErrors((prev) => new Set(prev).add(fieldName))
}
+ }
- setIsLoading(true)
-
- try {
- const { dontRemember } = data
-
- const { user, accessToken, refreshToken } = await signup({
- email: data.email,
- password: data.password,
- checkIfLeaked: data.checkIfLeaked,
- })
-
- setUser(user)
- setIsAuthenticated(true)
- setAccessToken(accessToken, dontRemember)
- setRefreshToken(refreshToken)
- setIsLoading(false)
-
- navigate(routes.onboarding)
- } catch (reason) {
- toast.error((reason as { message?: string })?.message || t('apiNotifications.somethingWentWrong'))
- setIsLoading(false)
+ const getFieldError = (fieldName: string) => {
+ if (clearedErrors.has(fieldName)) {
+ return undefined
}
+ return actionData?.fieldErrors?.[fieldName as keyof typeof actionData.fieldErrors]
+ }
+
+ const handleFormSubmit = () => {
+ setClearedErrors(new Set())
}
const onSsoLogin = async (provider: SSOProvider) => {
@@ -143,10 +77,12 @@ const Signup = () => {
if (!authWindow) {
toast.error(t('apiNotifications.socialisationAuthGenericError'))
- setIsLoading(false)
+ setIsSsoLoading(false)
return
}
+ setIsSsoLoading(true)
+
try {
const { uuid, auth_url: authUrl, expires_in: expiresIn } = await generateSSOAuthURL(provider)
@@ -178,7 +114,7 @@ const Signup = () => {
if (!safeAuthUrl) {
toast.error(t('apiNotifications.socialisationAuthGenericError'))
- setIsLoading(false)
+ setIsSsoLoading(false)
authWindow.close()
return
}
@@ -192,23 +128,19 @@ const Signup = () => {
await delay(HASH_CHECK_FREQUENCY)
try {
- const { accessToken, refreshToken, user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider)
+ const { user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider, true)
authWindow.close()
if (user.isTwoFactorAuthenticationEnabled) {
- setAccessToken(accessToken, true)
- setRefreshToken(refreshToken)
setUser(user)
navigate(`${routes.signin}?show_2fa_screen=true`)
- setIsLoading(false)
+ setIsSsoLoading(false)
return
}
setUser(user)
setIsAuthenticated(true)
setTotalMonthlyEvents(totalMonthlyEvents)
- setAccessToken(accessToken, false)
- setRefreshToken(refreshToken)
// Redirect to onboarding if user hasn't completed it
if (!user.hasCompletedOnboarding) {
@@ -223,42 +155,21 @@ const Signup = () => {
}
if (authWindow.closed) {
- setIsLoading(false)
+ setIsSsoLoading(false)
return
}
}
} catch (reason) {
toast.error((reason as { message?: string })?.message || t('apiNotifications.socialisationGenericError'))
- setIsLoading(false)
+ setIsSsoLoading(false)
return
}
}
- 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)
- }
- }
-
return (
<div className='flex min-h-min-footer bg-gray-50 dark:bg-slate-900'>
- {/* Left side - Form */}
<div className='flex w-full flex-col justify-center bg-gray-50 px-4 py-12 sm:px-6 lg:w-3/5 lg:px-12 xl:px-24 dark:bg-slate-900'>
<div className='mx-auto w-full max-w-md'>
- {/* Header */}
<div className='mb-8'>
<Text as='h1' size='3xl' weight='bold' className='tracking-tight'>
{isSelfhosted
@@ -274,7 +185,6 @@ const Signup = () => {
)}
</div>
- {/* SSO Buttons */}
<div className={cn('grid gap-3', isSelfhosted ? 'grid-cols-1' : 'grid-cols-2')}>
{isSelfhosted ? (
<OIDCAuth onClick={() => onSsoLogin('openid-connect')} disabled={isLoading} className='w-full' />
@@ -286,7 +196,6 @@ const Signup = () => {
)}
</div>
- {/* Divider */}
<div className='relative my-6'>
<div className='absolute inset-0 flex items-center' aria-hidden='true'>
<div className='w-full border-t border-gray-200 dark:border-gray-700' />
@@ -298,45 +207,46 @@ const Signup = () => {
</div>
</div>
- {/* Form */}
- <form className='space-y-4' onSubmit={handleSubmit}>
+ <Form method='post' className='space-y-4' onSubmit={handleFormSubmit}>
<Input
name='email'
type='email'
label={t('auth.common.email')}
- value={form.email}
- onChange={handleInput}
- error={beenSubmitted ? errors.email : ''}
+ error={getFieldError('email')}
placeholder='[email protected]'
+ disabled={isLoading}
+ onChange={() => clearFieldError('email')}
/>
<Input
name='password'
type='password'
label={t('auth.common.password')}
hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}
- value={form.password}
- onChange={handleInput}
- error={beenSubmitted ? errors.password : ''}
+ error={getFieldError('password')}
+ disabled={isLoading}
+ onChange={() => clearFieldError('password')}
/>
<Input
name='repeat'
type='password'
label={t('auth.common.repeat')}
- value={form.repeat}
- onChange={handleInput}
- error={beenSubmitted ? errors.repeat : ''}
+ error={getFieldError('repeat')}
+ disabled={isLoading}
+ onChange={() => clearFieldError('repeat')}
/>
+ {/* Hidden fields for checkbox values since Headless UI Checkbox doesn't submit natively */}
+ <input type='hidden' name='tos' value={tos ? 'true' : 'false'} />
+ <input type='hidden' name='checkIfLeaked' value={checkIfLeaked ? 'true' : 'false'} />
+
{isSelfhosted ? null : (
<Checkbox
- checked={form.tos}
- onChange={(checked) =>
- setForm((prev) => ({
- ...prev,
- tos: checked,
- }))
- }
- name='tos'
+ checked={tos}
+ onChange={(checked) => {
+ setTos(checked)
+ clearFieldError('tos')
+ }}
+ disabled={isLoading}
label={
<Text as='span' size='sm'>
<Trans
@@ -365,20 +275,15 @@ const Signup = () => {
classes={{
hint: '!text-red-600 dark:!text-red-500',
}}
- hint={beenSubmitted ? errors.tos : ''}
+ hint={getFieldError('tos')}
/>
)}
<div className='flex items-center'>
<Checkbox
- checked={form.checkIfLeaked}
- onChange={(checked) =>
- setForm((prev) => ({
- ...prev,
- checkIfLeaked: checked,
- }))
- }
- name='checkIfLeaked'
+ checked={checkIfLeaked}
+ onChange={setCheckIfLeaked}
+ disabled={isLoading}
label={<Text size='sm'>{t('auth.common.checkLeakedPassword')}</Text>}
/>
<Tooltip
@@ -405,12 +310,11 @@ const Signup = () => {
/>
</div>
- <Button className='mt-6 w-full justify-center' type='submit' loading={isLoading} primary giant>
+ <Button className='mt-6 w-full justify-center' type='submit' loading={isFormSubmitting} primary giant>
{t('auth.signup.button')}
</Button>
- </form>
+ </Form>
- {/* Sign in link */}
<Text as='p' size='sm' colour='muted' className='mt-6 text-center'>
<Trans
t={t}
@@ -429,14 +333,11 @@ const Signup = () => {
</div>
</div>
- {/* Right side - Visual showcase */}
<div className='relative hidden overflow-hidden bg-linear-to-br from-slate-800 via-slate-900 to-slate-950 lg:flex lg:w-2/5 lg:flex-col lg:justify-between dark:from-slate-900 dark:via-slate-950 dark:to-black'>
- {/* Decorative gradient orbs */}
<div className='absolute -top-24 -right-24 size-96 rounded-full bg-indigo-500/20 blur-3xl' />
<div className='absolute -bottom-24 -left-24 size-96 rounded-full bg-slate-500/20 blur-3xl' />
<div className='relative z-10 flex flex-1 flex-col justify-center px-10 py-10'>
- {/* Features list */}
<div className='mb-8'>
<Text as='h2' size='xl' weight='bold' className='mb-4 text-white'>
{t('auth.signup.insightsInMinutes')}
@@ -463,7 +364,6 @@ const Signup = () => {
</div>
</div>
- {/* Dashboard preview */}
<div className='relative'>
<div className='overflow-hidden rounded-xl shadow-2xl ring-1 ring-white/10'>
<img
@@ -476,7 +376,6 @@ const Signup = () => {
</div>
</div>
- {/* Testimonial */}
<div className='relative z-10 border-t border-white/10 bg-white/5 px-10 py-6 backdrop-blur-sm'>
<blockquote>
<Text as='p' size='sm' className='text-white/90'>
@@ -504,4 +403,4 @@ const Signup = () => {
)
}
-export default Signup
+export default memo(Signup)
diff --git a/web/app/pages/Auth/Socialised/index.tsx b/web/app/pages/Auth/Socialised/index.tsx
index 8054b7b34..fc8a8df49 100644
--- a/web/app/pages/Auth/Socialised/index.tsx
+++ b/web/app/pages/Auth/Socialised/index.tsx
@@ -3,7 +3,7 @@ import _split from 'lodash/split'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { processSSOToken, processSSOTokenCommunityEdition } from '~/api'
+import { useAuthProxy } from '~/hooks/useAuthProxy'
import { isSelfhosted, SSO_PROVIDERS } from '~/lib/constants'
import StatusPage from '~/ui/StatusPage'
import routes from '~/utils/routes'
@@ -12,6 +12,7 @@ const Socialised = () => {
const { t } = useTranslation('common')
const [loading, setLoading] = useState(true)
const [isError, setIsError] = useState(false)
+ const { processSSOToken, processSSOTokenCommunityEdition } = useAuthProxy()
useEffect(() => {
// For some reason, Google redirects to a hash URL, let's fix it
@@ -91,7 +92,7 @@ const Socialised = () => {
} else {
processCode()
}
- }, [])
+ }, [processSSOToken, processSSOTokenCommunityEdition])
if (loading) {
return <StatusPage loading />
diff --git a/web/app/pages/Auth/VerifyEmail/index.tsx b/web/app/pages/Auth/VerifyEmail/index.tsx
deleted file mode 100644
index bca7b5dd3..000000000
--- a/web/app/pages/Auth/VerifyEmail/index.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import _isString from 'lodash/isString'
-import { useState, useEffect } from 'react'
-import { useTranslation } from 'react-i18next'
-import { useParams } from 'react-router'
-
-import { verifyEmail } from '~/api'
-import { useAuth } from '~/providers/AuthProvider'
-import StatusPage from '~/ui/StatusPage'
-import routes from '~/utils/routes'
-
-const VerifyEmail = () => {
- const { t } = useTranslation('common')
- const { id } = useParams()
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState('')
- const { mergeUser } = useAuth()
-
- useEffect(() => {
- setLoading(true)
-
- if (!_isString(id)) {
- setError(t('auth.verification.invalid'))
- setLoading(false)
- return
- }
-
- const verify = async () => {
- try {
- await verifyEmail({ id })
- mergeUser({ isActive: true })
- } catch (reason: any) {
- setError(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- } finally {
- setLoading(false)
- }
- }
-
- verify()
- }, [id]) // eslint-disable-line
-
- if (loading) {
- return <StatusPage loading />
- }
-
- if (error) {
- return (
- <StatusPage
- type='error'
- title={error}
- actions={[
- { label: t('common.dashboard'), to: routes.dashboard, primary: true },
- { label: t('notFoundPage.support'), to: routes.contact },
- ]}
- />
- )
- }
-
- return (
- <StatusPage
- type='success'
- title={t('auth.verification.success')}
- actions={[{ label: t('auth.verification.continueToOnboarding'), to: routes.onboarding, primary: true }]}
- />
- )
-}
-
-export default VerifyEmail
diff --git a/web/app/pages/Billing/index.tsx b/web/app/pages/Billing/index.tsx
index 42a7a2a0c..7f186b9dc 100644
--- a/web/app/pages/Billing/index.tsx
+++ b/web/app/pages/Billing/index.tsx
@@ -3,20 +3,20 @@ import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import utc from 'dayjs/plugin/utc'
import _round from 'lodash/round'
-import { memo, useMemo, useState, useEffect } from 'react'
+import { useMemo, useState, useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
+import { useLoaderData, useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { getPaymentMetainfo, getUsageInfo } from '~/api'
import DashboardLockedBanner from '~/components/DashboardLockedBanner'
import FAQ from '~/components/marketing/FAQ'
import BillingPricing from '~/components/pricing/BillingPricing'
-import { withAuthentication, auth } from '~/hoc/protected'
-import { isSelfhosted, PADDLE_JS_URL, PADDLE_VENDOR_ID, CONTACT_EMAIL, paddleLanguageMapping } from '~/lib/constants'
-import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
+import { PADDLE_JS_URL, PADDLE_VENDOR_ID, CONTACT_EMAIL, paddleLanguageMapping } from '~/lib/constants'
+import { DEFAULT_METAINFO } from '~/lib/models/Metainfo'
import { UsageInfo } from '~/lib/models/Usageinfo'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
+import type { BillingActionData, BillingLoaderData } from '~/routes/billing'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
@@ -26,31 +26,43 @@ import { loadScript } from '~/utils/generic'
dayjs.extend(utc)
dayjs.extend(duration)
+const DEFAULT_USAGE_INFO: UsageInfo = {
+ total: 0,
+ traffic: 0,
+ errors: 0,
+ customEvents: 0,
+ captcha: 0,
+ trafficPerc: 0,
+ errorsPerc: 0,
+ customEventsPerc: 0,
+ captchaPerc: 0,
+}
+
const Billing = () => {
- const [isCancelSubModalOpened, setIsCancelSubModalOpened] = useState(false)
+ const loaderData = useLoaderData<BillingLoaderData>()
+ const metainfoFetcher = useFetcher<BillingActionData>()
- const [metainfo, setMetainfo] = useState<Metainfo>(DEFAULT_METAINFO)
- const [lastEvent, setLastEvent] = useState<{
- event: string
- } | null>(null)
+ const [isCancelSubModalOpened, setIsCancelSubModalOpened] = useState(false)
+ const [lastEvent, setLastEvent] = useState<{ event: string } | null>(null)
const { user, isLoading: authLoading } = useAuth()
const { theme } = useTheme()
- const [usageInfo, setUsageInfo] = useState<UsageInfo>({
- total: 0,
- traffic: 0,
- errors: 0,
- customEvents: 0,
- captcha: 0,
- trafficPerc: 0,
- errorsPerc: 0,
- customEventsPerc: 0,
- captchaPerc: 0,
- })
+
+ const metainfo = useMemo(() => {
+ if (metainfoFetcher.data?.success && metainfoFetcher.data.data) {
+ return metainfoFetcher.data.data as typeof DEFAULT_METAINFO
+ }
+ return loaderData?.metainfo ?? DEFAULT_METAINFO
+ }, [loaderData?.metainfo, metainfoFetcher.data])
+
+ const usageInfo = useMemo(() => loaderData?.usageInfo ?? DEFAULT_USAGE_INFO, [loaderData?.usageInfo])
+ const isLoading = !loaderData
+
const {
t,
i18n: { language },
} = useTranslation('common')
+
const {
nextBillDate,
planCode,
@@ -69,30 +81,15 @@ const Billing = () => {
const totalUsage = maxEventsCount ? _round((usageInfo.total / maxEventsCount) * 100, 2) : 0
const remainingUsage = _round(100 - totalUsage, 2)
- const [isLoading, setIsLoading] = useState(true)
-
- useEffect(() => {
- const abortController = new AbortController()
-
- getPaymentMetainfo({ signal: abortController.signal })
- .then(setMetainfo)
- .catch(() => {})
-
- return () => abortController.abort()
- }, [])
-
// Paddle (payment processor) set-up
useEffect(() => {
loadScript(PADDLE_JS_URL)
const interval = setInterval(paddleSetup, 200)
- // prettier-ignore
function paddleSetup() {
- if (isSelfhosted) {
- clearInterval(interval)
- } else if ((window as any)?.Paddle) {
- (window as any).Paddle.Setup({
+ if ((window as any)?.Paddle) {
+ ;(window as any).Paddle.Setup({
vendor: PADDLE_VENDOR_ID,
eventCallback: setLastEvent,
})
@@ -101,32 +98,7 @@ const Billing = () => {
}
}, [])
- const loadUsageInfo = async () => {
- if (!isLoading) {
- return
- }
-
- try {
- const result = await getUsageInfo()
- setUsageInfo(result)
- } catch (reason: any) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.failedToLoadUsageInfo'))
- } finally {
- setIsLoading(false)
- }
- }
-
- useEffect(() => {
- if (authLoading) {
- return
- }
-
- loadUsageInfo()
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [authLoading])
-
- const isTrialEnded = useMemo(() => {
+ const isTrialEnded = (() => {
if (!trialEndDate) {
return false
}
@@ -136,9 +108,9 @@ const Billing = () => {
const diff = future.diff(now)
return diff < 0
- }, [trialEndDate])
+ })()
- const trialEndsOnMessage = useMemo(() => {
+ const trialEndsOnMessage = (() => {
if (!trialEndDate || !isTrial) {
return null
}
@@ -164,7 +136,7 @@ const Billing = () => {
return t('billing.trialEnds', {
date,
})
- }, [language, trialEndDate, isTrial, timeFormat, isTrialEnded, t])
+ })()
const onSubscriptionCancel = () => {
if (!subCancelURL) {
@@ -307,11 +279,11 @@ const Billing = () => {
</div>
) : null}
- {isLoading ? (
+ {isLoading || authLoading ? (
<Loader />
) : (
<div className='mt-8 flex flex-col'>
- <BillingPricing lastEvent={lastEvent} />
+ <BillingPricing lastEvent={lastEvent} metainfo={metainfo} />
<div className='mt-2 space-y-2'>
{subUpdateURL && !cancellationEffectiveDate ? (
<Button className='mr-2' onClick={onUpdatePaymentDetails} type='button' primary large>
@@ -334,7 +306,7 @@ const Billing = () => {
</h2>
<p className='mt-1 max-w-prose text-base text-gray-900 dark:text-gray-50'>{t('billing.planUsageDesc')}</p>
- {isLoading ? (
+ {isLoading || authLoading ? (
<Loader />
) : (
<div className='mt-4 text-gray-900 dark:text-gray-50'>
@@ -502,4 +474,4 @@ const Billing = () => {
)
}
-export default memo(withAuthentication(Billing, auth.authenticated))
+export default Billing
diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsx
index 70a3edc2f..5534487cf 100644
--- a/web/app/pages/Dashboard/Dashboard.tsx
+++ b/web/app/pages/Dashboard/Dashboard.tsx
@@ -4,26 +4,25 @@ import _keys from 'lodash/keys'
import _map from 'lodash/map'
import _size from 'lodash/size'
import { StretchHorizontalIcon, LayoutGridIcon, SearchIcon, XIcon, FolderPlusIcon } from 'lucide-react'
-import React, { useState, useEffect, useRef, useMemo } from 'react'
+import React, { useState, useEffect, useRef, useMemo, memo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useLoaderData, useNavigate, useSearchParams } from 'react-router'
-import { ClientOnly } from 'remix-utils/client-only'
+import { useLoaderData, useNavigate, useSearchParams, useFetcher, useNavigation, useRevalidator } from 'react-router'
import { toast } from 'sonner'
-import { getProjects, getLiveVisitors, getOverallStats, createProject } from '~/api'
import DashboardLockedBanner from '~/components/DashboardLockedBanner'
import EventsRunningOutBanner from '~/components/EventsRunningOutBanner'
-import { withAuthentication, auth } from '~/hoc/protected'
+import { useLiveVisitorsProxy, useOverallStatsProxy } from '~/hooks/useAnalyticsProxy'
import useBreakpoint from '~/hooks/useBreakpoint'
import useDebounce from '~/hooks/useDebounce'
-import { isSelfhosted, LIVE_VISITORS_UPDATE_INTERVAL, tbPeriodPairs } from '~/lib/constants'
-import { Overall, Project } from '~/lib/models/Project'
+import { isSelfhosted, LIVE_VISITORS_UPDATE_INTERVAL } from '~/lib/constants'
+import { Overall } from '~/lib/models/Project'
import { useAuth } from '~/providers/AuthProvider'
+import type { DashboardLoaderData, DashboardActionData } from '~/routes/dashboard'
import Input from '~/ui/Input'
+import LoadingBar from '~/ui/LoadingBar'
import Modal from '~/ui/Modal'
import Pagination from '~/ui/Pagination'
import Select from '~/ui/Select'
-import StatusPage from '~/ui/StatusPage'
import { Text } from '~/ui/Text'
import { setCookie } from '~/utils/cookie'
import routes from '~/utils/routes'
@@ -31,7 +30,7 @@ import routes from '~/utils/routes'
import { AddProject } from './AddProject'
import { NoProjects } from './NoProjects'
import { PeriodSelector } from './PeriodSelector'
-import { ProjectCard, ProjectCardSkeleton } from './ProjectCard'
+import { ProjectCard } from './ProjectCard'
import { SortSelector, SORT_OPTIONS } from './SortSelector'
const PAGE_SIZE_OPTIONS = [12, 24, 48, 96]
@@ -45,20 +44,25 @@ const MAX_PROJECT_NAME_LENGTH = 50
const DEFAULT_PROJECT_NAME = 'Untitled Project'
const Dashboard = () => {
- const { viewMode: defaultViewMode } = useLoaderData<any>()
- const { user, isLoading: authLoading } = useAuth()
+ const loaderData = useLoaderData<DashboardLoaderData>()
const navigate = useNavigate()
+ const navigation = useNavigation()
+ const revalidator = useRevalidator()
const [searchParams, setSearchParams] = useSearchParams()
+ const fetcher = useFetcher<DashboardActionData>()
+
+ const { user } = useAuth()
const { t } = useTranslation('common')
const [isSearchActive, setIsSearchActive] = useState(false)
const searchInputRef = useRef<HTMLInputElement>(null)
const [showActivateEmailModal, setShowActivateEmailModal] = useState(false)
- const [viewMode, setViewMode] = useState(defaultViewMode)
+ const [viewMode, setViewMode] = useState(loaderData.viewMode)
const isAboveLgBreakpoint = useBreakpoint('lg')
- const [projects, setProjects] = useState<Project[]>([])
- const [paginationTotal, setPaginationTotal] = useState(0)
+ const projects = useMemo(() => loaderData.projects?.results || [], [loaderData.projects?.results])
+ const paginationTotal = loaderData.projects?.total || 0
+
const page = useMemo(() => {
const pageParam = searchParams.get('page')
@@ -75,32 +79,32 @@ const Dashboard = () => {
return parsedPage
}, [searchParams])
- const [pageSize, setPageSize] = useState(() => {
+ const pageSize = useMemo(() => {
const pageSizeParam = searchParams.get('pageSize')
return pageSizeParam && PAGE_SIZE_OPTIONS.includes(parseInt(pageSizeParam, 10))
? parseInt(pageSizeParam, 10)
: PAGE_SIZE_OPTIONS[0]
- })
- const [isLoading, setIsLoading] = useState<boolean | null>(null)
- const [error, setError] = useState<string | null>(null)
+ }, [searchParams])
+
+ const isLoading = navigation.state === 'loading' || revalidator.state === 'loading'
const [liveStats, setLiveStats] = useState<Record<string, number>>({})
const [overallStats, setOverallStats] = useState<Overall>({})
+ const { fetchLiveVisitors } = useLiveVisitorsProxy()
+ const { fetchOverallStats } = useOverallStatsProxy()
- const [activePeriod, setActivePeriod] = useState(() => {
- const periodParam = searchParams.get('period')
- return periodParam || '7d'
- })
+ const activePeriod = useMemo(() => {
+ return searchParams.get('period') || '7d'
+ }, [searchParams])
- const [sortBy, setSortBy] = useState(() => {
+ const sortBy = useMemo(() => {
const sortParam = searchParams.get('sort')
return sortParam && Object.values(SORT_OPTIONS).includes(sortParam as any) ? sortParam : SORT_OPTIONS.ALPHA_ASC
- })
+ }, [searchParams])
// New project modal state
const [newProjectModalOpen, setNewProjectModalOpen] = useState(false)
const [newProjectName, setNewProjectName] = useState('')
const [newProjectOrganisationId, setNewProjectOrganisationId] = useState<string | undefined>(undefined)
- const [isNewProjectLoading, setIsNewProjectLoading] = useState(false)
const [newProjectError, setNewProjectError] = useState<string | null>(null)
const [newProjectBeenSubmitted, setNewProjectBeenSubmitted] = useState(false)
@@ -120,44 +124,34 @@ const Dashboard = () => {
const pageAmount = Math.ceil(paginationTotal / pageSize)
// This search represents what's inside the search input
- const [search, setSearch] = useState('')
+ const [search, setSearch] = useState(searchParams.get('search') || '')
const debouncedSearch = useDebounce(search, 500)
- // Update URL only when values are explicitly changed
const updateURL = (params: Record<string, string>) => {
const newSearchParams = new URLSearchParams(searchParams)
Object.entries(params).forEach(([key, value]) => {
- newSearchParams.set(key, value)
+ if (value) {
+ newSearchParams.set(key, value)
+ } else {
+ newSearchParams.delete(key)
+ }
})
setSearchParams(newSearchParams)
}
- const setPage = (newPage: number) => {
- const newSearchParams = new URLSearchParams(searchParams)
- newSearchParams.set('page', newPage.toString())
- setSearchParams(newSearchParams)
- }
-
const handlePageChange = (newPage: number) => {
- setPage(newPage)
updateURL({ page: newPage.toString() })
}
const handlePageSizeChange = (size: number) => {
- setPageSize(size)
- setPage(1)
updateURL({ pageSize: size.toString(), page: '1' })
}
const handlePeriodChange = (period: string) => {
- setActivePeriod(period)
- setPage(1)
updateURL({ period, page: '1' })
}
const handleSortChange = (sort: string) => {
- setSortBy(sort)
- setPage(1)
updateURL({ sort, page: '1' })
}
@@ -191,11 +185,23 @@ const Dashboard = () => {
return { errors, valid: _isEmpty(_keys(errors)) }
}
- const onCreateProject = async () => {
- if (isNewProjectLoading) {
- return
+ // Handle fetcher responses for create project
+ useEffect(() => {
+ if (fetcher.data?.success && fetcher.data?.intent === 'create-project') {
+ refetchProjects()
+ toast.success(t('project.settings.created'))
+ closeNewProjectModal()
+ } else if (fetcher.data?.error && fetcher.data?.intent === 'create-project') {
+ setNewProjectError(fetcher.data.error)
+ toast.error(fetcher.data.error)
+ } else if (fetcher.data?.fieldErrors?.name && fetcher.data?.intent === 'create-project') {
+ setNewProjectError(fetcher.data.fieldErrors.name)
}
+ }, [fetcher.data, t]) // eslint-disable-line react-hooks/exhaustive-deps
+
+ const isNewProjectLoading = fetcher.state === 'submitting'
+ const onCreateProject = () => {
setNewProjectBeenSubmitted(true)
const { errors, valid } = validateProjectName()
@@ -204,33 +210,13 @@ const Dashboard = () => {
return
}
- setIsNewProjectLoading(true)
-
- try {
- await createProject({
- name: newProjectName || DEFAULT_PROJECT_NAME,
- organisationId: newProjectOrganisationId,
- })
-
- await refetchProjects()
-
- toast.success(t('project.settings.created'))
- closeNewProjectModal()
- } catch (reason: unknown) {
- console.error('[ERROR] Error while creating project:', reason)
-
- const normalizedMessage =
- typeof reason === 'string'
- ? reason
- : (reason as any)?.response?.data?.message ||
- (reason as any)?.message ||
- t('apiNotifications.somethingWentWrong')
-
- setNewProjectError(normalizedMessage)
- toast.error(normalizedMessage)
- } finally {
- setIsNewProjectLoading(false)
+ const formData = new FormData()
+ formData.set('intent', 'create-project')
+ formData.set('name', newProjectName || DEFAULT_PROJECT_NAME)
+ if (newProjectOrganisationId) {
+ formData.set('organisationId', newProjectOrganisationId)
}
+ fetcher.submit(formData, { method: 'post' })
}
const closeNewProjectModal = () => {
@@ -245,25 +231,8 @@ const Dashboard = () => {
setNewProjectBeenSubmitted(false)
}
- const refetchProjects = async () => {
- await loadProjects(pageSize, (page - 1) * pageSize, debouncedSearch, activePeriod, sortBy)
- }
-
- const loadProjects = async (take: number, skip: number, search?: string, period?: string, sort?: string) => {
- if (isLoading) {
- return
- }
- setIsLoading(true)
-
- try {
- const result = await getProjects(take, skip, search, period, sort)
- setProjects(result.results)
- setPaginationTotal(result.total)
- } catch (reason: any) {
- setError(reason)
- } finally {
- setIsLoading(false)
- }
+ const refetchProjects = () => {
+ revalidator.revalidate()
}
// Redirect to onboarding if user hasn't completed it
@@ -274,15 +243,14 @@ const Dashboard = () => {
}
}, [user, navigate])
+ // Update URL when debounced search changes
useEffect(() => {
- if (authLoading) {
- return
+ const currentSearch = searchParams.get('search') || ''
+ if (debouncedSearch !== currentSearch) {
+ updateURL({ search: debouncedSearch, page: '1' })
}
-
- loadProjects(pageSize, (page - 1) * pageSize, debouncedSearch, activePeriod, sortBy)
-
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [page, pageSize, debouncedSearch, activePeriod, authLoading, sortBy])
+ }, [debouncedSearch])
// Set up interval for live visitors
useEffect(() => {
@@ -291,60 +259,43 @@ const Dashboard = () => {
try {
const projectIds = projects.map((p) => p.id)
- const stats = await getLiveVisitors(projectIds)
- setLiveStats(stats)
+ const stats = await fetchLiveVisitors(projectIds)
+ if (stats) {
+ setLiveStats(stats)
+ }
} catch (reason) {
console.error('Failed to fetch live visitors:', reason)
}
}
- const updateOverallStats = async (projectIds: string[]) => {
- if (!projectIds.length) return
+ updateLiveVisitors()
+
+ const interval = setInterval(updateLiveVisitors, LIVE_VISITORS_UPDATE_INTERVAL)
+
+ return () => clearInterval(interval)
+ }, [projects, fetchLiveVisitors]) // Reset interval when projects change
+
+ // Fetch overall stats when projects or period changes
+ useEffect(() => {
+ const updateOverallStats = async () => {
+ if (!projects.length) return
try {
- const timeBucket = tbPeriodPairs(t).find((p) => p.period === activePeriod)?.tbs[0] || ''
- const stats = await getOverallStats(
- projectIds,
- timeBucket,
- activePeriod,
- '',
- '',
- 'Etc/GMT',
- '',
- undefined,
- true,
- )
- setOverallStats((prev) => ({ ...prev, ...stats }))
+ const projectIds = projects.map((p) => p.id)
+ const stats = await fetchOverallStats(projectIds, {
+ period: activePeriod,
+ timezone: user?.timezone || 'UTC',
+ })
+ if (stats) {
+ setOverallStats(stats)
+ }
} catch (reason) {
console.error('Failed to fetch overall stats:', reason)
}
}
- const updateAllOverallStats = async () => {
- await updateOverallStats(projects.map((p) => p.id))
- }
-
- updateLiveVisitors()
- updateAllOverallStats()
-
- const interval = setInterval(updateLiveVisitors, LIVE_VISITORS_UPDATE_INTERVAL)
-
- return () => clearInterval(interval)
- }, [projects, activePeriod, t]) // Reset interval when projects change
-
- if (error && isLoading === false) {
- return (
- <StatusPage
- type='error'
- title={t('apiNotifications.somethingWentWrong')}
- description={t('apiNotifications.errorCode', { error })}
- actions={[
- { label: t('dashboard.reloadPage'), onClick: () => window.location.reload(), primary: true },
- { label: t('notFoundPage.support'), to: routes.contact },
- ]}
- />
- )
- }
+ updateOverallStats()
+ }, [projects, activePeriod, user?.timezone, fetchOverallStats])
const onSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearch(e.target.value)
@@ -424,13 +375,9 @@ const Dashboard = () => {
<PeriodSelector
activePeriod={activePeriod}
setActivePeriod={handlePeriodChange}
- isLoading={isLoading === null || isLoading}
- />
- <SortSelector
- activeSort={sortBy}
- setActiveSort={handleSortChange}
- isLoading={isLoading === null || isLoading}
+ isLoading={isLoading}
/>
+ <SortSelector activeSort={sortBy} setActiveSort={handleSortChange} isLoading={isLoading} />
<div className='hidden lg:block'>
{viewMode === DASHBOARD_VIEW.GRID ? (
<button
@@ -488,48 +435,31 @@ const Dashboard = () => {
</div>
</div>
) : null}
- {isLoading || isLoading === null ? (
- <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
- <ProjectCardSkeleton viewMode={_viewMode} />
- </div>
+ {isLoading && !_isEmpty(projects) ? <LoadingBar /> : null}
+ {_isEmpty(projects) ? (
+ <NoProjects search={debouncedSearch} onClick={onNewProject} />
) : (
- <ClientOnly
- fallback={
- <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
- <ProjectCardSkeleton viewMode={_viewMode} />
- </div>
- }
- >
- {() => (
- <>
- {_isEmpty(projects) ? (
- <NoProjects search={debouncedSearch} onClick={onNewProject} />
- ) : (
- <div
- className={cx(
- 'grid gap-3',
- _viewMode === DASHBOARD_VIEW.GRID ? 'grid-cols-1 lg:grid-cols-3' : 'grid-cols-1',
- )}
- >
- {_map(projects, (project) => (
- <ProjectCard
- key={`${project.id}-${project.name}`}
- project={project}
- live={liveStats[project.id] ?? (_isEmpty(liveStats) ? null : 'N/A')}
- overallStats={overallStats[project.id]}
- activePeriod={activePeriod}
- viewMode={_viewMode}
- refetchProjects={refetchProjects}
- />
- ))}
- {_size(projects) % 12 !== 0 ? (
- <AddProject sitesCount={_size(projects)} onClick={onNewProject} viewMode={_viewMode} />
- ) : null}
- </div>
- )}
- </>
+ <div
+ className={cx(
+ 'grid gap-3',
+ _viewMode === DASHBOARD_VIEW.GRID ? 'grid-cols-1 lg:grid-cols-3' : 'grid-cols-1',
)}
- </ClientOnly>
+ >
+ {_map(projects, (project) => (
+ <ProjectCard
+ key={`${project.id}-${project.name}`}
+ project={project}
+ live={liveStats[project.id] ?? (_isEmpty(liveStats) ? null : 'N/A')}
+ overallStats={overallStats[project.id]}
+ activePeriod={activePeriod}
+ viewMode={_viewMode}
+ refetchProjects={refetchProjects}
+ />
+ ))}
+ {_size(projects) % 12 !== 0 ? (
+ <AddProject sitesCount={_size(projects)} onClick={onNewProject} viewMode={_viewMode} />
+ ) : null}
+ </div>
)}
{paginationTotal > PAGE_SIZE_OPTIONS[0] ? (
<Pagination
@@ -605,4 +535,4 @@ const Dashboard = () => {
)
}
-export default withAuthentication(Dashboard, auth.authenticated)
+export default memo(Dashboard)
diff --git a/web/app/pages/Dashboard/ProjectCard.tsx b/web/app/pages/Dashboard/ProjectCard.tsx
index 81d367a10..4efe8c80e 100644
--- a/web/app/pages/Dashboard/ProjectCard.tsx
+++ b/web/app/pages/Dashboard/ProjectCard.tsx
@@ -1,18 +1,17 @@
import cx from 'clsx'
import _find from 'lodash/find'
import _isNumber from 'lodash/isNumber'
-import _map from 'lodash/map'
import _replace from 'lodash/replace'
import _size from 'lodash/size'
import { Settings2Icon, PinIcon, ChevronUpIcon, ChevronDownIcon } from 'lucide-react'
import React, { useState, useMemo, useCallback, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link } from 'react-router'
+import { Link, useFetcher, useNavigate } from 'react-router'
import { toast } from 'sonner'
-import { acceptProjectShare, pinProject, unpinProject } from '~/api'
import { OverallObject, Project } from '~/lib/models/Project'
import { useAuth } from '~/providers/AuthProvider'
+import type { DashboardActionData } from '~/routes/dashboard'
import { Badge, BadgeProps } from '~/ui/Badge'
import Spin from '~/ui/icons/Spin'
import Modal from '~/ui/Modal'
@@ -25,13 +24,17 @@ import Sparkline from './Sparkline'
// Detect if device supports hover (i.e., not a touch-only device)
const useIsTouchDevice = () => {
- const [isTouchDevice, setIsTouchDevice] = useState(() => {
- if (typeof window === 'undefined') return false
- return window.matchMedia('(hover: none)').matches
- })
+ // Important for SSR hydration: first client render must match server output.
+ const [isTouchDevice, setIsTouchDevice] = useState(false)
useEffect(() => {
+ if (typeof window === 'undefined') {
+ return
+ }
+
const mediaQuery = window.matchMedia('(hover: none)')
+ queueMicrotask(() => setIsTouchDevice(mediaQuery.matches))
+
const handler = (e: MediaQueryListEvent) => setIsTouchDevice(e.matches)
mediaQuery.addEventListener('change', handler)
return () => mediaQuery.removeEventListener('change', handler)
@@ -46,7 +49,7 @@ interface ProjectCardProps {
project: Project
activePeriod: string
viewMode: 'grid' | 'list'
- refetchProjects: () => Promise<void>
+ refetchProjects: () => void
}
interface MiniCardProps {
@@ -123,6 +126,8 @@ export const ProjectCard = ({
}: ProjectCardProps) => {
const { t } = useTranslation('common')
const [showInviteModal, setShowInviteModal] = useState(false)
+ const fetcher = useFetcher<DashboardActionData>()
+ const navigate = useNavigate()
const { user, mergeUser } = useAuth()
const isTouchDevice = useIsTouchDevice()
@@ -146,46 +151,78 @@ export const ProjectCard = ({
} = project
const faviconHost = useMemo(() => getFaviconHost(websiteUrl || null), [websiteUrl])
- const [isPinning, setIsPinning] = useState(false)
const [localIsPinned, setLocalIsPinned] = useState(isPinned)
+ const isPinning =
+ (fetcher.state === 'submitting' || fetcher.state === 'loading') &&
+ (fetcher.formData?.get('intent') === 'pin-project' || fetcher.formData?.get('intent') === 'unpin-project')
+
+ const isAccepting =
+ (fetcher.state === 'submitting' || fetcher.state === 'loading') &&
+ fetcher.formData?.get('intent') === 'accept-project-share'
+
// Sync local state with prop
useEffect(() => {
setLocalIsPinned(isPinned)
}, [isPinned])
+ // Handle fetcher responses
+ useEffect(() => {
+ if (!fetcher.data) return
+
+ // Guard: only process responses for this specific project card
+ const submittedProjectId = fetcher.formData?.get('projectId')
+ const submittedShareId = fetcher.formData?.get('shareId')
+ const isForThisCard = submittedProjectId === id || submittedShareId === shareId
+ if (!isForThisCard) return
+
+ if (fetcher.data.success) {
+ const { intent } = fetcher.data
+
+ if (intent === 'pin-project') {
+ toast.success(t('dashboard.pinned'))
+ refetchProjects()
+ } else if (intent === 'unpin-project') {
+ toast.success(t('dashboard.unpinned'))
+ refetchProjects()
+ } else if (intent === 'accept-project-share') {
+ mergeUser({
+ sharedProjects: user?.sharedProjects?.map((item) => {
+ if (item.id === shareId) {
+ return { ...item, isAccessConfirmed: true }
+ }
+ return item
+ }),
+ })
+ refetchProjects()
+ toast.success(t('apiNotifications.acceptInvitation'))
+ }
+ } else if (fetcher.data.error) {
+ // Revert optimistic update on error
+ if (fetcher.data.intent === 'pin-project' || fetcher.data.intent === 'unpin-project') {
+ setLocalIsPinned(isPinned)
+ }
+ toast.error(fetcher.data.error)
+ }
+ }, [fetcher.data, fetcher.formData, isPinned, shareId, user, mergeUser, refetchProjects, t, id])
+
const handlePinToggle = useCallback(
- async (e: React.MouseEvent) => {
+ (e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
if (isPinning) return
- setIsPinning(true)
// Optimistically update local state
const newPinnedState = !localIsPinned
setLocalIsPinned(newPinnedState)
- try {
- if (!newPinnedState) {
- await unpinProject(id)
- toast.success(t('dashboard.unpinned'))
- } else {
- await pinProject(id)
- toast.success(t('dashboard.pinned'))
- }
- // Silently refetch projects in background - don't await
- refetchProjects()
- } catch (reason: any) {
- // Revert on error
- setLocalIsPinned(!newPinnedState)
- console.error('[ERROR] Error while toggling pin:', reason)
- toast.error(t('apiNotifications.somethingWentWrong'))
- } finally {
- setIsPinning(false)
- }
+ const formData = new FormData()
+ formData.set('intent', newPinnedState ? 'pin-project' : 'unpin-project')
+ formData.set('projectId', id)
+ fetcher.submit(formData, { method: 'post' })
},
- [id, localIsPinned, isPinning, refetchProjects, t],
+ [id, localIsPinned, isPinning, fetcher],
)
const badges = useMemo(() => {
@@ -224,31 +261,20 @@ export const ProjectCard = ({
return list
}, [t, active, isTransferring, isPublic, organisation, share, project.isAccessConfirmed, project.role, shareId])
- const onAccept = async () => {
- try {
- if (!shareId) {
- throw new Error('Project share not found')
- }
-
- await acceptProjectShare(shareId)
-
- mergeUser({
- sharedProjects: user?.sharedProjects?.map((item) => {
- if (item.id === shareId) {
- return { ...item, isAccessConfirmed: true }
- }
-
- return item
- }),
- })
-
- await refetchProjects()
+ const onAccept = () => {
+ if (fetcher.state !== 'idle') {
+ return
+ }
- toast.success(t('apiNotifications.acceptInvitation'))
- } catch (reason: any) {
- console.error(`[ERROR] Error while accepting project invitation: ${reason}`)
+ if (!shareId) {
toast.error(t('apiNotifications.acceptInvitationError'))
+ return
}
+
+ const formData = new FormData()
+ formData.set('intent', 'accept-project-share')
+ formData.set('shareId', shareId)
+ fetcher.submit(formData, { method: 'post' })
}
const onElementClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
@@ -320,20 +346,21 @@ export const ProjectCard = ({
disabled={isPinning}
aria-label={localIsPinned ? t('dashboard.unpin') : t('dashboard.pin')}
>
- <PinIcon
- className={cx('size-5 transition-transform', localIsPinned && 'rotate-[30deg]')}
- strokeWidth={1.5}
- />
+ <PinIcon className={cx('size-5 transition-transform', localIsPinned && 'rotate-30')} strokeWidth={1.5} />
</button>
{project.isAccessConfirmed && role !== 'viewer' ? (
- <Link
+ <button
+ type='button'
className='rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 dark:hover:border-slate-700/80 dark:hover:bg-slate-800 dark:hover:text-slate-300'
- onClick={(e) => e.stopPropagation()}
- to={_replace(routes.project_settings, ':id', id)}
+ onClick={(e) => {
+ e.preventDefault()
+ e.stopPropagation()
+ navigate(_replace(routes.project_settings, ':id', id))
+ }}
aria-label={`${t('project.settings.settings')} ${name}`}
>
<Settings2Icon className='size-5' strokeWidth={1.5} />
- </Link>
+ </button>
) : null}
</div>
</div>
@@ -372,6 +399,7 @@ export const ProjectCard = ({
onAccept()
}}
submitText={t('common.accept')}
+ submitDisabled={isAccepting}
type='confirmed'
closeText={t('common.cancel')}
title={t('dashboard.invitationFor', { project: name })}
@@ -382,44 +410,3 @@ export const ProjectCard = ({
</Link>
)
}
-
-interface ProjectCardSkeletonProps {
- viewMode: 'grid' | 'list'
-}
-
-export const ProjectCardSkeleton = ({ viewMode }: ProjectCardSkeletonProps) => {
- return (
- <div
- className={cx(
- 'grid gap-x-6 gap-y-3',
- viewMode === 'grid' ? 'grid-cols-1 lg:grid-cols-3 lg:gap-y-6' : 'grid-cols-1 gap-y-3',
- )}
- >
- {_map(Array(viewMode === 'grid' ? 12 : 8), (_, index) => (
- <div
- key={index}
- className={cx(
- 'animate-pulse cursor-wait overflow-hidden rounded-xl border border-gray-200 bg-gray-50 dark:border-slate-800/25 dark:bg-slate-800',
- viewMode === 'list' ? 'flex items-center justify-between px-6 py-4' : 'min-h-[153.1px]',
- )}
- >
- <div className={cx('flex flex-col', viewMode === 'list' ? 'flex-1' : 'px-4 py-4')}>
- <div className={cx('flex items-center', viewMode === 'grid' ? 'justify-between' : 'justify-start gap-1')}>
- <div className='h-6 w-3/4 max-w-80 rounded-sm bg-gray-200 dark:bg-slate-700' />
- <div className='size-6 rounded-[3px] bg-gray-200 dark:bg-slate-700' />
- </div>
- <div className='mt-1 flex shrink-0 flex-wrap gap-2'>
- <div className='h-6 w-16 rounded-sm bg-gray-200 dark:bg-slate-700' />
- <div className='h-6 w-16 rounded-sm bg-gray-200 dark:bg-slate-700' />
- <div className='h-6 w-16 rounded-sm bg-gray-200 dark:bg-slate-700' />
- </div>
- </div>
- <div className={cx('flex shrink-0 gap-5', viewMode === 'list' ? 'ml-4' : 'mt-[1.375rem] px-4 pb-4')}>
- <div className='h-10 w-24 rounded-sm bg-gray-200 dark:bg-slate-700' />
- <div className='h-10 w-24 rounded-sm bg-gray-200 dark:bg-slate-700' />
- </div>
- </div>
- ))}
- </div>
- )
-}
diff --git a/web/app/pages/Onboarding/Onboarding.tsx b/web/app/pages/Onboarding/Onboarding.tsx
index 4b2edaed1..df9dfee9f 100644
--- a/web/app/pages/Onboarding/Onboarding.tsx
+++ b/web/app/pages/Onboarding/Onboarding.tsx
@@ -2,17 +2,17 @@ import { EnvelopeIcon } from '@heroicons/react/24/outline'
import { CheckCircleIcon as CheckCircleIconSolid } from '@heroicons/react/24/solid'
import type { TFunction } from 'i18next'
import { ChevronRightIcon, LaptopMinimalIcon, RocketIcon, CodeIcon, MailCheckIcon, SparklesIcon } from 'lucide-react'
-import { useState, useEffect, useMemo } from 'react'
+import { useState, useEffect, useMemo, useRef } from 'react'
import { Trans, useTranslation } from 'react-i18next'
-import { Link, useNavigate } from 'react-router'
+import { Link, useNavigate, useFetcher, useLoaderData } from 'react-router'
import { toast } from 'sonner'
-import { updateOnboardingStep, completeOnboarding, createProject, authMe, getProjects, deleteUser } from '~/api'
import { CONTACT_US_URL } from '~/components/Footer'
-import { withAuthentication, auth } from '~/hoc/protected'
+import { useAuthProxy } from '~/hooks/useAuthProxy'
import { DOCS_URL, INTEGRATIONS_URL, isSelfhosted } from '~/lib/constants'
import { getSnippet } from '~/modals/TrackingSnippet'
import { useAuth } from '~/providers/AuthProvider'
+import type { OnboardingActionData, OnboardingLoaderData } from '~/routes/onboarding'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import PulsatingCircle from '~/ui/icons/PulsatingCircle'
@@ -20,10 +20,8 @@ import Input from '~/ui/Input'
import Loader from '~/ui/Loader'
import { Text } from '~/ui/Text'
import Textarea from '~/ui/Textarea'
-import { removeAccessToken } from '~/utils/accessToken'
import { trackCustom } from '~/utils/analytics'
import { cn } from '~/utils/generic'
-import { removeRefreshToken } from '~/utils/refreshToken'
import routes from '~/utils/routes'
const MAX_PROJECT_NAME_LENGTH = 50
@@ -70,13 +68,16 @@ interface Project {
const Onboarding = () => {
const { t } = useTranslation('common')
+ const loaderData = useLoaderData<OnboardingLoaderData>()
const { user, loadUser, logout } = useAuth()
+ const { authMe } = useAuthProxy()
const navigate = useNavigate()
+ const fetcher = useFetcher<OnboardingActionData>()
+ const lastHandledFetcherDataRef = useRef<OnboardingActionData | null>(null)
const [currentStep, setCurrentStep] = useState(0)
- const [isLoading, setIsLoading] = useState(false)
const [projectName, setProjectName] = useState('')
- const [project, setProject] = useState<Project | null>(null)
+ const [project, setProject] = useState<Project | null>(loaderData.project)
const [isWaitingForEvents, setIsWaitingForEvents] = useState(false)
const [hasEvents, setHasEvents] = useState(false)
@@ -84,49 +85,73 @@ const Onboarding = () => {
name?: string
}>({})
+ const isLoading = fetcher.state === 'submitting' || fetcher.state === 'loading'
+
+ useEffect(() => {
+ if (!fetcher.data) return
+ if (lastHandledFetcherDataRef.current === fetcher.data) return
+ lastHandledFetcherDataRef.current = fetcher.data
+
+ if (fetcher.data?.success) {
+ const { intent, project: newProject } = fetcher.data
+
+ if (intent === 'create-project' && newProject) {
+ setTimeout(() => setProject(newProject), 0)
+ // Update the step after project creation
+ const stepFormData = new FormData()
+ stepFormData.set('intent', 'update-step')
+ stepFormData.set('step', 'setup_tracking')
+ fetcher.submit(stepFormData, { method: 'post' })
+ setTimeout(() => setCurrentStep(2), 0)
+ } else if (intent === 'update-step') {
+ loadUser()
+ } else if (intent === 'complete-onboarding') {
+ loadUser()
+ navigate(routes.dashboard)
+ } else if (intent === 'delete-account') {
+ logout()
+ navigate(routes.main)
+ }
+ } else if (fetcher.data?.error) {
+ toast.error(fetcher.data.error)
+ } else if (fetcher.data?.fieldErrors?.name) {
+ setTimeout(() => setNewProjectErrors({ name: fetcher.data!.fieldErrors!.name }), 0)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetcher.data, fetcher.submit, loadUser, logout, navigate])
+
useEffect(() => {
if (user?.hasCompletedOnboarding) {
navigate(routes.dashboard)
return
}
- const determineCurrentStep = async () => {
- if (!user?.isActive && !isSelfhosted) {
- setCurrentStep(0)
- return
- }
+ if (!user?.isActive && !isSelfhosted) {
+ setTimeout(() => setCurrentStep(0), 0)
+ return
+ }
- if (!user?.onboardingStep) {
- setCurrentStep(1)
- return
- }
+ if (!user?.onboardingStep) {
+ setTimeout(() => setCurrentStep(1), 0)
+ return
+ }
- switch (user.onboardingStep) {
- case 'create_project':
- setCurrentStep(1)
- break
- case 'setup_tracking':
- setCurrentStep(2)
- try {
- const projectsData = await getProjects(1, 0)
- if (projectsData.results.length > 0) {
- setProject(projectsData.results[0])
- setCurrentStep(2)
- }
- } catch (reason) {
- console.error('Failed to get projects:', reason)
- }
- break
- case 'waiting_for_events':
+ switch (user.onboardingStep) {
+ case 'create_project':
+ setTimeout(() => setCurrentStep(1), 0)
+ break
+ case 'setup_tracking':
+ setTimeout(() => setCurrentStep(2), 0)
+ break
+ case 'waiting_for_events':
+ setTimeout(() => {
setCurrentStep(3)
setIsWaitingForEvents(true)
- break
- default:
- setCurrentStep(1)
- }
+ }, 0)
+ break
+ default:
+ setTimeout(() => setCurrentStep(1), 0)
}
-
- determineCurrentStep()
}, [user, navigate])
useEffect(() => {
@@ -146,21 +171,23 @@ const Onboarding = () => {
const interval = setInterval(checkForEvents, 3000)
return () => clearInterval(interval)
- }, [isWaitingForEvents, project])
-
- const updateUserStep = async (step: string) => {
- try {
- await updateOnboardingStep(step)
- await loadUser()
- } catch (reason) {
- console.error('Failed to update onboarding step:', reason)
- }
+ }, [isWaitingForEvents, project, authMe])
+
+ const updateUserStep = (step: string) => {
+ if (fetcher.state !== 'idle') return
+
+ const formData = new FormData()
+ formData.set('intent', 'update-step')
+ formData.set('step', step)
+ fetcher.submit(formData, { method: 'post' })
}
- const handleCreateProject = async (e?: React.FormEvent<HTMLFormElement>) => {
+ const handleCreateProject = (e?: React.FormEvent<HTMLFormElement>) => {
e?.preventDefault()
e?.stopPropagation()
+ if (fetcher.state !== 'idle') return
+
const trimmedName = projectName.trim()
if (!trimmedName) {
@@ -173,36 +200,29 @@ const Onboarding = () => {
return
}
- setIsLoading(true)
- try {
- const newProject = await createProject({
- name: trimmedName,
- })
-
- setProject(newProject)
- await updateUserStep('setup_tracking')
- setCurrentStep(2)
- } catch (reason) {
- toast.error(typeof reason === 'string' ? reason : 'Failed to create project')
- } finally {
- setIsLoading(false)
- }
+ setNewProjectErrors({})
+ const formData = new FormData()
+ formData.set('intent', 'create-project')
+ formData.set('name', trimmedName)
+ fetcher.submit(formData, { method: 'post' })
}
- const handleCompleteOnboarding = async (skipped: boolean) => {
- try {
- await completeOnboarding()
- await loadUser()
+ const handleCompleteOnboarding = (skipped: boolean) => {
+ if (fetcher.state !== 'idle') return
- trackCustom('ONBOARDING_COMPLETED', {
- skipped,
- })
+ trackCustom('ONBOARDING_COMPLETED', { skipped })
- navigate(routes.dashboard)
- } catch (reason) {
- console.error('Failed to complete onboarding:', reason)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- }
+ const formData = new FormData()
+ formData.set('intent', 'complete-onboarding')
+ fetcher.submit(formData, { method: 'post' })
+ }
+
+ const handleDeleteAccount = () => {
+ if (fetcher.state !== 'idle') return
+
+ const formData = new FormData()
+ formData.set('intent', 'delete-account')
+ fetcher.submit(formData, { method: 'post' })
}
const steps = useMemo(() => {
@@ -379,19 +399,7 @@ const Onboarding = () => {
tabIndex={0}
role='button'
className='cursor-pointer font-medium text-indigo-600 hover:underline dark:text-indigo-400'
- onClick={async () => {
- try {
- await deleteUser()
- // Clear tokens synchronously before React state updates trigger redirects
- removeAccessToken()
- removeRefreshToken()
- logout()
- navigate(routes.signup)
- } catch (error) {
- console.error('Failed to delete account:', error)
- toast.error(t('apiNotifications.somethingWentWrong'))
- }
- }}
+ onClick={handleDeleteAccount}
/>
),
}}
@@ -649,4 +657,4 @@ const Onboarding = () => {
)
}
-export default withAuthentication(Onboarding, auth.authenticated)
+export default Onboarding
diff --git a/web/app/pages/OpenStartup/index.tsx b/web/app/pages/OpenStartup/index.tsx
index 4c54c6bc2..06c71e57d 100644
--- a/web/app/pages/OpenStartup/index.tsx
+++ b/web/app/pages/OpenStartup/index.tsx
@@ -1,10 +1,9 @@
/* eslint-disable no-useless-escape */
import billboard, { bar, line } from 'billboard.js'
-import { useEffect, useState } from 'react'
+import { useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
import { Link } from 'react-router'
-import { getGeneralStats } from '~/api'
import { LIVE_DEMO_URL } from '~/lib/constants'
import { Stats } from '~/lib/models/Stats'
import { nFormatterSeparated } from '~/utils/generic'
@@ -384,19 +383,18 @@ const getSettings = () => {
}
}
-const OpenStartup = () => {
+interface OpenStartupProps {
+ stats: Stats | null
+}
+
+const OpenStartup = ({ stats }: OpenStartupProps) => {
const { t }: any = useTranslation('common')
- const [stats, setStats] = useState<Stats>({} as Stats)
- const events = nFormatterSeparated(Number(stats.events), 1)
- const users = nFormatterSeparated(Number(stats.users), 1)
- const websites = nFormatterSeparated(Number(stats.projects), 1)
+ const events = nFormatterSeparated(Number(stats?.events || 0), 1)
+ const users = nFormatterSeparated(Number(stats?.users || 0), 1)
+ const websites = nFormatterSeparated(Number(stats?.projects || 0), 1)
useEffect(() => {
- getGeneralStats()
- .then((stats) => setStats(stats))
- .catch(console.error)
-
const bbSettings = getSettings()
// @ts-expect-error
diff --git a/web/app/pages/Organisations/OrganisationCard.tsx b/web/app/pages/Organisations/OrganisationCard.tsx
index b0ce21ca4..d338748ad 100644
--- a/web/app/pages/Organisations/OrganisationCard.tsx
+++ b/web/app/pages/Organisations/OrganisationCard.tsx
@@ -4,14 +4,13 @@ import _map from 'lodash/map'
import _replace from 'lodash/replace'
import _size from 'lodash/size'
import { Settings2Icon } from 'lucide-react'
-import React, { useState, useMemo } from 'react'
+import React, { useState, useMemo, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link } from 'react-router'
-import { toast } from 'sonner'
+import { Link, useFetcher } from 'react-router'
-import { acceptOrganisationInvitation } from '~/api'
import { DetailedOrganisation } from '~/lib/models/Organisation'
import { useAuth } from '~/providers/AuthProvider'
+import type { OrganisationsActionData } from '~/routes/organisations._index'
import { Badge, BadgeProps } from '~/ui/Badge'
import Modal from '~/ui/Modal'
import { Text } from '~/ui/Text'
@@ -19,21 +18,36 @@ import routes from '~/utils/routes'
interface OrganisationCardProps {
organisation: DetailedOrganisation
- reloadOrganisations: () => Promise<void>
}
-export const OrganisationCard = ({ organisation, reloadOrganisations }: OrganisationCardProps) => {
+export const OrganisationCard = ({ organisation }: OrganisationCardProps) => {
const { t } = useTranslation('common')
const { user, mergeUser } = useAuth()
const [showInviteModal, setShowInviteModal] = useState(false)
+ const fetcher = useFetcher<OrganisationsActionData>()
const { name, members } = organisation
+ const isAccepting = fetcher.state === 'submitting' && fetcher.formData?.get('intent') === 'accept-invitation'
+
const membership = useMemo(
() => _find(members, (member) => member.user.email === user?.email),
[members, user?.email],
)
+ useEffect(() => {
+ if (fetcher.data?.success && fetcher.data?.intent === 'accept-invitation') {
+ mergeUser({
+ organisationMemberships: _map(user?.organisationMemberships, (item) => {
+ if (item.id === membership?.id) {
+ return { ...item, confirmed: true }
+ }
+ return item
+ }),
+ })
+ }
+ }, [fetcher.data]) // eslint-disable-line react-hooks/exhaustive-deps
+
const badges = useMemo(() => {
const list: BadgeProps[] = []
@@ -58,30 +72,15 @@ export const OrganisationCard = ({ organisation, reloadOrganisations }: Organisa
return list
}, [t, membership, members])
- const onAccept = async () => {
- try {
- if (!membership?.id) {
- throw new Error('Membership not found')
- }
-
- await acceptOrganisationInvitation(membership.id)
-
- await reloadOrganisations()
-
- mergeUser({
- organisationMemberships: _map(user?.organisationMemberships, (item) => {
- if (item.id === membership.id) {
- return { ...item, confirmed: true }
- }
- return item
- }),
- })
-
- toast.success(t('apiNotifications.acceptOrganisationInvitation'))
- } catch (reason: any) {
- console.error(`[ERROR] Error while accepting organisation invitation: ${reason}`)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.acceptOrganisationInvitationError'))
+ const onAccept = () => {
+ if (!membership?.id) {
+ return
}
+
+ const formData = new FormData()
+ formData.set('intent', 'accept-invitation')
+ formData.set('membershipId', membership.id)
+ fetcher.submit(formData, { method: 'post' })
}
const onElementClick = (e: React.MouseEvent<HTMLAnchorElement | HTMLDivElement>) => {
@@ -93,46 +92,23 @@ export const OrganisationCard = ({ organisation, reloadOrganisations }: Organisa
setShowInviteModal(true)
}
- const CardWrapper = ({
- children,
- to,
- ...props
- }: {
- children: React.ReactNode
- to?: string
- onClick?: (e: React.MouseEvent<HTMLAnchorElement | HTMLDivElement>) => void
- className?: string
- }) => {
- if (membership?.role === 'viewer') {
- return <div {...props}>{children}</div>
- }
-
- return (
- <Link to={to!} {...props}>
- {children}
- </Link>
- )
- }
+ const isViewer = membership?.role === 'viewer'
+ const cardClassName = cx(
+ 'min-h-[153.1px] overflow-hidden rounded-xl border border-gray-200 bg-gray-50 transition-colors dark:border-slate-800/25 dark:bg-slate-800/70',
+ {
+ 'cursor-pointer hover:bg-gray-200/70 dark:hover:bg-slate-700/60': !isViewer,
+ },
+ )
- return (
- <CardWrapper
- to={_replace(routes.organisation, ':id', organisation.id)}
- onClick={onElementClick}
- className={cx(
- 'min-h-[153.1px] overflow-hidden rounded-xl border border-gray-200 bg-gray-50 transition-colors dark:border-slate-800/25 dark:bg-slate-800/70',
- {
- 'cursor-pointer hover:bg-gray-200/70 dark:hover:bg-slate-700/60': membership?.role !== 'viewer',
- },
- )}
- >
+ const cardContent = (
+ <>
<div className='px-4 py-4'>
<div className='flex items-center justify-between'>
<Text as='p' size='lg' weight='semibold' truncate>
{name}
</Text>
- {membership?.role === 'viewer' ? null : (
- // dummy button, since the whole card is clickable
+ {isViewer ? null : (
<div
aria-label={`${t('project.settings.settings')} ${name}`}
className='rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 dark:hover:text-slate-300'
@@ -162,8 +138,23 @@ export const OrganisationCard = ({ organisation, reloadOrganisations }: Organisa
title={t('dashboard.invitationFor', { project: name })}
message={t('dashboard.invitationDesc', { project: name })}
isOpened={showInviteModal}
+ isLoading={isAccepting}
/>
) : null}
- </CardWrapper>
+ </>
+ )
+
+ if (isViewer) {
+ return (
+ <div onClick={onElementClick} className={cardClassName}>
+ {cardContent}
+ </div>
+ )
+ }
+
+ return (
+ <Link to={_replace(routes.organisation, ':id', organisation.id)} onClick={onElementClick} className={cardClassName}>
+ {cardContent}
+ </Link>
)
}
diff --git a/web/app/pages/Organisations/Organisations.tsx b/web/app/pages/Organisations/Organisations.tsx
index 578541986..1de17ea23 100644
--- a/web/app/pages/Organisations/Organisations.tsx
+++ b/web/app/pages/Organisations/Organisations.tsx
@@ -3,20 +3,16 @@ import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import _size from 'lodash/size'
import { SearchIcon, XIcon } from 'lucide-react'
-import React, { useState, useEffect, useCallback, useRef } from 'react'
+import React, { useState, useEffect, useRef, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
-import { ClientOnly } from 'remix-utils/client-only'
+import { useFetcher, useLoaderData, useNavigate, useRevalidator } from 'react-router'
import { toast } from 'sonner'
-import { createOrganisation, getOrganisations } from '~/api'
import EventsRunningOutBanner from '~/components/EventsRunningOutBanner'
-import { withAuthentication, auth } from '~/hoc/protected'
import useDebounce from '~/hooks/useDebounce'
import { ENTRIES_PER_PAGE_DASHBOARD } from '~/lib/constants'
-import { DetailedOrganisation } from '~/lib/models/Organisation'
-import { useAuth } from '~/providers/AuthProvider'
+import type { OrganisationsActionData, OrganisationsLoaderData } from '~/routes/organisations._index'
import Input from '~/ui/Input'
-import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
import Pagination from '~/ui/Pagination'
import StatusPage from '~/ui/StatusPage'
@@ -28,110 +24,113 @@ import { NoOrganisations } from './NoOrganisations'
import { OrganisationCard } from './OrganisationCard'
const Organisations = () => {
- const { isLoading: authLoading } = useAuth()
+ const loaderData = useLoaderData<OrganisationsLoaderData>()
+ const fetcher = useFetcher<OrganisationsActionData>()
+ const navigate = useNavigate()
+ const { revalidate } = useRevalidator()
const { t } = useTranslation('common')
- const [isSearchActive, setIsSearchActive] = useState(false)
+ const [isSearchActive, setIsSearchActive] = useState(() => !!loaderData?.search)
const searchInputRef = useRef<HTMLInputElement>(null)
const [showActivateEmailModal, setShowActivateEmailModal] = useState(false)
- const [search, setSearch] = useState('')
+ const [search, setSearch] = useState(loaderData?.search || '')
const debouncedSearch = useDebounce<string>(search, 500)
- const [organisations, setOrganisations] = useState<DetailedOrganisation[]>([])
- const [paginationTotal, setPaginationTotal] = useState(0)
- const [page, setPage] = useState(1)
const [newOrganisationModalOpen, setNewOrganisationModalOpen] = useState(false)
const [newOrganisationName, setNewOrganisationName] = useState('')
+ const [newOrganisationError, setNewOrganisationError] = useState<string | null>(null)
- const [isLoading, setIsLoading] = useState<boolean | null>(null)
- const [isNewOrganisationLoading, setIsNewOrganisationLoading] = useState(false)
+ const isNewOrganisationLoading = fetcher.state === 'submitting'
- const [error, setError] = useState<string | null>(null)
- const [newOrganisationError, setNewOrganisationError] = useState<string | null>(null)
+ const organisations = loaderData?.organisations || []
+ const paginationTotal = loaderData?.total || 0
+ const page = loaderData?.page || 1
+ const error = loaderData?.error
const pageAmount = Math.ceil(paginationTotal / ENTRIES_PER_PAGE_DASHBOARD)
- const onNewOrganisation = () => {
- setNewOrganisationModalOpen(true)
+ const updateUrlParams = (newPage: number, newSearch: string) => {
+ const params = new URLSearchParams()
+ if (newPage > 1) params.set('page', String(newPage))
+ if (newSearch) params.set('search', newSearch)
+ navigate(`${routes.organisations}${params.toString() ? `?${params.toString()}` : ''}`, { replace: true })
}
- const onCreateOrganisation = async () => {
+ const closeNewOrganisationModal = useCallback(() => {
if (isNewOrganisationLoading) {
return
}
- setIsNewOrganisationLoading(true)
+ setNewOrganisationModalOpen(false)
+ setNewOrganisationError(null)
+ setNewOrganisationName('')
+ }, [isNewOrganisationLoading])
+
+ useEffect(() => {
+ if (debouncedSearch !== loaderData?.search) {
+ updateUrlParams(1, debouncedSearch)
+ }
+ }, [debouncedSearch]) // eslint-disable-line react-hooks/exhaustive-deps
- try {
- await createOrganisation(newOrganisationName)
+ // Handle fetcher responses
+ useEffect(() => {
+ if (!fetcher.data) return
- const result = await getOrganisations(
- ENTRIES_PER_PAGE_DASHBOARD,
- (page - 1) * ENTRIES_PER_PAGE_DASHBOARD,
- debouncedSearch,
- )
- setOrganisations(result.results)
- setPaginationTotal(result.total)
+ const { intent, success, error, fieldErrors } = fetcher.data
- toast.success(t('apiNotifications.organisationCreated'))
+ switch (intent) {
+ case 'create-organisation':
+ if (success) {
+ revalidate()
+ toast.success(t('apiNotifications.organisationCreated'))
+ // eslint-disable-next-line
+ closeNewOrganisationModal()
+ } else if (fieldErrors?.name) {
+ setNewOrganisationError(fieldErrors.name)
+ toast.error(fieldErrors.name)
+ } else if (error) {
+ setNewOrganisationError(error)
+ toast.error(error)
+ }
+ break
- closeNewOrganisationModal()
- } catch (reason: any) {
- setNewOrganisationError(reason)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.organisationCreateError'))
- } finally {
- setIsNewOrganisationLoading(false)
- }
- }
+ case 'accept-invitation':
+ if (success) {
+ revalidate()
+ toast.success(t('apiNotifications.acceptOrganisationInvitation'))
+ } else if (error) {
+ toast.error(error)
+ }
+ break
- const closeNewOrganisationModal = () => {
- if (isNewOrganisationLoading) {
- return
+ default:
+ if (error) {
+ toast.error(error)
+ }
+ break
}
+ }, [fetcher.data, t, revalidate, closeNewOrganisationModal])
- setNewOrganisationModalOpen(false)
- setNewOrganisationError(null)
- setNewOrganisationName('')
+ const onNewOrganisation = () => {
+ setNewOrganisationModalOpen(true)
}
- const loadOrganisations = async (take: number, skip: number, search?: string) => {
- if (isLoading) {
+ const onCreateOrganisation = () => {
+ if (fetcher.state === 'submitting') {
return
}
- setIsLoading(true)
- try {
- const result = await getOrganisations(take, skip, search)
- setOrganisations(result.results)
- setPaginationTotal(result.total)
- } catch (reason: any) {
- setError(reason)
- } finally {
- setIsLoading(false)
- }
+ const formData = new FormData()
+ formData.set('intent', 'create-organisation')
+ formData.set('name', newOrganisationName)
+ fetcher.submit(formData, { method: 'post' })
}
- const reloadOrganisations = useCallback(async () => {
- try {
- const result = await getOrganisations(
- ENTRIES_PER_PAGE_DASHBOARD,
- (page - 1) * ENTRIES_PER_PAGE_DASHBOARD,
- debouncedSearch,
- )
- setOrganisations(result.results)
- setPaginationTotal(result.total)
- } catch (reason: any) {
- console.error(`[ERROR] Error while reloading organisations: ${reason}`)
- }
- }, [debouncedSearch, page])
-
- useEffect(() => {
- loadOrganisations(ENTRIES_PER_PAGE_DASHBOARD, (page - 1) * ENTRIES_PER_PAGE_DASHBOARD, debouncedSearch)
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [page, debouncedSearch])
+ const setPage = (newPage: number) => {
+ updateUrlParams(newPage, debouncedSearch)
+ }
- if (error && isLoading === false) {
+ if (error) {
return (
<StatusPage
type='error'
@@ -250,38 +249,18 @@ const Organisations = () => {
</div>
</div>
) : null}
- {authLoading || isLoading || isLoading === null ? (
- <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
- <Loader />
- </div>
- ) : (
- <ClientOnly
- fallback={
- <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
- <Loader />
- </div>
- }
- >
- {() => (
- <div>
- {_isEmpty(organisations) ? (
- <NoOrganisations onClick={onNewOrganisation} />
- ) : (
- <div className='grid grid-cols-1 gap-x-6 gap-y-3 lg:grid-cols-3 lg:gap-y-6'>
- {_map(organisations, (organisation) => (
- <OrganisationCard
- key={organisation.id}
- organisation={organisation}
- reloadOrganisations={reloadOrganisations}
- />
- ))}
- <AddOrganisation sitesCount={_size(organisations)} onClick={onNewOrganisation} />
- </div>
- )}
- </div>
- )}
- </ClientOnly>
- )}
+ <div>
+ {_isEmpty(organisations) ? (
+ <NoOrganisations onClick={onNewOrganisation} />
+ ) : (
+ <div className='grid grid-cols-1 gap-x-6 gap-y-3 lg:grid-cols-3 lg:gap-y-6'>
+ {_map(organisations, (organisation) => (
+ <OrganisationCard key={organisation.id} organisation={organisation} />
+ ))}
+ <AddOrganisation sitesCount={_size(organisations)} onClick={onNewOrganisation} />
+ </div>
+ )}
+ </div>
{pageAmount > 1 ? (
<Pagination
className='mt-2'
@@ -331,4 +310,4 @@ const Organisations = () => {
)
}
-export default withAuthentication(Organisations, auth.authenticated)
+export default Organisations
diff --git a/web/app/pages/Organisations/Settings/People.tsx b/web/app/pages/Organisations/Settings/People.tsx
index a4e95995e..bb1a73d49 100644
--- a/web/app/pages/Organisations/Settings/People.tsx
+++ b/web/app/pages/Organisations/Settings/People.tsx
@@ -7,13 +7,14 @@ import _map from 'lodash/map'
import { Trash2Icon, UserRoundPlusIcon } from 'lucide-react'
import React, { useState, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { changeOrganisationRole, inviteOrganisationMember, removeOrganisationMember } from '~/api'
import useOnClickOutside from '~/hooks/useOnClickOutside'
import { roles, INVITATION_EXPIRES_IN } from '~/lib/constants'
import { DetailedOrganisation, Role } from '~/lib/models/Organisation'
import { useAuth } from '~/providers/AuthProvider'
+import type { OrganisationSettingsActionData } from '~/routes/organisations.$id'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
@@ -35,10 +36,10 @@ const NoPeople = () => {
interface UsersListProps {
members: DetailedOrganisation['members']
onRemove: (member: DetailedOrganisation['members'][number]) => void
- reloadOrganisation: () => Promise<void>
+ fetcher: ReturnType<typeof useFetcher<OrganisationSettingsActionData>>
}
-const UsersList = ({ members, onRemove, reloadOrganisation }: UsersListProps) => {
+const UsersList = ({ members, onRemove, fetcher }: UsersListProps) => {
const {
t,
i18n: { language },
@@ -49,16 +50,12 @@ const UsersList = ({ members, onRemove, reloadOrganisation }: UsersListProps) =>
const openRef = useRef<HTMLUListElement>(null)
useOnClickOutside(openRef, () => setRoleEditDropdownId(null))
- const changeRole = async (memberId: string, newRole: Role) => {
- try {
- await changeOrganisationRole(memberId, newRole)
- await reloadOrganisation()
- toast.success(t('apiNotifications.roleUpdated'))
- } catch (reason) {
- console.error(`[ERROR] Error while updating user's role: ${reason}`)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.roleUpdateError'))
- }
-
+ const changeRole = (memberId: string, newRole: Role) => {
+ const formData = new FormData()
+ formData.set('intent', 'update-member-role')
+ formData.set('memberId', memberId)
+ formData.set('role', newRole)
+ fetcher.submit(formData, { method: 'post' })
setRoleEditDropdownId(null)
}
@@ -148,12 +145,13 @@ const UsersList = ({ members, onRemove, reloadOrganisation }: UsersListProps) =>
interface PeopleProps {
organisation: DetailedOrganisation
- reloadOrganisation: () => Promise<void>
}
-const People = ({ organisation, reloadOrganisation }: PeopleProps) => {
+const People = ({ organisation }: PeopleProps) => {
const [showModal, setShowModal] = useState(false)
const { t } = useTranslation('common')
+ const fetcher = useFetcher<OrganisationSettingsActionData>()
+
const [form, setForm] = useState<{
email: string
role: Role
@@ -169,11 +167,44 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps) => {
const [validated, setValidated] = useState(false)
const [showDeleteModal, setShowDeleteModal] = useState(false)
- const [isDeleting, setIsDeleting] = useState(false)
const [memberToRemove, setMemberToRemove] = useState<DetailedOrganisation['members'][number] | null>(null)
const { name, members } = organisation
+ const isSubmitting = fetcher.state === 'submitting'
+ const isDeleting = isSubmitting && fetcher.formData?.get('intent') === 'remove-member'
+
+ const closeModal = () => {
+ setShowModal(false)
+ setTimeout(() => setForm({ email: '', role: 'viewer' }), 300)
+ setErrors({})
+ setBeenSubmitted(false)
+ }
+
+ const closeRemoveUserModal = () => {
+ setShowDeleteModal(false)
+ setTimeout(() => setMemberToRemove(null), 300)
+ }
+
+ /* eslint-disable react-hooks/set-state-in-effect */
+ useEffect(() => {
+ if (fetcher.data?.success) {
+ const { intent } = fetcher.data
+ if (intent === 'invite-member') {
+ toast.success(t('apiNotifications.userInvited'))
+ closeModal()
+ } else if (intent === 'remove-member') {
+ toast.success(t('apiNotifications.orgUserRemoved'))
+ closeRemoveUserModal()
+ } else if (intent === 'update-member-role') {
+ toast.success(t('apiNotifications.roleUpdated'))
+ }
+ } else if (fetcher.data?.error) {
+ toast.error(fetcher.data.error)
+ }
+ }, [fetcher.data, t])
+ /* eslint-enable react-hooks/set-state-in-effect */
+
const validate = () => {
const allErrors: {
email?: string
@@ -194,11 +225,13 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps) => {
setValidated(valid)
}
+ /* eslint-disable react-hooks/set-state-in-effect */
useEffect(() => {
if (showModal) {
validate()
}
- }, [form]) // eslint-disable-line
+ }, [form]) // eslint-disable-line react-hooks/exhaustive-deps
+ /* eslint-enable react-hooks/set-state-in-effect */
const handleInput = ({ target }: React.ChangeEvent<HTMLInputElement>) => {
const value = target.type === 'checkbox' ? target.checked : target.value
@@ -209,22 +242,12 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps) => {
}))
}
- const onInviteToOrganisation = async () => {
- setShowModal(false)
- setErrors({})
- setValidated(false)
-
- try {
- await inviteOrganisationMember(organisation.id, form)
- await reloadOrganisation()
- toast.success(t('apiNotifications.userInvited'))
- } catch (reason) {
- console.error(`[ERROR] Error while inviting a user: ${reason}`)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.userInviteError'))
- }
-
- // a timeout is needed to prevent the flicker of data fields in the modal when closing
- setTimeout(() => setForm({ email: '', role: 'viewer' }), 300)
+ const onInviteToOrganisation = () => {
+ const formData = new FormData()
+ formData.set('intent', 'invite-member')
+ formData.set('email', form.email)
+ formData.set('role', form.role)
+ fetcher.submit(formData, { method: 'post' })
}
const handleSubmit = (e: React.MouseEvent<HTMLButtonElement>) => {
@@ -239,36 +262,11 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps) => {
}
}
- const closeModal = () => {
- setShowModal(false)
- // a timeout is needed to prevent the flicker of data fields in the modal when closing
- setTimeout(() => setForm({ email: '', role: 'viewer' }), 300)
- setErrors({})
- }
-
- const closeRemoveUserModal = () => {
- setShowDeleteModal(false)
- setTimeout(() => setMemberToRemove(null), 300)
- }
-
- const onRemove = async (member: DetailedOrganisation['members'][number]) => {
- if (isDeleting) {
- return
- }
-
- setIsDeleting(true)
-
- try {
- await removeOrganisationMember(member.id)
- await reloadOrganisation()
-
- toast.success(t('apiNotifications.orgUserRemoved'))
- } catch (reason) {
- console.error(`[ERROR] Error while removing user from the organisation: ${reason}`)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.orgUserRemoveError'))
- } finally {
- setIsDeleting(false)
- }
+ const onRemove = (member: DetailedOrganisation['members'][number]) => {
+ const formData = new FormData()
+ formData.set('intent', 'remove-member')
+ formData.set('memberId', member.id)
+ fetcher.submit(formData, { method: 'post' })
}
return (
@@ -320,7 +318,7 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps) => {
setMemberToRemove(member)
setShowDeleteModal(true)
}}
- reloadOrganisation={reloadOrganisation}
+ fetcher={fetcher}
/>
</tbody>
</table>
diff --git a/web/app/pages/Organisations/Settings/Projects.tsx b/web/app/pages/Organisations/Settings/Projects.tsx
index 258602aaa..3e5aa2611 100644
--- a/web/app/pages/Organisations/Settings/Projects.tsx
+++ b/web/app/pages/Organisations/Settings/Projects.tsx
@@ -5,14 +5,14 @@ import _map from 'lodash/map'
import _replace from 'lodash/replace'
import { useState, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link } from 'react-router'
+import { Link, useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { removeProjectFromOrganisation, getProjectsAvailableForOrganisation, addProjectToOrganisation } from '~/api'
import useDebounce from '~/hooks/useDebounce'
import { DetailedOrganisation } from '~/lib/models/Organisation'
import { Project } from '~/lib/models/Project'
import { useAuth } from '~/providers/AuthProvider'
+import type { OrganisationSettingsActionData } from '~/routes/organisations.$id'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
@@ -29,39 +29,39 @@ const PROJECT_LIST_PAGE_SIZE = 20
const SelectAProject = ({ onSelect }: SelectAProjectProps) => {
const { t } = useTranslation('common')
+ const fetcher = useFetcher<OrganisationSettingsActionData>()
const [currentPage, setCurrentPage] = useState(1)
const [search, setSearch] = useState('')
- const [isLoading, setIsLoading] = useState(false)
const [projects, setProjects] = useState<Project[]>([])
const [total, setTotal] = useState(0)
const debouncedSearch = useDebounce(search, 500)
const pageAmount = Math.ceil(total / PROJECT_SELECT_PAGE_SIZE)
+ const isLoading = fetcher.state === 'submitting' || fetcher.state === 'loading'
+ // Fetch projects when page or search changes
useEffect(() => {
- const loadProjects = async () => {
- setIsLoading(true)
- try {
- const { results, total: totalCount } = await getProjectsAvailableForOrganisation(
- PROJECT_SELECT_PAGE_SIZE,
- (currentPage - 1) * PROJECT_SELECT_PAGE_SIZE,
- debouncedSearch,
- )
- setProjects(results)
- setTotal(totalCount)
- } catch (reason) {
- console.error('Failed to load projects:', reason)
- } finally {
- setIsLoading(false)
- }
+ const formData = new FormData()
+ formData.set('intent', 'get-available-projects')
+ formData.set('take', String(PROJECT_SELECT_PAGE_SIZE))
+ formData.set('skip', String((currentPage - 1) * PROJECT_SELECT_PAGE_SIZE))
+ formData.set('search', debouncedSearch)
+ fetcher.submit(formData, { method: 'post' })
+ }, [currentPage, debouncedSearch]) // eslint-disable-line react-hooks/exhaustive-deps
+
+ // Update local state when fetcher returns data
+ useEffect(() => {
+ if (fetcher.data?.intent === 'get-available-projects' && fetcher.data?.availableProjects) {
+ setTimeout(() => {
+ setProjects(fetcher.data!.availableProjects!.results as Project[])
+ setTotal(fetcher.data!.availableProjects!.total)
+ }, 0)
}
-
- loadProjects()
- }, [currentPage, debouncedSearch])
+ }, [fetcher.data])
useEffect(() => {
- setCurrentPage(1)
+ setTimeout(() => setCurrentPage(1), 0)
}, [debouncedSearch])
return (
@@ -169,17 +169,15 @@ const ProjectList = ({ projects, onRemove }: ProjectListProps) => {
interface ProjectsProps {
organisation: DetailedOrganisation
- reloadOrganisation: () => Promise<void>
}
-export const Projects = ({ organisation, reloadOrganisation }: ProjectsProps) => {
+export const Projects = ({ organisation }: ProjectsProps) => {
const { t } = useTranslation('common')
+ const fetcher = useFetcher<OrganisationSettingsActionData>()
const [showDeleteModal, setShowDeleteModal] = useState(false)
const [showAddProjectModal, setShowAddProjectModal] = useState(false)
const [projectToRemove, setProjectToRemove] = useState<DetailedOrganisation['projects'][number] | null>(null)
-
- const [isActionLoading, setIsActionLoading] = useState(false)
const [selectedProject, setSelectedProject] = useState<any>(null)
const [currentPage, setCurrentPage] = useState(1)
@@ -187,6 +185,29 @@ export const Projects = ({ organisation, reloadOrganisation }: ProjectsProps) =>
const [isSearchActive, setIsSearchActive] = useState(false)
const { projects } = organisation
+ const isSubmitting = fetcher.state === 'submitting'
+ const isAddingProject = isSubmitting && fetcher.formData?.get('intent') === 'add-project'
+ const isRemovingProject = isSubmitting && fetcher.formData?.get('intent') === 'remove-project'
+
+ /* eslint-disable react-hooks/set-state-in-effect */
+ useEffect(() => {
+ if (fetcher.data?.success) {
+ const { intent } = fetcher.data
+ if (intent === 'add-project') {
+ toast.success(t('apiNotifications.projectAddedToOrganisation'))
+ setShowAddProjectModal(false)
+ setSelectedProject(null)
+ } else if (intent === 'remove-project') {
+ toast.success(t('apiNotifications.projectRemovedFromOrganisation'))
+ setShowDeleteModal(false)
+ setProjectToRemove(null)
+ }
+ } else if (fetcher.data?.error) {
+ toast.error(fetcher.data.error)
+ }
+ }, [fetcher.data, t])
+ /* eslint-enable react-hooks/set-state-in-effect */
+
const filteredProjects = useMemo(() => {
if (!search) {
return projects
@@ -197,46 +218,20 @@ export const Projects = ({ organisation, reloadOrganisation }: ProjectsProps) =>
const pageAmount = Math.ceil(filteredProjects.length / PROJECT_LIST_PAGE_SIZE)
- const removeProject = async (projectId: string) => {
- if (isActionLoading) {
- return
- }
-
- setIsActionLoading(true)
-
- try {
- await removeProjectFromOrganisation(organisation.id, projectId)
- await reloadOrganisation()
- toast.success(t('apiNotifications.projectRemovedFromOrganisation'))
- } catch (reason) {
- console.error(`[ERROR] Error while deleting a project: ${reason}`)
- toast.error(t('apiNotifications.projectRemoveError'))
- } finally {
- setProjectToRemove(null)
- setIsActionLoading(false)
- }
+ const removeProject = (projectId: string) => {
+ const formData = new FormData()
+ formData.set('intent', 'remove-project')
+ formData.set('projectId', projectId)
+ fetcher.submit(formData, { method: 'post' })
}
- const onAddProject = async () => {
- setShowAddProjectModal(false)
+ const onAddProject = () => {
+ if (!selectedProject) return
- if (isActionLoading) {
- return
- }
-
- setIsActionLoading(true)
-
- try {
- await addProjectToOrganisation(organisation.id, selectedProject.id)
- await reloadOrganisation()
- toast.success(t('apiNotifications.projectAddedToOrganisation'))
- } catch (reason) {
- console.error(`[ERROR] Error while adding a project: ${reason}`)
- toast.error(t('apiNotifications.projectAddError'))
- } finally {
- setSelectedProject(null)
- setIsActionLoading(false)
- }
+ const formData = new FormData()
+ formData.set('intent', 'add-project')
+ formData.set('projectId', selectedProject.id)
+ fetcher.submit(formData, { method: 'post' })
}
return (
@@ -353,7 +348,7 @@ export const Projects = ({ organisation, reloadOrganisation }: ProjectsProps) =>
type='button'
className='inline-flex w-full justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-base font-medium text-white hover:bg-indigo-700 sm:ml-3 sm:w-auto sm:text-sm'
onClick={onAddProject}
- disabled={!selectedProject || isActionLoading}
+ disabled={!selectedProject || isAddingProject}
>
{t('organisations.addProject')}
</button>
@@ -383,7 +378,7 @@ export const Projects = ({ organisation, reloadOrganisation }: ProjectsProps) =>
</div>
}
isOpened={showAddProjectModal}
- isLoading={isActionLoading}
+ isLoading={isAddingProject}
/>
<Modal
@@ -391,9 +386,8 @@ export const Projects = ({ organisation, reloadOrganisation }: ProjectsProps) =>
setShowDeleteModal(false)
setProjectToRemove(null)
}}
- onSubmit={async () => {
- await removeProject(projectToRemove!.id)
- setShowDeleteModal(false)
+ onSubmit={() => {
+ removeProject(projectToRemove!.id)
}}
submitText={t('common.yes')}
closeText={t('common.no')}
@@ -401,7 +395,7 @@ export const Projects = ({ organisation, reloadOrganisation }: ProjectsProps) =>
message={t('organisations.modals.remove.message')}
isOpened={showDeleteModal}
type='warning'
- isLoading={isActionLoading}
+ isLoading={isRemovingProject}
/>
</div>
)
diff --git a/web/app/pages/Organisations/Settings/index.tsx b/web/app/pages/Organisations/Settings/index.tsx
index a77df5b19..59c622747 100644
--- a/web/app/pages/Organisations/Settings/index.tsx
+++ b/web/app/pages/Organisations/Settings/index.tsx
@@ -2,17 +2,15 @@ import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _size from 'lodash/size'
import { Trash2Icon } from 'lucide-react'
-import React, { useState, useEffect, useCallback, useMemo } from 'react'
+import React, { useState, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link, useNavigate } from 'react-router'
+import { Link, useNavigate, useFetcher, useLoaderData, useRevalidator } from 'react-router'
import { toast } from 'sonner'
-import { transferProject, getOrganisation, updateOrganisation, deleteOrganisation } from '~/api'
-import { withAuthentication, auth } from '~/hoc/protected'
-import { useRequiredParams } from '~/hooks/useRequiredParams'
import { TITLE_SUFFIX } from '~/lib/constants'
import { DetailedOrganisation } from '~/lib/models/Organisation'
import { useAuth } from '~/providers/AuthProvider'
+import type { OrganisationSettingsActionData, OrganisationLoaderData } from '~/routes/organisations.$id'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import Loader from '~/ui/Loader'
@@ -23,18 +21,16 @@ import routes from '~/utils/routes'
import People from './People'
import { Projects } from './Projects'
-// import { ArrowLeftRight } from 'lucide-react'
-
const MAX_NAME_LENGTH = 50
-const DEFAULT_ORGANISATION_NAME = 'Untitled Organisation'
-
const OrganisationSettings = () => {
const { t } = useTranslation('common')
- const { id } = useRequiredParams<{ id: string }>()
+ const loaderData = useLoaderData<OrganisationLoaderData>()
const navigate = useNavigate()
+ const fetcher = useFetcher<OrganisationSettingsActionData>()
+ const revalidator = useRevalidator()
- const { user, isLoading: authLoading } = useAuth()
+ const { user } = useAuth()
const [validated, setValidated] = useState(false)
const [errors, setErrors] = useState<{
@@ -42,18 +38,52 @@ const OrganisationSettings = () => {
}>({})
const [beenSubmitted, setBeenSubmitted] = useState(false)
const [showDelete, setShowDelete] = useState(false)
- const [isDeleting, setIsDeleting] = useState(false)
- const [isSaving, setIsSaving] = useState(false)
- const [showTransfer, setShowTransfer] = useState(false)
- const [transferEmail, setTransferEmail] = useState('')
+ const [isFormDirty, setIsFormDirty] = useState(false)
+
+ const organisation = loaderData?.organisation || null
+ const error = loaderData?.error
+
+ const [form, setForm] = useState<Pick<DetailedOrganisation, 'name'>>(() => ({
+ name: organisation?.name || '',
+ }))
+
+ useEffect(() => {
+ if (organisation && !isFormDirty) {
+ // eslint-disable-next-line
+ setForm({ name: organisation.name || '' })
+ }
+ }, [organisation, isFormDirty])
- const [isLoading, setIsLoading] = useState<boolean | null>(null)
- const [error, setError] = useState<string | null>(null)
+ const isSaving = fetcher.state === 'submitting' && fetcher.formData?.get('intent') === 'update-organisation'
+ const isDeleting = fetcher.state === 'submitting' && fetcher.formData?.get('intent') === 'delete-organisation'
- const [organisation, setOrganisation] = useState<DetailedOrganisation | null>(null)
- const [form, setForm] = useState<Pick<DetailedOrganisation, 'name'>>({
- name: '',
- })
+ useEffect(() => {
+ if (fetcher.data?.success) {
+ const { intent } = fetcher.data
+
+ if (intent === 'update-organisation') {
+ toast.success(t('apiNotifications.orgSettingsUpdated'))
+ // eslint-disable-next-line
+ setIsFormDirty(false)
+ revalidator.revalidate()
+ } else if (intent === 'delete-organisation') {
+ toast.success(t('apiNotifications.organisationDeleted'))
+ setShowDelete(false)
+ navigate(routes.organisations)
+ } else if (
+ intent === 'invite-member' ||
+ intent === 'remove-member' ||
+ intent === 'update-member-role' ||
+ intent === 'add-project' ||
+ intent === 'remove-project'
+ ) {
+ revalidator.revalidate()
+ }
+ } else if (fetcher.data?.error) {
+ toast.error(fetcher.data.error)
+ setShowDelete(false)
+ }
+ }, [fetcher.data, t, navigate, revalidator])
const isOrganisationOwner = useMemo(() => {
if (!organisation) {
@@ -65,81 +95,21 @@ const OrganisationSettings = () => {
return owner?.user?.email === user?.email
}, [organisation, user])
- const loadOrganisation = async (organisationId: string) => {
- if (isLoading) {
- return
- }
- setIsLoading(true)
-
- try {
- const result = await getOrganisation(organisationId)
- setOrganisation(result)
- setForm({
- name: result.name,
- })
- } catch (reason: any) {
- setError(reason)
- } finally {
- setIsLoading(false)
- }
- }
-
- const reloadOrganisation = useCallback(async () => {
- try {
- const result = await getOrganisation(id)
- setOrganisation(result)
- setForm({
- name: result.name,
- })
- } catch (reason: any) {
- console.error(`[ERROR] Error while reloading organisation: ${reason}`)
- }
- }, [id])
-
- useEffect(() => {
- if (authLoading) {
- return
- }
-
- loadOrganisation(id)
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [authLoading, id])
-
- const onSubmit = async (data: any) => {
- if (isSaving) {
- return
- }
-
- setIsSaving(true)
+ const onSubmit = (formData: Pick<DetailedOrganisation, 'name'>) => {
+ if (fetcher.state === 'submitting') return
- try {
- await updateOrganisation(id, { name: data.name })
- toast.success(t('apiNotifications.orgSettingsUpdated'))
- } catch (reason: any) {
- toast.error(reason)
- } finally {
- setIsSaving(false)
- }
+ const fd = new FormData()
+ fd.set('intent', 'update-organisation')
+ fd.set('name', formData.name)
+ fetcher.submit(fd, { method: 'post' })
}
- const onDelete = async () => {
- if (isDeleting) {
- return
- }
-
- setIsDeleting(true)
+ const onDelete = () => {
+ if (fetcher.state === 'submitting') return
- try {
- await deleteOrganisation(id)
- toast.success(t('apiNotifications.organisationDeleted'))
- navigate(routes.organisations)
- } catch (reason: any) {
- toast.error(reason)
- } finally {
- setIsDeleting(false)
- setShowDelete(false)
- }
+ const fd = new FormData()
+ fd.set('intent', 'delete-organisation')
+ fetcher.submit(fd, { method: 'post' })
}
const validate = () => {
@@ -164,14 +134,17 @@ const OrganisationSettings = () => {
setValidated(valid)
}
+ /* eslint-disable react-hooks/set-state-in-effect */
useEffect(() => {
validate()
- }, [form]) // eslint-disable-line
+ }, [form]) // eslint-disable-line react-hooks/exhaustive-deps
+ /* eslint-enable react-hooks/set-state-in-effect */
const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
const { target } = event
const value = target.type === 'checkbox' ? target.checked : target.value
+ setIsFormDirty(true)
setForm((oldForm) => ({
...oldForm,
[target.name]: value,
@@ -188,36 +161,13 @@ const OrganisationSettings = () => {
}
}
- const onTransfer = async () => {
- await transferProject(id, transferEmail)
- .then(() => {
- toast.success(t('apiNotifications.transferRequestSent'))
- navigate(routes.dashboard)
- })
- .catch((reason) => {
- toast.error(reason)
- })
- .finally(() => {
- setShowTransfer(false)
- setTransferEmail('')
- })
- }
-
const title = `${t('project.settings.settings')} ${form.name}`
useEffect(() => {
document.title = `${t('project.settings.settings')} ${form.name} ${TITLE_SUFFIX}`
}, [form, t])
- if (isLoading || isLoading === null || !organisation) {
- 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) {
+ if (error) {
return (
<StatusPage
type='error'
@@ -231,6 +181,14 @@ const OrganisationSettings = () => {
)
}
+ if (!organisation) {
+ 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>
+ )
+ }
+
return (
<div className='flex min-h-min-footer flex-col bg-gray-50 pb-40 dark:bg-slate-900'>
<form className='mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8' onSubmit={handleSubmit}>
@@ -274,8 +232,8 @@ const OrganisationSettings = () => {
) : null}
</div>
<hr className='mt-2 border-gray-200 sm:mt-5 dark:border-gray-600' />
- <People organisation={organisation} reloadOrganisation={reloadOrganisation} />
- <Projects organisation={organisation} reloadOrganisation={reloadOrganisation} />
+ <People organisation={organisation} />
+ <Projects organisation={organisation} />
</form>
<Modal
onClose={() => setShowDelete(false)}
@@ -291,36 +249,8 @@ const OrganisationSettings = () => {
isOpened={showDelete}
isLoading={isDeleting}
/>
- <Modal
- onClose={() => {
- setShowTransfer(false)
- }}
- submitText={t('project.settings.transfer')}
- closeText={t('common.cancel')}
- message={
- <div>
- <h2 className='text-xl font-bold text-gray-700 dark:text-gray-200'>{t('project.settings.transferTo')}</h2>
- <p className='mt-2 text-base text-gray-700 dark:text-gray-200'>
- {t('project.settings.transferHint', {
- name: form.name || DEFAULT_ORGANISATION_NAME,
- })}
- </p>
- <Input
- name='email'
- type='email'
- label={t('project.settings.transfereeEmail')}
- value={transferEmail}
- placeholder='[email protected]'
- className='mt-4'
- onChange={(e) => setTransferEmail(e.target.value)}
- />
- </div>
- }
- isOpened={showTransfer}
- onSubmit={onTransfer}
- />
</div>
)
}
-export default withAuthentication(OrganisationSettings, auth.authenticated)
+export default OrganisationSettings
diff --git a/web/app/pages/Project/ConfirmShare/index.tsx b/web/app/pages/Project/ConfirmShare/index.tsx
deleted file mode 100644
index 26e411933..000000000
--- a/web/app/pages/Project/ConfirmShare/index.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import _split from 'lodash/split'
-import { useState, useEffect } from 'react'
-import { useTranslation } from 'react-i18next'
-import { useParams } from 'react-router'
-
-import { verifyShare } from '~/api'
-import StatusPage from '~/ui/StatusPage'
-import routes from '~/utils/routes'
-
-const ConfirmShare = () => {
- const { t } = useTranslation('common')
- const { id } = useParams()
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState('')
-
- useEffect(() => {
- setLoading(true)
- const path = _split(window.location.pathname, '/')[1]
-
- if (!id) {
- setError(t('common.error'))
- setLoading(false)
- return
- }
-
- const verify = async () => {
- try {
- await verifyShare({ path, id })
- } catch (reason: any) {
- setError(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- } finally {
- setLoading(false)
- }
- }
-
- verify()
- }, [id]) // eslint-disable-line
-
- if (loading) {
- return <StatusPage loading />
- }
-
- if (error) {
- return (
- <StatusPage
- type='error'
- title={error}
- actions={[
- { label: t('common.dashboard'), to: routes.dashboard, primary: true },
- { label: t('notFoundPage.support'), to: routes.contact },
- ]}
- />
- )
- }
-
- return (
- <StatusPage
- type='success'
- title={t('apiNotifications.acceptInvitation')}
- actions={[{ label: t('common.dashboard'), to: routes.dashboard, primary: true }]}
- />
- )
-}
-
-export default ConfirmShare
diff --git a/web/app/pages/Project/Settings/Annotations.tsx b/web/app/pages/Project/Settings/Annotations.tsx
index ed1ebe104..bc493ccb1 100644
--- a/web/app/pages/Project/Settings/Annotations.tsx
+++ b/web/app/pages/Project/Settings/Annotations.tsx
@@ -2,18 +2,14 @@ import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import _size from 'lodash/size'
import { PencilIcon, Trash2Icon, PlusIcon } from 'lucide-react'
-import { useCallback, useEffect, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import {
- getAnnotations,
- createAnnotation,
- updateAnnotation as updateAnnotationApi,
- deleteAnnotation as deleteAnnotationApi,
-} from '~/api'
import { Annotation } from '~/lib/models/Project'
import AnnotationModal from '~/modals/AnnotationModal'
+import type { ProjectViewActionData } from '~/routes/projects.$id'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
@@ -28,6 +24,8 @@ interface AnnotationsProps {
const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
const { t } = useTranslation('common')
+ const fetcher = useFetcher<ProjectViewActionData>()
+ const lastHandledData = useRef<ProjectViewActionData | null>(null)
const [annotations, setAnnotations] = useState<Annotation[]>([])
const [isLoading, setIsLoading] = useState(true)
@@ -36,27 +34,53 @@ const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
// Modal states
const [isModalOpen, setIsModalOpen] = useState(false)
const [editingAnnotation, setEditingAnnotation] = useState<Annotation | undefined>()
- const [actionLoading, setActionLoading] = useState(false)
+ const [deleteAnnotationItem, setDeleteAnnotationItem] = useState<Annotation | null>(null)
- // Delete confirmation
- const [deleteAnnotation, setDeleteAnnotation] = useState<Annotation | null>(null)
+ const actionLoading = fetcher.state !== 'idle'
- const loadAnnotations = useCallback(async () => {
- setIsLoading(true)
- try {
- const result = await getAnnotations(projectId)
- // Sort by date descending (newest first)
- const sorted = result.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
- setAnnotations(sorted)
- const totalPages = Math.max(1, Math.ceil(sorted.length / ANNOTATIONS_PER_PAGE))
- setPage((prev) => Math.min(prev, totalPages))
- } catch (reason: any) {
- console.error('[ERROR] Failed to load annotations:', reason)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- } finally {
+ const loadAnnotations = useCallback(() => {
+ fetcher.submit({ intent: 'get-annotations', password: '' }, { method: 'POST', action: `/projects/${projectId}` })
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [projectId])
+
+ // Handle fetcher responses
+ useEffect(() => {
+ if (fetcher.state !== 'idle' || !fetcher.data) return
+ if (lastHandledData.current === fetcher.data) return
+ lastHandledData.current = fetcher.data
+
+ const { intent, success, data, error } = fetcher.data
+
+ if (success) {
+ if (intent === 'get-annotations' && data) {
+ const result = data as Annotation[]
+ const sorted = result.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
+ setAnnotations(sorted)
+ const totalPages = Math.max(1, Math.ceil(sorted.length / ANNOTATIONS_PER_PAGE))
+ setPage((prev) => Math.min(prev, totalPages))
+ setIsLoading(false)
+ } else if (intent === 'create-annotation') {
+ toast.success(t('apiNotifications.annotationCreated'))
+ setIsModalOpen(false)
+ setEditingAnnotation(undefined)
+ loadAnnotations()
+ } else if (intent === 'update-annotation') {
+ toast.success(t('apiNotifications.annotationUpdated'))
+ setIsModalOpen(false)
+ setEditingAnnotation(undefined)
+ loadAnnotations()
+ } else if (intent === 'delete-annotation') {
+ toast.success(t('apiNotifications.annotationDeleted'))
+ setDeleteAnnotationItem(null)
+ setIsModalOpen(false)
+ setEditingAnnotation(undefined)
+ loadAnnotations()
+ }
+ } else if (error) {
+ toast.error(error)
setIsLoading(false)
}
- }, [projectId, t])
+ }, [fetcher.state, fetcher.data, t, loadAnnotations])
useEffect(() => {
loadAnnotations()
@@ -80,61 +104,35 @@ const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
setEditingAnnotation(undefined)
}
- const handleSubmit = async (date: string, text: string) => {
- setActionLoading(true)
- try {
- if (editingAnnotation) {
- await updateAnnotationApi(editingAnnotation.id, projectId, date, text)
- toast.success(t('apiNotifications.annotationUpdated'))
- } else {
- await createAnnotation(projectId, date, text)
- toast.success(t('apiNotifications.annotationCreated'))
- }
- await loadAnnotations()
- } catch (reason: any) {
- console.error('[ERROR] Failed to save annotation:', reason)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- } finally {
- setActionLoading(false)
+ const handleSubmit = (date: string, text: string) => {
+ if (actionLoading) return
+
+ if (editingAnnotation) {
+ fetcher.submit(
+ { intent: 'update-annotation', annotationId: editingAnnotation.id, date, text },
+ { method: 'POST', action: `/projects/${projectId}` },
+ )
+ } else {
+ fetcher.submit({ intent: 'create-annotation', date, text }, { method: 'POST', action: `/projects/${projectId}` })
}
}
- const handleDelete = async () => {
- if (!deleteAnnotation) return
+ const handleDelete = () => {
+ if (!deleteAnnotationItem || actionLoading) return
- setActionLoading(true)
- try {
- await deleteAnnotationApi(deleteAnnotation.id, projectId)
- toast.success(t('apiNotifications.annotationDeleted'))
- setDeleteAnnotation(null)
- await loadAnnotations()
- // Reset to first page if current page becomes empty
- if (paginatedAnnotations.length === 1 && page > 1) {
- setPage(page - 1)
- }
- } catch (reason: any) {
- console.error('[ERROR] Failed to delete annotation:', reason)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- } finally {
- setActionLoading(false)
- }
+ fetcher.submit(
+ { intent: 'delete-annotation', annotationId: deleteAnnotationItem.id },
+ { method: 'POST', action: `/projects/${projectId}` },
+ )
}
- const handleDeleteFromModal = async () => {
- if (!editingAnnotation) return
+ const handleDeleteFromModal = () => {
+ if (!editingAnnotation || actionLoading) return
- setActionLoading(true)
- try {
- await deleteAnnotationApi(editingAnnotation.id, projectId)
- toast.success(t('apiNotifications.annotationDeleted'))
- closeModal()
- await loadAnnotations()
- } catch (reason: any) {
- console.error('[ERROR] Failed to delete annotation:', reason)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- } finally {
- setActionLoading(false)
- }
+ fetcher.submit(
+ { intent: 'delete-annotation', annotationId: editingAnnotation.id },
+ { method: 'POST', action: `/projects/${projectId}` },
+ )
}
if (isLoading) {
@@ -217,7 +215,7 @@ const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
</button>
<button
type='button'
- onClick={() => setDeleteAnnotation(annotation)}
+ onClick={() => setDeleteAnnotationItem(annotation)}
className='rounded p-1.5 text-red-500 transition-colors hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-900/20 dark:hover:text-red-300'
title={t('common.delete')}
>
@@ -251,8 +249,8 @@ const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
/>
<Modal
- isOpened={!!deleteAnnotation}
- onClose={() => setDeleteAnnotation(null)}
+ isOpened={!!deleteAnnotationItem}
+ onClose={() => setDeleteAnnotationItem(null)}
onSubmit={handleDelete}
title={t('project.settings.annotations.deleteTitle')}
message={t('project.settings.annotations.deleteConfirm')}
diff --git a/web/app/pages/Project/Settings/Emails/ConfirmReportsShare/index.tsx b/web/app/pages/Project/Settings/Emails/ConfirmReportsShare/index.tsx
deleted file mode 100644
index af7c7aea7..000000000
--- a/web/app/pages/Project/Settings/Emails/ConfirmReportsShare/index.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import { useState, useEffect, memo } from 'react'
-import { useTranslation } from 'react-i18next'
-import { useParams } from 'react-router'
-
-import { confirmSubscriberInvite } from '~/api'
-import StatusPage from '~/ui/StatusPage'
-import routes from '~/utils/routes'
-
-const ConfirmReportsShare = () => {
- const { t } = useTranslation('common')
- const { id } = useParams()
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState('')
-
- const handleConfirm = async (token: string) => {
- try {
- await confirmSubscriberInvite(id as string, token)
- } catch {
- setError(t('apiNotifications.invalidToken'))
- } finally {
- setLoading(false)
- }
- }
-
- useEffect(() => {
- setLoading(true)
- const query = new URLSearchParams(window.location.search)
- const token = query.get('token')
-
- if (!token) {
- setError(t('apiNotifications.invalidToken'))
- setLoading(false)
- return
- }
-
- handleConfirm(token)
- }, []) // eslint-disable-line
-
- if (loading) {
- return <StatusPage loading />
- }
-
- if (error) {
- return (
- <StatusPage
- type='error'
- title={error}
- actions={[
- { label: t('common.dashboard'), to: routes.dashboard, primary: true },
- { label: t('notFoundPage.support'), to: routes.contact },
- ]}
- />
- )
- }
-
- return (
- <StatusPage
- type='success'
- title={t('apiNotifications.acceptInvitation')}
- actions={[{ label: t('common.dashboard'), to: routes.dashboard, primary: true }]}
- />
- )
-}
-
-export default memo(ConfirmReportsShare)
diff --git a/web/app/pages/Project/Settings/Emails/Emails.tsx b/web/app/pages/Project/Settings/Emails/Emails.tsx
index 3757dd6c3..d4f2c13f9 100644
--- a/web/app/pages/Project/Settings/Emails/Emails.tsx
+++ b/web/app/pages/Project/Settings/Emails/Emails.tsx
@@ -9,12 +9,13 @@ import _toLower from 'lodash/toLower'
import { MailPlusIcon, Trash2Icon } from 'lucide-react'
import React, { useState, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher, useParams } from 'react-router'
import { toast } from 'sonner'
-import { addSubscriber, removeSubscriber, getSubscribers, updateSubscriber } from '~/api'
import useOnClickOutside from '~/hooks/useOnClickOutside'
import { reportFrequencyForEmailsOptions } from '~/lib/constants'
import { Subscriber } from '~/lib/models/Subscriber'
+import { ProjectSettingsActionData } from '~/routes/projects.settings.$id'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
@@ -141,29 +142,34 @@ const EmailList = ({ data, onRemove, setEmails }: EmailListProps) => {
t,
i18n: { language },
} = useTranslation('common')
+ const { id: projectId } = useParams()
+ const fetcher = useFetcher<ProjectSettingsActionData>()
const [open, setOpen] = useState(false)
const openRef = useRef<HTMLUListElement>(null)
useOnClickOutside(openRef, () => setOpen(false))
- const { id, addedAt, isConfirmed, projectId, email, reportFrequency } = data || {}
-
- const changeRole = async (reportType: { value: string; label: string }) => {
- try {
- const results = await updateSubscriber(projectId, id, { reportFrequency: reportType.value })
- setEmails((prev) => {
- const newEmails = _map(prev, (item) => {
- if (item.id === results.id) {
- return results
- }
- return item
- })
- return newEmails
- })
- toast.success(t('apiNotifications.updatedPeriodEmailReports'))
- } catch (reason: any) {
- console.error(`[ERROR] Error while updating user's role: ${reason}`)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.updatedPeriodEmailReportsError'))
+ const { id, addedAt, isConfirmed, email, reportFrequency } = data || {}
+
+ useEffect(() => {
+ if (fetcher.data?.intent === 'update-subscriber') {
+ if (fetcher.data.success && fetcher.data.subscriber) {
+ const updated = fetcher.data.subscriber
+ setEmails((prev) => _map(prev, (item) => (item.id === updated.id ? updated : item)))
+ toast.success(t('apiNotifications.updatedPeriodEmailReports'))
+ } else if (fetcher.data.error) {
+ toast.error(
+ typeof fetcher.data.error === 'string'
+ ? fetcher.data.error
+ : t('apiNotifications.updatedPeriodEmailReportsError'),
+ )
+ }
}
+ }, [fetcher.data, setEmails, t])
+ const changeRole = (reportType: { value: string; label: string }) => {
+ fetcher.submit(
+ { intent: 'update-subscriber', subscriberId: id, reportFrequency: reportType.value },
+ { method: 'post', action: `/projects/settings/${projectId}` },
+ )
setOpen(false)
}
@@ -254,6 +260,9 @@ const NoSubscribers = () => {
const Emails = ({ projectId }: { projectId: string }) => {
const [showModal, setShowModal] = useState(false)
const { t } = useTranslation('common')
+ const fetcher = useFetcher<ProjectSettingsActionData>()
+ const loadFetcher = useFetcher<ProjectSettingsActionData>()
+ const removeFetcher = useFetcher<ProjectSettingsActionData>()
const [form, setForm] = useState<{
email: string
reportFrequency: string
@@ -276,28 +285,61 @@ const Emails = ({ projectId }: { projectId: string }) => {
})
const [showDeleteModal, setShowDeleteModal] = useState(false)
- const [isDeleting, setIsDeleting] = useState(false)
const [emailToRemove, setEmailToRemove] = useState<Subscriber | null>(null)
+ const removingEmailId = useRef<string | null>(null)
- const getSubcribersAsync = async () => {
- try {
- const { subscribers, count } = await getSubscribers(projectId, pagination.page - 1, pagination.limit)
- setPagination((oldPaggination) => ({
- ...oldPaggination,
- count,
- }))
- setEmails(subscribers)
- } catch (reason) {
- console.error(`[ERROR] Error while getting subscribers: ${reason}`)
- } finally {
- setLoading(false)
- }
- }
+ const isDeleting = removeFetcher.state !== 'idle'
useEffect(() => {
- getSubcribersAsync()
+ loadFetcher.submit(
+ { intent: 'get-subscribers', offset: String(pagination.page - 1), limit: String(pagination.limit) },
+ { method: 'post', action: `/projects/settings/${projectId}` },
+ )
}, []) // eslint-disable-line
+ useEffect(() => {
+ if (loadFetcher.data?.intent === 'get-subscribers') {
+ if (loadFetcher.data.success) {
+ setTimeout(() => {
+ setEmails(loadFetcher.data!.subscribers || [])
+ setPagination((old) => ({ ...old, total: loadFetcher.data!.subscribersCount || 0 }))
+ }, 0)
+ }
+ setTimeout(() => setLoading(false), 0)
+ }
+ }, [loadFetcher.data])
+
+ useEffect(() => {
+ if (fetcher.data?.intent === 'add-subscriber') {
+ if (fetcher.data.success && fetcher.data.subscriber) {
+ setTimeout(() => setEmails((prev) => [...prev, fetcher.data!.subscriber!]), 0)
+ toast.success(t('apiNotifications.userInvited'))
+ } else if (fetcher.data.error) {
+ toast.error(typeof fetcher.data.error === 'string' ? fetcher.data.error : t('apiNotifications.userInviteError'))
+ }
+ }
+ }, [fetcher.data, t])
+
+ useEffect(() => {
+ if (removeFetcher.state === 'idle' && removeFetcher.data?.intent === 'remove-subscriber') {
+ if (removeFetcher.data.success) {
+ const capturedId = removingEmailId.current
+ setTimeout(() => {
+ setEmails((prev) => _filter(prev, (s) => s.id !== capturedId))
+ setShowDeleteModal(false)
+ setEmailToRemove(null)
+ }, 0)
+ removingEmailId.current = null
+ } else if (removeFetcher.data.error) {
+ toast.error(
+ typeof removeFetcher.data.error === 'string'
+ ? removeFetcher.data.error
+ : t('apiNotifications.somethingWentWrong'),
+ )
+ }
+ }
+ }, [removeFetcher.data, removeFetcher.state, t])
+
const validate = () => {
const allErrors: {
email?: string
@@ -316,7 +358,7 @@ const Emails = ({ projectId }: { projectId: string }) => {
useEffect(() => {
if (showModal) {
- validate()
+ setTimeout(() => validate(), 0)
}
}, [form]) // eslint-disable-line
@@ -329,22 +371,18 @@ const Emails = ({ projectId }: { projectId: string }) => {
}))
}
- const onSubmit = async () => {
+ const onSubmit = () => {
setShowModal(false)
+ setBeenSubmitted(false)
setErrors({})
setValidated(false)
- try {
- const results = await addSubscriber(projectId, { reportFrequency: form.reportFrequency, email: form.email })
- setEmails([...emails, results])
- toast.success(t('apiNotifications.userInvited'))
- } catch (reason) {
- console.error(`[ERROR] Error while inviting a user: ${reason}`)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.userInviteError'))
- }
+ fetcher.submit(
+ { intent: 'add-subscriber', email: form.email, reportFrequency: form.reportFrequency },
+ { method: 'post', action: `/projects/settings/${projectId}` },
+ )
- // a timeout is needed to prevent the flicker of data fields in the modal when closing
- setTimeout(() => setForm({ email: '', reportFrequency: '' }), 300)
+ setTimeout(() => setForm({ email: '', reportFrequency: reportFrequencyForEmailsOptions[3].value }), 300)
}
const handleSubmit = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
@@ -361,28 +399,22 @@ const Emails = ({ projectId }: { projectId: string }) => {
const closeModal = () => {
setShowModal(false)
+ setBeenSubmitted(false)
// a timeout is needed to prevent the flicker of data fields in the modal when closing
- setTimeout(() => setForm({ email: '', reportFrequency: '' }), 300)
+ setTimeout(() => setForm({ email: '', reportFrequency: reportFrequencyForEmailsOptions[3].value }), 300)
setErrors({})
}
- const onRemove = async (emailId: string) => {
+ const onRemove = (emailId: string) => {
if (isDeleting) {
return
}
- setIsDeleting(true)
-
- try {
- await removeSubscriber(projectId, emailId)
- const results = _filter(emails, (s) => s.id !== emailId)
- setEmails(results)
- } catch (reason: any) {
- console.error(`[ERROR] Error while deleting a email: ${reason}`)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- } finally {
- setIsDeleting(false)
- }
+ removingEmailId.current = emailId
+ removeFetcher.submit(
+ { intent: 'remove-subscriber', subscriberId: emailId },
+ { method: 'post', action: `/projects/settings/${projectId}` },
+ )
}
return (
@@ -464,10 +496,9 @@ const Emails = ({ projectId }: { projectId: string }) => {
setShowDeleteModal(false)
setEmailToRemove(null)
}}
- onSubmit={async () => {
- await onRemove(emailToRemove!.id)
- setEmailToRemove(null)
- setShowDeleteModal(false)
+ onSubmit={() => {
+ if (!emailToRemove) return
+ onRemove(emailToRemove.id)
}}
submitText={t('common.yes')}
type='confirmed'
diff --git a/web/app/pages/Project/Settings/People/People.tsx b/web/app/pages/Project/Settings/People/People.tsx
index 13fa5a8b5..95841df5e 100644
--- a/web/app/pages/Project/Settings/People/People.tsx
+++ b/web/app/pages/Project/Settings/People/People.tsx
@@ -7,15 +7,16 @@ import _map from 'lodash/map'
import { Trash2Icon, UserRoundPlusIcon } from 'lucide-react'
import React, { useState, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher, useRevalidator } from 'react-router'
import { toast } from 'sonner'
-import { deleteShareProjectUsers, shareProject, changeShareRole } from '~/api'
import useOnClickOutside from '~/hooks/useOnClickOutside'
import { roles, INVITATION_EXPIRES_IN, isSelfhosted } from '~/lib/constants'
import { Role } from '~/lib/models/Organisation'
import { Project, ShareOwnerProject } from '~/lib/models/Project'
import PaidFeature from '~/modals/PaidFeature'
import { useAuth } from '~/providers/AuthProvider'
+import { ProjectSettingsActionData } from '~/routes/projects.settings.$id'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
@@ -39,26 +40,36 @@ interface TableUserRowProps {
onRemove: () => void
language: string
authedUserEmail: string | undefined
- reloadProject: () => Promise<void>
+ projectId: string
}
-const TableUserRow = ({ data, onRemove, language, authedUserEmail, reloadProject }: TableUserRowProps) => {
+const TableUserRow = ({ data, onRemove, language, authedUserEmail, projectId }: TableUserRowProps) => {
const { t } = useTranslation('common')
const [open, setOpen] = useState(false)
const openRef = useRef<HTMLUListElement>(null)
useOnClickOutside(openRef, () => setOpen(false))
+ const fetcher = useFetcher<ProjectSettingsActionData>()
+ const revalidator = useRevalidator()
const { id, created, confirmed, role, user } = data || {}
- const changeRole = async (newRole: string) => {
- try {
- await changeShareRole(id, { role: newRole })
- await reloadProject()
- toast.success(t('apiNotifications.roleUpdated'))
- } catch (reason) {
- console.error(`[ERROR] Error while updating user's role: ${reason}`)
- toast.error(t('apiNotifications.roleUpdateError'))
+ useEffect(() => {
+ if (fetcher.state === 'idle' && fetcher.data) {
+ if (fetcher.data.intent === 'change-share-role') {
+ if (fetcher.data.success) {
+ toast.success(t('apiNotifications.roleUpdated'))
+ revalidator.revalidate()
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ }
}
+ }, [fetcher.state, fetcher.data, t, revalidator])
+ const changeRole = (newRole: string) => {
+ fetcher.submit(
+ { intent: 'change-share-role', shareId: id, role: newRole },
+ { method: 'POST', action: `/projects/settings/${projectId}` },
+ )
setOpen(false)
}
@@ -140,11 +151,11 @@ const TableUserRow = ({ data, onRemove, language, authedUserEmail, reloadProject
interface PeopleProps {
project: Project
- reloadProject: () => Promise<void>
}
-const People = ({ project, reloadProject }: PeopleProps) => {
+const People = ({ project }: PeopleProps) => {
const { user: currentUser } = useAuth()
+ const fetcher = useFetcher<ProjectSettingsActionData>()
const [showModal, setShowModal] = useState(false)
const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)
@@ -167,11 +178,41 @@ const People = ({ project, reloadProject }: PeopleProps) => {
const [validated, setValidated] = useState(false)
const [showDeleteModal, setShowDeleteModal] = useState(false)
- const [isDeleting, setIsDeleting] = useState(false)
const [memberToRemove, setMemberToRemove] = useState<ShareOwnerProject | null>(null)
const { id, name, share } = project
+ const isSubmitting = fetcher.state !== 'idle'
+
+ useEffect(() => {
+ if (fetcher.state === 'idle' && fetcher.data) {
+ if (fetcher.data.intent === 'share-project') {
+ if (fetcher.data.success) {
+ toast.success(t('apiNotifications.userInvited'))
+ setTimeout(() => {
+ setShowModal(false)
+ setBeenSubmitted(false)
+ setErrors({})
+ setValidated(false)
+ }, 0)
+ setTimeout(() => setForm({ email: '', role: 'viewer' }), 300)
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ } else if (fetcher.data.intent === 'delete-share-user') {
+ if (fetcher.data.success) {
+ toast.success(t('apiNotifications.userRemoved'))
+ setTimeout(() => {
+ setShowDeleteModal(false)
+ setMemberToRemove(null)
+ }, 0)
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ }
+ }
+ }, [fetcher.state, fetcher.data, t])
+
const validate = () => {
const allErrors: {
email?: string
@@ -194,7 +235,7 @@ const People = ({ project, reloadProject }: PeopleProps) => {
useEffect(() => {
if (showModal) {
- validate()
+ setTimeout(() => validate(), 0)
}
}, [form]) // eslint-disable-line
@@ -207,22 +248,11 @@ const People = ({ project, reloadProject }: PeopleProps) => {
}))
}
- const onSubmit = async () => {
- setShowModal(false)
- setErrors({})
- setValidated(false)
-
- try {
- await shareProject(id, { email: form.email, role: form.role })
- await reloadProject()
- toast.success(t('apiNotifications.userInvited'))
- } catch (reason) {
- console.error(`[ERROR] Error while inviting a user: ${reason}`)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.userInviteError'))
- }
-
- // a timeout is needed to prevent the flicker of data fields in the modal when closing
- setTimeout(() => setForm({ email: '', role: 'viewer' }), 300)
+ const onSubmit = () => {
+ fetcher.submit(
+ { intent: 'share-project', email: form.email, role: form.role },
+ { method: 'POST', action: `/projects/settings/${id}` },
+ )
}
const handleSubmit = (e: React.MouseEvent<HTMLButtonElement>) => {
@@ -239,28 +269,17 @@ const People = ({ project, reloadProject }: PeopleProps) => {
const closeModal = () => {
setShowModal(false)
+ setBeenSubmitted(false)
// a timeout is needed to prevent the flicker of data fields in the modal when closing
setTimeout(() => setForm({ email: '', role: 'viewer' }), 300)
setErrors({})
}
- const onRemove = async (member: ShareOwnerProject) => {
- if (isDeleting) {
- return
- }
-
- setIsDeleting(true)
-
- try {
- await deleteShareProjectUsers(id, member.id)
- await reloadProject()
- toast.success(t('apiNotifications.userRemoved'))
- } catch (reason) {
- console.error(`[ERROR] Error while deleting a user: ${reason}`)
- toast.error(t('apiNotifications.userRemoveError'))
- } finally {
- setIsDeleting(false)
- }
+ const onRemove = (member: ShareOwnerProject) => {
+ fetcher.submit(
+ { intent: 'delete-share-user', shareId: member.id },
+ { method: 'POST', action: `/projects/settings/${id}` },
+ )
}
return (
@@ -313,7 +332,7 @@ const People = ({ project, reloadProject }: PeopleProps) => {
}}
language={language}
authedUserEmail={currentUser?.email}
- reloadProject={reloadProject}
+ projectId={id}
/>
))}
</tbody>
@@ -328,8 +347,8 @@ const People = ({ project, reloadProject }: PeopleProps) => {
setMemberToRemove(null)
}}
onSubmit={() => {
- setShowDeleteModal(false)
- onRemove(memberToRemove!)
+ if (!memberToRemove) return
+ onRemove(memberToRemove)
}}
submitText={t('common.yes')}
type='confirmed'
@@ -337,7 +356,7 @@ const People = ({ project, reloadProject }: PeopleProps) => {
title={t('project.settings.removeUser', { user: memberToRemove?.user?.email })}
message={t('project.settings.removeConfirm')}
isOpened={showDeleteModal}
- isLoading={isDeleting}
+ isLoading={isSubmitting ? fetcher.formData?.get('intent') === 'delete-share-user' : undefined}
/>
<Modal
onClose={closeModal}
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index f892eb2f0..7290f7058 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -8,7 +8,6 @@ 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 _toUpper from 'lodash/toUpper'
import {
Settings2Icon,
@@ -23,33 +22,17 @@ import {
ShieldCheckIcon,
DollarSignIcon,
} from 'lucide-react'
-import React, { useState, useEffect, useMemo, useCallback } from 'react'
+import React, { useState, useEffect, useMemo, useRef } from 'react'
import { Trans, useTranslation } from 'react-i18next'
-import { useLoaderData, useNavigate, Link, useSearchParams } from 'react-router'
+import { useLoaderData, useNavigate, Link, useSearchParams, useFetcher } from 'react-router'
import { toast } from 'sonner'
-import {
- updateProject,
- deleteProject,
- resetProject,
- transferProject,
- deletePartially,
- getFilters,
- resetFilters,
- getProject,
- assignProjectToOrganisation,
- generateGSCAuthURL,
- getGSCStatus,
- getGSCProperties,
- setGSCProperty,
- disconnectGSC,
- reGenerateCaptchaSecretKey,
-} from '~/api'
-import { withAuthentication, auth } from '~/hoc/protected'
+import { useFiltersProxy } from '~/hooks/useAnalyticsProxy'
import { useRequiredParams } from '~/hooks/useRequiredParams'
import { isSelfhosted, TITLE_SUFFIX, FILTERS_PANELS_ORDER, isBrowser } from '~/lib/constants'
import { Project } from '~/lib/models/Project'
import { useAuth } from '~/providers/AuthProvider'
+import type { ProjectSettingsActionData } from '~/routes/projects.settings.$id'
import Button from '~/ui/Button'
import DatePicker from '~/ui/Datepicker'
import Dropdown from '~/ui/Dropdown'
@@ -60,13 +43,11 @@ import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
import MultiSelect from '~/ui/MultiSelect'
import Select from '~/ui/Select'
-import StatusPage from '~/ui/StatusPage'
// Select is used inside tab components
import countries from '~/utils/isoCountries'
import routes from '~/utils/routes'
import CCRow from '../View/components/CCRow'
-import { getFormatDate } from '../View/ViewProject.helpers'
import Annotations from './Annotations'
import Emails from './Emails'
@@ -106,6 +87,7 @@ interface ModalMessageProps {
setActiveFilter: any
filterType: string
setFilterType: (a: string) => void
+ fetchFilters: (projectId: string, filterType: string) => Promise<string[] | null>
}
const ModalMessage = ({
@@ -118,6 +100,7 @@ const ModalMessage = ({
setActiveFilter,
filterType,
setFilterType,
+ fetchFilters,
}: ModalMessageProps) => {
const {
t,
@@ -128,9 +111,9 @@ const ModalMessage = ({
const getFiltersList = async () => {
if (!_isEmpty(filterType)) {
- const res = await getFilters(pid, filterType)
- setFilterList(res)
- setSearchList(res)
+ const res = await fetchFilters(pid, filterType)
+ setFilterList(res || [])
+ setSearchList(res || [])
if (!_isEmpty(activeFilter)) {
setActiveFilter([])
}
@@ -279,26 +262,34 @@ interface Form extends Partial<Project> {
const DEFAULT_PROJECT_NAME = 'Untitled Project'
const ProjectSettings = () => {
- const { user, isLoading: authLoading } = useAuth()
+ const { user } = useAuth()
const { t } = useTranslation('common')
const { id } = useRequiredParams<{ id: string }>()
const navigate = useNavigate()
- const { requestOrigin } = useLoaderData<{ requestOrigin: string | null }>()
-
- const [project, setProject] = useState<Project | null>(null)
- const [form, setForm] = useState<Form>({
- name: '',
- id,
- public: false,
- isPasswordProtected: false,
- origins: null,
- ipBlacklist: null,
- countryBlacklist: [],
- botsProtectionLevel: 'basic',
- gscPropertyUri: null,
- websiteUrl: null,
- })
+ const { project: initialProject, requestOrigin } = useLoaderData<{
+ project: Project
+ requestOrigin: string | null
+ }>()
+ const fetcher = useFetcher<ProjectSettingsActionData>()
+ const gscFetcher = useFetcher<ProjectSettingsActionData>()
+ const { fetchFilters } = useFiltersProxy()
+
+ const [project, setProject] = useState<Project>(initialProject)
+ const [form, setForm] = useState<Form>(() => ({
+ name: initialProject.name || '',
+ id: initialProject.id,
+ public: initialProject.public || false,
+ isPasswordProtected: initialProject.isPasswordProtected || false,
+ origins: _isString(initialProject.origins) ? initialProject.origins : _join(initialProject.origins, ', '),
+ ipBlacklist: _isString(initialProject.ipBlacklist)
+ ? initialProject.ipBlacklist
+ : _join(initialProject.ipBlacklist, ', '),
+ countryBlacklist: initialProject.countryBlacklist || [],
+ botsProtectionLevel: (initialProject.botsProtectionLevel as 'off' | 'basic') || 'basic',
+ gscPropertyUri: initialProject.gscPropertyUri || null,
+ websiteUrl: initialProject.websiteUrl || null,
+ }))
const [validated, setValidated] = useState(false)
const [errors, setErrors] = useState<{
name?: string
@@ -306,12 +297,14 @@ const ProjectSettings = () => {
ipBlacklist?: string
password?: string
websiteUrl?: string
+ transferEmail?: string
+ email?: string
}>({})
const [beenSubmitted, setBeenSubmitted] = useState(false)
const [showDelete, setShowDelete] = useState(false)
const [showReset, setShowReset] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
- const [setResetting, setIsResetting] = useState(false)
+ const [isResetting, setIsResetting] = useState(false)
const [isSaving, setIsSaving] = useState(false)
const [showTransfer, setShowTransfer] = useState(false)
const [transferEmail, setTransferEmail] = useState('')
@@ -319,8 +312,6 @@ const ProjectSettings = () => {
const [tab, setTab] = useState(DELETE_DATA_MODAL_TABS[0].name)
const [showProtected, setShowProtected] = useState(false)
- const [isLoading, setIsLoading] = useState<boolean | null>(null)
- const [error, setError] = useState<string | null>(null)
const [searchParams, setSearchParams] = useSearchParams()
type SettingsTab =
@@ -390,10 +381,9 @@ const ProjectSettings = () => {
const [gscEmail, setGscEmail] = useState<string | null>(null)
// CAPTCHA state
- const [captchaSecretKey, setCaptchaSecretKey] = useState<string | null>(null)
+ const [captchaSecretKey, setCaptchaSecretKey] = useState<string | null>(() => initialProject.captchaSecretKey || null)
const [captchaDifficulty, setCaptchaDifficulty] = useState<number>(4)
const [showRegenerateSecret, setShowRegenerateSecret] = useState(false)
- const [isSavingDifficulty, setIsSavingDifficulty] = useState(false)
// for reset data via filters
const [activeFilter, setActiveFilter] = useState<string[]>([])
@@ -425,171 +415,235 @@ const ProjectSettings = () => {
[user?.organisationMemberships, t],
)
- const assignOrganisation = async (organisationId?: string) => {
- try {
- await assignProjectToOrganisation(id, organisationId)
- toast.success(t('apiNotifications.projectAssigned'))
- } catch (reason: any) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.projectAssignError'))
- }
+ const assignOrganisation = async (organisationId?: string): Promise<void> => {
+ const formData = new FormData()
+ formData.set('intent', 'assign-organisation')
+ if (organisationId) formData.set('organisationId', organisationId)
+ fetcher.submit(formData, { method: 'post' })
}
const sharableLink = useMemo(() => {
- const origin = requestOrigin || isBrowser ? window.location.origin : 'https://swetrix.com'
+ const origin = requestOrigin ?? (isBrowser ? window.location.origin : 'https://swetrix.com')
return `${origin}/projects/${id}`
}, [requestOrigin, id])
- const loadProject = async (projectId: string) => {
- if (isLoading) {
- return
- }
- setIsLoading(true)
-
- try {
- const result = await getProject(projectId)
- setProject(result)
- setCaptchaSecretKey(result.captchaSecretKey)
- setCaptchaDifficulty(result.captchaDifficulty || 4)
- setForm({
- ...result,
- ipBlacklist: _isString(result.ipBlacklist) ? result.ipBlacklist : _join(result.ipBlacklist, ', '),
- origins: _isString(result.origins) ? result.origins : _join(result.origins, ', '),
- countryBlacklist: result.countryBlacklist || [],
- websiteUrl: result.websiteUrl || null,
- })
- } catch (reason: any) {
- setError(reason)
- } finally {
- setIsLoading(false)
- }
- }
+ const [gscPropertiesPending, setGscPropertiesPending] = useState(false)
+ const lastHandledGscData = useRef<ProjectSettingsActionData | null>(null)
+ const gscInitialized = useRef(false)
- const refreshGSCStatus = useCallback(async () => {
- if (isSelfhosted) {
- return
- }
+ // Handle GSC fetcher responses
+ useEffect(() => {
+ if (gscFetcher.state !== 'idle' || !gscFetcher.data) return
+
+ // Prevent handling the same response twice
+ if (lastHandledGscData.current === gscFetcher.data) return
+ lastHandledGscData.current = gscFetcher.data
+
+ const { intent, success, gscStatus, gscProperties: properties, gscAuthUrl, error: gscError } = gscFetcher.data
+
+ if (success) {
+ if (intent === 'gsc-status' && gscStatus) {
+ setGscConnected(gscStatus.connected)
+ setGscEmail(gscStatus.email || null)
+ if (gscStatus.connected) {
+ setGscPropertiesPending(true)
+ } else {
+ setGscProperties([])
+ }
+ } else if (intent === 'gsc-properties' && properties) {
+ setGscProperties(properties)
+ setGscPropertiesPending(false)
+ } else if (intent === 'gsc-connect' && gscAuthUrl) {
+ const safeUrl = (() => {
+ try {
+ const parsed = new URL(gscAuthUrl)
+ if (parsed.protocol !== 'https:') return null
+ if (parsed.username || parsed.password) return null
+ if (parsed.hostname !== 'accounts.google.com') return null
+ return parsed.toString()
+ } catch {
+ return null
+ }
+ })()
- try {
- const { connected, email } = await getGSCStatus(id)
- setGscConnected(connected)
- setGscEmail(email || null)
- if (connected) {
- try {
- const props = await getGSCProperties(id)
- setGscProperties(props)
- } catch {
- //
+ if (!safeUrl) {
+ toast.error(t('apiNotifications.somethingWentWrong'))
+ return
}
- } else {
+
+ window.location.href = safeUrl
+ } else if (intent === 'gsc-disconnect') {
+ setGscConnected(false)
setGscProperties([])
+ setGscEmail(null)
+ setForm((prevForm) => ({
+ ...prevForm,
+ gscPropertyUri: null,
+ }))
+ toast.success(t('project.settings.gsc.disconnected'))
+ } else if (intent === 'gsc-set-property') {
+ toast.success(t('project.settings.gsc.propertyConnected'))
}
- } catch {
- setGscConnected(false)
+ } else if (gscError) {
+ toast.error(typeof gscError === 'string' ? gscError : t('apiNotifications.somethingWentWrong'))
+ setGscPropertiesPending(false)
}
- }, [id])
+ }, [gscFetcher.state, gscFetcher.data, t])
+ // Fetch GSC properties after status confirms connected
useEffect(() => {
- refreshGSCStatus()
- }, [refreshGSCStatus])
+ if (gscPropertiesPending && gscFetcher.state === 'idle') {
+ setGscPropertiesPending(false)
+ gscFetcher.submit({ intent: 'gsc-properties' }, { method: 'post' })
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [gscPropertiesPending, gscFetcher.state])
+ // Initial GSC status fetch
useEffect(() => {
- if (authLoading) {
- return
- }
+ if (isSelfhosted || gscInitialized.current) return
+ gscInitialized.current = true
+ gscFetcher.submit({ intent: 'gsc-status' }, { method: 'post' })
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
- loadProject(id)
+ // Handle fetcher responses
+ useEffect(() => {
+ if (fetcher.data?.success) {
+ const { intent, project: updatedProject } = fetcher.data
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [authLoading, id])
+ setErrors({})
- const onSubmit = async (data: Form) => {
- if (!isSaving) {
- setIsSaving(true)
- try {
- const formalisedData = {
- ...data,
- origins: _isEmpty(data.origins)
- ? null
- : _map(_split(data.origins, ','), (origin) => {
- try {
- if (_includes(origin, 'localhost')) {
- return origin
- }
- return new URL(origin).host
- } catch {
- return origin
- }
- }),
- ipBlacklist: _isEmpty(data.ipBlacklist) ? null : _split(data.ipBlacklist, ','),
- countryBlacklist: _isEmpty(data.countryBlacklist) ? null : data.countryBlacklist,
+ if (intent === 'update-project') {
+ if (updatedProject) {
+ // Merge with existing project to preserve fields like 'role' that aren't returned from update
+ setProject((prev) => (prev ? { ...prev, ...updatedProject } : updatedProject))
}
- await updateProject(id, formalisedData as Partial<Project>)
+ setBeenSubmitted(false)
toast.success(t('project.settings.updated'))
- } catch (reason: any) {
- toast.error(reason)
- } finally {
- setIsSaving(false)
+ } else if (intent === 'delete-project') {
+ toast.success(t('project.settings.deleted'))
+ navigate(routes.dashboard)
+ } else if (intent === 'reset-project' || intent === 'delete-partially' || intent === 'reset-filters') {
+ toast.success(t('project.settings.resetSuccess'))
+ setShowReset(false)
+ } else if (intent === 'transfer-project') {
+ toast.success(t('apiNotifications.transferRequestSent'))
+ setShowTransfer(false)
+ setTransferEmail('')
+ } else if (intent === 'regenerate-captcha-key' && updatedProject?.captchaSecretKey) {
+ setCaptchaSecretKey(updatedProject.captchaSecretKey)
+ toast.success(t('project.settings.updated'))
+ } else if (intent === 'assign-organisation') {
+ toast.success(t('apiNotifications.projectAssigned'))
}
+
+ setIsSaving(false)
+ setIsDeleting(false)
+ setIsResetting(false)
+ } else if (fetcher.data?.fieldErrors) {
+ setErrors(fetcher.data.fieldErrors)
+ setIsSaving(false)
+ setIsDeleting(false)
+ setIsResetting(false)
+ } else if (fetcher.data?.error) {
+ toast.error(fetcher.data.error)
+ setIsSaving(false)
+ setIsDeleting(false)
+ setIsResetting(false)
}
+ }, [fetcher.data, t, navigate])
+
+ const onSubmit = (data: Form) => {
+ if (fetcher.state === 'submitting') return
+
+ setIsSaving(true)
+ const formData = new FormData()
+ formData.set('intent', 'update-project')
+ if (data.name) formData.set('name', data.name)
+ formData.set('public', data.public ? 'true' : 'false')
+ formData.set('isPasswordProtected', data.isPasswordProtected ? 'true' : 'false')
+ if (data.password) formData.set('password', data.password)
+ if (data.origins !== null) formData.set('origins', data.origins)
+ if (data.ipBlacklist !== null) formData.set('ipBlacklist', data.ipBlacklist)
+ if (data.botsProtectionLevel) formData.set('botsProtectionLevel', data.botsProtectionLevel)
+ if (data.countryBlacklist) formData.set('countryBlacklist', JSON.stringify(data.countryBlacklist))
+ if (data.websiteUrl !== undefined) formData.set('websiteUrl', data.websiteUrl || '')
+
+ fetcher.submit(formData, { method: 'post' })
}
- const onDelete = async () => {
+ const onDelete = () => {
setShowDelete(false)
- if (isDeleting) {
- return
- }
+ if (fetcher.state === 'submitting') return
setIsDeleting(true)
- try {
- await deleteProject(id)
- toast.success(t('project.settings.deleted'))
- navigate(routes.dashboard)
- } catch (reason: any) {
- toast.error(reason)
- } finally {
- setIsDeleting(false)
- }
+ const formData = new FormData()
+ formData.set('intent', 'delete-project')
+ fetcher.submit(formData, { method: 'post' })
}
- const onReset = async () => {
- setShowReset(false)
+ const onReset = (resetTab: string, dateRange?: Date[], filterType?: string, filterValue?: string[]) => {
+ if (fetcher.state === 'submitting') return
- if (setResetting) {
- return
+ setIsResetting(true)
+ const formData = new FormData()
+
+ if (resetTab === 'all') {
+ formData.set('intent', 'reset-project')
+ } else if (resetTab === 'partially' && dateRange) {
+ formData.set('intent', 'delete-partially')
+ formData.set('from', dateRange[0]?.toISOString() || '')
+ formData.set('to', dateRange[1]?.toISOString() || '')
+ } else if (resetTab === 'viaFilters' && filterType && filterValue && filterValue.length > 0) {
+ formData.set('intent', 'reset-filters')
+ formData.set('type', filterType)
+ formData.set('value', JSON.stringify(filterValue))
}
- setIsResetting(true)
+ fetcher.submit(formData, { method: 'post' })
+ }
- try {
- if (tab === DELETE_DATA_MODAL_TABS[1].name) {
- if (_isEmpty(dateRange)) {
- toast.error(t('project.settings.noDateRange'))
- setIsResetting(false)
- return
- }
- await deletePartially(id, {
- from: getFormatDate(dateRange[0]),
- to: getFormatDate(dateRange[1]),
- })
- } else if (tab === DELETE_DATA_MODAL_TABS[2].name) {
- if (_isEmpty(activeFilter)) {
- toast.error(t('project.settings.noFilters'))
- setIsResetting(false)
- return
- }
+ const onTransfer = () => {
+ if (fetcher.state === 'submitting') return
+
+ const formData = new FormData()
+ formData.set('intent', 'transfer-project')
+ formData.set('email', transferEmail)
+ fetcher.submit(formData, { method: 'post' })
+ }
+
+ const onRegenerateCaptchaKey = () => {
+ if (fetcher.state === 'submitting') return
+
+ const formData = new FormData()
+ formData.set('intent', 'regenerate-captcha-key')
+ fetcher.submit(formData, { method: 'post' })
+ }
- await resetFilters(id, filterType, activeFilter)
- } else {
- await resetProject(id)
+ // Wrapper for reset that handles tab logic
+ const handleReset = () => {
+ if (fetcher.state === 'submitting') return
+
+ if (tab === DELETE_DATA_MODAL_TABS[1].name) {
+ if (_isEmpty(dateRange) || !dateRange[0] || !dateRange[1]) {
+ toast.error(t('project.settings.noDateRange'))
+ return
}
- toast.success(t('project.settings.projectReset'))
- navigate(routes.dashboard)
- } catch (reason: any) {
- toast.error(reason)
- } finally {
- setIsResetting(false)
+ setShowReset(false)
+ onReset('partially', dateRange)
+ } else if (tab === DELETE_DATA_MODAL_TABS[2].name) {
+ if (_isEmpty(activeFilter) || _isEmpty(filterType)) {
+ toast.error(t('project.settings.noFilters'))
+ return
+ }
+ setShowReset(false)
+ onReset('viaFilters', undefined, filterType, activeFilter)
+ } else if (tab === DELETE_DATA_MODAL_TABS[0].name) {
+ setShowReset(false)
+ onReset('all')
}
}
@@ -660,21 +714,6 @@ const ProjectSettings = () => {
}
}
- const onTransfer = async () => {
- await transferProject(id, transferEmail)
- .then(() => {
- toast.success(t('apiNotifications.transferRequestSent'))
- navigate(routes.dashboard)
- })
- .catch((reason) => {
- toast.error(reason)
- })
- .finally(() => {
- setShowTransfer(false)
- setTransferEmail('')
- })
- }
-
const onProtected = async () => {
setBeenSubmitted(true)
@@ -693,15 +732,6 @@ const ProjectSettings = () => {
}
}
- const reloadProject = useCallback(async () => {
- try {
- const result = await getProject(id)
- setProject(result)
- } catch (reason: any) {
- console.error(`[ERROR] Error while reloading project: ${reason}`)
- }
- }, [id])
-
const title = `${t('project.settings.settings')} ${form.name}`
useEffect(() => {
@@ -712,28 +742,6 @@ const ProjectSettings = () => {
return (tabs.find((t) => t.id === activeTab)?.label as string) || ''
}, [tabs, activeTab])
- if (error && !isLoading) {
- return (
- <StatusPage
- type='error'
- title={t('apiNotifications.somethingWentWrong')}
- description={t('apiNotifications.errorCode', { error })}
- actions={[
- { label: t('dashboard.reloadPage'), onClick: () => window.location.reload(), primary: true },
- { label: t('notFoundPage.support'), to: routes.contact },
- ]}
- />
- )
- }
-
- 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>
- )
- }
-
return (
<div className='flex min-h-min-footer flex-col bg-gray-50 pb-40 dark:bg-slate-900'>
<div className='mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8'>
@@ -857,7 +865,7 @@ const ProjectSettings = () => {
) : null}
{activeTab === 'emails' && !isSelfhosted ? <Emails projectId={id} /> : null}
- {activeTab === 'people' ? <People project={project} reloadProject={reloadProject} /> : null}
+ {activeTab === 'people' ? <People project={project} /> : null}
{activeTab === 'annotations' ? (
<Annotations projectId={id} allowedToManage={project?.role === 'owner' || project?.role === 'admin'} />
) : null}
@@ -877,32 +885,12 @@ const ProjectSettings = () => {
<Button
className='flex items-center gap-2'
type='button'
- onClick={async () => {
- try {
- const { url } = await generateGSCAuthURL(id)
- const safeUrl = (() => {
- try {
- const parsed = new URL(url)
- if (parsed.protocol !== 'https:') return null
- if (parsed.username || parsed.password) return null
- // Google OAuth consent screen
- if (parsed.hostname !== 'accounts.google.com') return null
- return parsed.toString()
- } catch {
- return null
- }
- })()
-
- if (!safeUrl) {
- toast.error(t('apiNotifications.somethingWentWrong'))
- return
- }
-
- window.location.href = safeUrl
- } catch (reason: any) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- }
+ onClick={() => {
+ gscFetcher.submit({ intent: 'gsc-connect' }, { method: 'post' })
}}
+ loading={
+ gscFetcher.state !== 'idle' ? gscFetcher.formData?.get('intent') === 'gsc-connect' : undefined
+ }
primary
regular
>
@@ -924,21 +912,14 @@ const ProjectSettings = () => {
className='max-w-max'
semiDanger
regular
- onClick={async () => {
- try {
- await disconnectGSC(id)
- setGscConnected(false)
- setGscProperties([])
- setGscEmail(null)
- setForm((prevForm) => ({
- ...prevForm,
- gscPropertyUri: null,
- }))
- toast.success(t('project.settings.gsc.disconnected'))
- } catch (reason: any) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- }
+ onClick={() => {
+ gscFetcher.submit({ intent: 'gsc-disconnect' }, { method: 'post' })
}}
+ loading={
+ gscFetcher.state !== 'idle'
+ ? gscFetcher.formData?.get('intent') === 'gsc-disconnect'
+ : undefined
+ }
>
{t('common.disconnect')}
</Button>
@@ -967,15 +948,18 @@ const ProjectSettings = () => {
<Button
type='button'
className='max-w-max'
- onClick={async () => {
+ onClick={() => {
if (!form.gscPropertyUri) return
- try {
- await setGSCProperty(id, form.gscPropertyUri)
- toast.success(t('project.settings.gsc.propertyConnected'))
- } catch (reason: any) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- }
+ gscFetcher.submit(
+ { intent: 'gsc-set-property', propertyUri: form.gscPropertyUri },
+ { method: 'post' },
+ )
}}
+ loading={
+ gscFetcher.state !== 'idle'
+ ? gscFetcher.formData?.get('intent') === 'gsc-set-property'
+ : undefined
+ }
primary
regular
>
@@ -1070,19 +1054,12 @@ const ProjectSettings = () => {
<Button
type='button'
className='mt-4'
- loading={isSavingDifficulty}
- onClick={async () => {
- setIsSavingDifficulty(true)
- try {
- await updateProject(id, { captchaDifficulty })
- toast.success(t('project.settings.updated'))
- } catch (reason: any) {
- toast.error(
- typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'),
- )
- } finally {
- setIsSavingDifficulty(false)
- }
+ loading={fetcher.state === 'submitting'}
+ onClick={() => {
+ const formData = new FormData()
+ formData.set('intent', 'update-project')
+ formData.set('captchaDifficulty', captchaDifficulty.toString())
+ fetcher.submit(formData, { method: 'post' })
}}
primary
regular
@@ -1096,20 +1073,7 @@ const ProjectSettings = () => {
<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
- >
+ <Button type='button' onClick={onRegenerateCaptchaKey} primary regular>
{t('project.settings.captcha.generateKey')}
</Button>
</>
@@ -1126,7 +1090,7 @@ const ProjectSettings = () => {
setShowReset={setShowReset}
setShowDelete={setShowDelete}
isDeleting={isDeleting}
- setResetting={setResetting}
+ setResetting={isResetting}
/>
) : null}
</section>
@@ -1145,7 +1109,7 @@ const ProjectSettings = () => {
/>
<Modal
onClose={() => setShowReset(false)}
- onSubmit={onReset}
+ onSubmit={handleReset}
size='large'
submitText={t('project.settings.reset')}
closeText={t('common.close')}
@@ -1161,6 +1125,7 @@ const ProjectSettings = () => {
setActiveFilter={setActiveFilter}
filterType={filterType}
setFilterType={setFilterType}
+ fetchFilters={fetchFilters}
/>
}
submitType='danger'
@@ -1225,15 +1190,9 @@ const ProjectSettings = () => {
/>
<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'))
- }
+ onSubmit={() => {
+ setShowRegenerateSecret(false)
+ onRegenerateCaptchaKey()
}}
submitText={t('project.settings.captcha.regenerateKey')}
closeText={t('common.cancel')}
@@ -1247,4 +1206,4 @@ const ProjectSettings = () => {
)
}
-export default withAuthentication(ProjectSettings, auth.authenticated)
+export default ProjectSettings
diff --git a/web/app/pages/Project/Settings/TransferProject/TransferProjectConfirm.tsx b/web/app/pages/Project/Settings/TransferProject/TransferProjectConfirm.tsx
deleted file mode 100644
index 7f555cf87..000000000
--- a/web/app/pages/Project/Settings/TransferProject/TransferProjectConfirm.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { useState, useEffect } from 'react'
-import { useTranslation } from 'react-i18next'
-
-import { confirmTransferProject } from '~/api'
-import StatusPage from '~/ui/StatusPage'
-import routes from '~/utils/routes'
-
-const TransferProjectConfirm = () => {
- const { t } = useTranslation('common')
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState('')
-
- const handleConfirm = async (token: string) => {
- try {
- await confirmTransferProject(token)
- } catch {
- setError(t('apiNotifications.invalidToken'))
- } finally {
- setLoading(false)
- }
- }
-
- useEffect(() => {
- setLoading(true)
- const query = new URLSearchParams(window.location.search)
- const token = query.get('token')
-
- if (!token) {
- setError(t('apiNotifications.invalidToken'))
- setLoading(false)
- return
- }
-
- handleConfirm(token)
- }, []) // eslint-disable-line
-
- if (loading) {
- return <StatusPage loading />
- }
-
- if (error) {
- return (
- <StatusPage
- type='error'
- title={error}
- actions={[
- { label: t('common.dashboard'), to: routes.dashboard, primary: true },
- { label: t('notFoundPage.support'), to: routes.contact },
- ]}
- />
- )
- }
-
- return (
- <StatusPage
- type='success'
- title={t('apiNotifications.acceptInvitation')}
- actions={[{ label: t('common.dashboard'), to: routes.dashboard, primary: true }]}
- />
- )
-}
-
-export default TransferProjectConfirm
diff --git a/web/app/pages/Project/Settings/TransferProject/TransferProjectReject.tsx b/web/app/pages/Project/Settings/TransferProject/TransferProjectReject.tsx
deleted file mode 100644
index 34b3f2219..000000000
--- a/web/app/pages/Project/Settings/TransferProject/TransferProjectReject.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { useState, useEffect } from 'react'
-import { useTranslation } from 'react-i18next'
-
-import { rejectTransferProject } from '~/api'
-import StatusPage from '~/ui/StatusPage'
-import routes from '~/utils/routes'
-
-const TransferProjectReject = () => {
- const { t } = useTranslation('common')
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState('')
-
- const handleConfirm = async (token: string) => {
- try {
- await rejectTransferProject(token)
- } catch {
- setError(t('apiNotifications.invalidToken'))
- } finally {
- setLoading(false)
- }
- }
-
- useEffect(() => {
- setLoading(true)
- const query = new URLSearchParams(window.location.search)
- const token = query.get('token')
-
- if (!token) {
- setError(t('apiNotifications.invalidToken'))
- setLoading(false)
- return
- }
-
- handleConfirm(token)
- }, []) // eslint-disable-line
-
- if (loading) {
- return <StatusPage loading />
- }
-
- if (error) {
- return (
- <StatusPage
- type='error'
- title={error}
- actions={[
- { label: t('common.dashboard'), to: routes.dashboard, primary: true },
- { label: t('notFoundPage.support'), to: routes.contact },
- ]}
- />
- )
- }
-
- return (
- <StatusPage
- type='info'
- title={t('apiNotifications.transferProjectReject')}
- actions={[{ label: t('common.dashboard'), to: routes.dashboard, primary: true }]}
- />
- )
-}
-
-export default TransferProjectReject
diff --git a/web/app/pages/Project/Settings/tabs/Revenue.tsx b/web/app/pages/Project/Settings/tabs/Revenue.tsx
index 21f8d5481..2fe0561d3 100644
--- a/web/app/pages/Project/Settings/tabs/Revenue.tsx
+++ b/web/app/pages/Project/Settings/tabs/Revenue.tsx
@@ -1,12 +1,12 @@
import { CheckCircleIcon } from '@heroicons/react/24/solid'
import { ArrowUpRightIcon, ExternalLinkIcon } from 'lucide-react'
-import React, { useCallback, useEffect, useState } from 'react'
+import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { connectRevenue, disconnectRevenue, getRevenueStatus, updateRevenueCurrency } from '~/api'
-import type { RevenueProvider } from '~/api'
import { DOCS_URL } from '~/lib/constants'
+import type { ProjectSettingsActionData, RevenueStatus } from '~/routes/projects.settings.$id'
import Button from '~/ui/Button'
import PaddleSVG from '~/ui/icons/Paddle'
import StripeSVG from '~/ui/icons/Stripe'
@@ -15,12 +15,7 @@ import Loader from '~/ui/Loader'
import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
-interface RevenueStatus {
- connected: boolean
- provider?: string
- currency?: string
- lastSyncAt?: string
-}
+type RevenueProvider = 'stripe' | 'paddle'
const SUPPORTED_CURRENCIES = [
{ code: 'USD', symbol: '$', name: 'US Dollar' },
@@ -85,82 +80,96 @@ interface Props {
const Revenue = ({ projectId }: Props) => {
const { t } = useTranslation('common')
+ const fetcher = useFetcher<ProjectSettingsActionData>()
const [status, setStatus] = useState<RevenueStatus | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [apiKey, setApiKey] = useState('')
const [selectedProvider, setSelectedProvider] = useState<RevenueProvider>('stripe')
const [selectedCurrency, setSelectedCurrency] = useState<'USD' | 'EUR' | 'GBP'>('USD')
- const [isConnecting, setIsConnecting] = useState(false)
- const [isDisconnecting, setIsDisconnecting] = useState(false)
- const [isSavingCurrency, setIsSavingCurrency] = useState(false)
-
- const loadStatus = useCallback(async () => {
- try {
- const result = await getRevenueStatus(projectId)
- setStatus(result)
- if (result.provider === 'stripe' || result.provider === 'paddle') {
- setSelectedProvider(result.provider)
- }
- if (result.currency === 'USD' || result.currency === 'EUR' || result.currency === 'GBP') {
- setSelectedCurrency(result.currency)
- }
- } catch (error) {
- console.error('Failed to load revenue status:', error)
- } finally {
- setIsLoading(false)
- }
+
+ const isConnecting = fetcher.state !== 'idle' && fetcher.formData?.get('intent') === 'connect-revenue'
+ const isDisconnecting = fetcher.state !== 'idle' && fetcher.formData?.get('intent') === 'disconnect-revenue'
+ const isSavingCurrency = fetcher.state !== 'idle' && fetcher.formData?.get('intent') === 'update-revenue-currency'
+
+ useEffect(() => {
+ fetcher.submit({ intent: 'get-revenue-status' }, { method: 'POST', action: `/projects/settings/${projectId}` })
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [projectId])
useEffect(() => {
- loadStatus()
- }, [loadStatus])
+ if (fetcher.state === 'idle' && fetcher.data) {
+ const { intent, success, error, revenueStatus } = fetcher.data
+
+ if (intent === 'get-revenue-status') {
+ setIsLoading(false)
+ if (success && revenueStatus) {
+ setStatus(revenueStatus)
+ if (revenueStatus.provider === 'stripe' || revenueStatus.provider === 'paddle') {
+ setSelectedProvider(revenueStatus.provider)
+ }
+ if (
+ revenueStatus.currency === 'USD' ||
+ revenueStatus.currency === 'EUR' ||
+ revenueStatus.currency === 'GBP'
+ ) {
+ setSelectedCurrency(revenueStatus.currency)
+ }
+ } else if (error) {
+ console.error('Failed to load revenue status:', error)
+ }
+ } else if (intent === 'connect-revenue') {
+ if (success) {
+ toast.success(t('project.settings.revenue.connected'))
+ setApiKey('')
+ fetcher.submit(
+ { intent: 'get-revenue-status' },
+ { method: 'POST', action: `/projects/settings/${projectId}` },
+ )
+ } else if (error) {
+ toast.error(error)
+ }
+ } else if (intent === 'disconnect-revenue') {
+ if (success) {
+ toast.success(t('project.settings.revenue.disconnected'))
+ setStatus({ connected: false })
+ } else if (error) {
+ toast.error(error)
+ }
+ } else if (intent === 'update-revenue-currency') {
+ if (success) {
+ toast.success(t('project.settings.revenue.currencyUpdated'))
+ setStatus((prev) => (prev ? { ...prev, currency: selectedCurrency } : prev))
+ } else if (error) {
+ toast.error(error)
+ }
+ }
+ }
+ }, [fetcher.state, fetcher.data, t, projectId, selectedCurrency, fetcher])
- const handleConnect = async () => {
+ const handleConnect = () => {
if (!apiKey.trim()) {
toast.error(t('project.settings.revenue.apiKeyRequired'))
return
}
- setIsConnecting(true)
- try {
- await connectRevenue(projectId, selectedProvider, apiKey, selectedCurrency)
- toast.success(t('project.settings.revenue.connected'))
- setApiKey('')
- await loadStatus()
- } catch (error: any) {
- toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))
- } finally {
- setIsConnecting(false)
- }
+ fetcher.submit(
+ { intent: 'connect-revenue', provider: selectedProvider, apiKey, currency: selectedCurrency },
+ { method: 'POST', action: `/projects/settings/${projectId}` },
+ )
}
- const handleDisconnect = async () => {
- setIsDisconnecting(true)
- try {
- await disconnectRevenue(projectId)
- toast.success(t('project.settings.revenue.disconnected'))
- setStatus({ connected: false })
- } catch (error: any) {
- toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))
- } finally {
- setIsDisconnecting(false)
- }
+ const handleDisconnect = () => {
+ fetcher.submit({ intent: 'disconnect-revenue' }, { method: 'POST', action: `/projects/settings/${projectId}` })
}
- const handleCurrencyChange = async () => {
+ const handleCurrencyChange = () => {
if (!status?.connected) return
- setIsSavingCurrency(true)
- try {
- await updateRevenueCurrency(projectId, selectedCurrency)
- toast.success(t('project.settings.revenue.currencyUpdated'))
- setStatus((prev) => (prev ? { ...prev, currency: selectedCurrency } : prev))
- } catch (error: any) {
- toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))
- } finally {
- setIsSavingCurrency(false)
- }
+ fetcher.submit(
+ { intent: 'update-revenue-currency', currency: selectedCurrency },
+ { method: 'POST', action: `/projects/settings/${projectId}` },
+ )
}
if (isLoading) {
diff --git a/web/app/pages/Project/View/Panels.tsx b/web/app/pages/Project/View/Panels.tsx
index c99c646e2..249673fbd 100644
--- a/web/app/pages/Project/View/Panels.tsx
+++ b/web/app/pages/Project/View/Panels.tsx
@@ -24,10 +24,10 @@ import React, { memo, useState, useEffect, useMemo, Fragment, useRef } from 'rea
import { useTranslation } from 'react-i18next'
import { Link, LinkProps, useNavigate } from 'react-router'
-import { getProjectDataCustomEvents } from '~/api'
+import { useProjectDataCustomEventsProxy } from '~/hooks/useAnalyticsProxy'
import { PROJECT_TABS } from '~/lib/constants'
import { Entry } from '~/lib/models/Entry'
-import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import Button from '~/ui/Button'
import Dropdown from '~/ui/Dropdown'
import Sort from '~/ui/icons/Sort'
@@ -397,8 +397,8 @@ function sortDesc<T>(obj: T, sortByKeys?: boolean): T {
const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, getFilterLink }: CustomEventsProps) => {
const { t } = useTranslation('common')
const { id } = useCurrentProject()
- const projectPassword = useProjectPassword(id)
const { timeBucket, timezone, period, dateRange, timeFormat, rotateXAxis } = useViewProjectContext()
+ const { fetchCustomEvents } = useProjectDataCustomEventsProxy()
const [detailsOpened, setDetailsOpened] = useState(false)
const [activeEvents, setActiveEvents] = useState<any>({})
@@ -467,23 +467,20 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
const to = isCustomPeriod ? getFormatDate(dateRange![1]) : ''
const periodValue = isCustomPeriod ? '' : period
- const data = await getProjectDataCustomEvents(
- id,
+ const data = await fetchCustomEvents(id, topEventsForChart, {
timeBucket,
- periodValue,
+ period: periodValue,
filters,
from,
to,
timezone,
- topEventsForChart,
- projectPassword,
- )
+ })
if (cancelled) {
return
}
- setStackedChart(data?.chart || null)
+ setStackedChart((data?.chart as unknown as typeof stackedChart) || null)
} catch (reason) {
console.error('[ERROR](CustomEvents) Failed to load stacked custom events chart', reason)
if (!cancelled) {
@@ -501,7 +498,7 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
return () => {
cancelled = true
}
- }, [id, timeBucket, period, dateRange, timezone, projectPassword, filters, topEventsForChart])
+ }, [id, timeBucket, period, dateRange, timezone, filters, topEventsForChart, fetchCustomEvents])
useEffect(() => {
setEventsMetadata({})
@@ -1318,9 +1315,7 @@ interface PanelProps {
getVersionFilterLink?: (parent: string | null, version: string | null) => LinkProps['to']
valuesHeaderName?: string
highlightColour?: 'blue' | 'red' | 'orange'
- // When true, rows are non-interactive (no filter link/navigation)
disableRowClick?: boolean
- // Details modal specific overrides
hidePercentageInDetails?: boolean
detailsExtraColumns?: Array<{
header: string
@@ -1328,6 +1323,8 @@ interface PanelProps {
sortLabel: string
getSortValue: (entry: Entry) => number
}>
+ dataLoading?: boolean
+ activeTab?: keyof typeof PROJECT_TABS
}
interface DetailsTableProps extends Pick<
@@ -1341,6 +1338,7 @@ interface DetailsTableProps extends Pick<
| 'rowMapper'
| 'valueMapper'
| 'getFilterLink'
+ | 'activeTab'
> {
total: number
closeDetails: () => void
@@ -1369,12 +1367,12 @@ const DetailsTable = ({
disableRowClick,
hidePercentageInDetails,
detailsExtraColumns,
+ activeTab = PROJECT_TABS.traffic,
}: DetailsTableProps) => {
const {
t,
i18n: { language },
} = useTranslation('common')
- const { activeTab } = useViewProjectContext()
const tnMapping = typeNameMapping(t)
const parentRef = useRef<HTMLDivElement>(null)
const [search, setSearch] = useState('')
@@ -1669,8 +1667,12 @@ const Panel = ({
disableRowClick = false,
hidePercentageInDetails,
detailsExtraColumns,
+ dataLoading: dataLoadingProp,
+ activeTab: activeTabProp,
}: PanelProps) => {
- const { dataLoading, activeTab } = useViewProjectContext()
+ const ctx = useViewProjectContext()
+ const dataLoading = dataLoadingProp ?? ctx.dataLoading
+ const activeTab = activeTabProp ?? ctx.activeTab
const { t } = useTranslation('common')
const total = useMemo(() => _reduce(data, (prev, curr) => prev + curr.count, 0), [data])
const [detailsOpened, setDetailsOpened] = useState(false)
@@ -1917,6 +1919,7 @@ const Panel = ({
disableRowClick={disableRowClick}
hidePercentageInDetails={hidePercentageInDetails}
detailsExtraColumns={detailsExtraColumns}
+ activeTab={activeTab}
/>
}
size='large'
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index b22f0f9ca..0dacc8cda 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -26,11 +26,10 @@ import {
import React, { useState, useEffect, useMemo, useRef, useCallback, createContext, useContext, lazy } from 'react'
import { useHotkeys } from 'react-hotkeys-hook'
import { useTranslation } from 'react-i18next'
-import { useNavigate, useSearchParams, LinkProps } from 'react-router'
+import { useNavigate, useSearchParams, LinkProps, useFetcher } from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
import { toast } from 'sonner'
-import { getProjectViews, deleteProjectView } from '~/api'
import EventsRunningOutBanner from '~/components/EventsRunningOutBanner'
import Footer from '~/components/Footer'
import Header from '~/components/Header'
@@ -59,6 +58,7 @@ import {
import ViewProjectHotkeys from '~/modals/ViewProjectHotkeys'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
+import { ProjectViewActionData } from '~/routes/projects.$id'
import Dropdown from '~/ui/Dropdown'
import Flag from '~/ui/Flag'
import Loader from '~/ui/Loader'
@@ -111,16 +111,6 @@ interface ViewProjectContextType {
dataLoading: boolean
activeTab: keyof typeof PROJECT_TABS
filters: Filter[]
- captchaRefreshTrigger: number
- goalsRefreshTrigger: number
- experimentsRefreshTrigger: number
- featureFlagsRefreshTrigger: number
- sessionsRefreshTrigger: number
- errorsRefreshTrigger: number
- performanceRefreshTrigger: number
- trafficRefreshTrigger: number
- funnelsRefreshTrigger: number
- profilesRefreshTrigger: number
isActiveCompare: boolean
dateRangeCompare: Date[] | null
@@ -157,6 +147,19 @@ interface ViewProjectContextType {
setIsMapFullscreen: (value: boolean) => void
}
+interface RefreshTriggersContextType {
+ captchaRefreshTrigger: number
+ goalsRefreshTrigger: number
+ experimentsRefreshTrigger: number
+ featureFlagsRefreshTrigger: number
+ sessionsRefreshTrigger: number
+ errorsRefreshTrigger: number
+ performanceRefreshTrigger: number
+ trafficRefreshTrigger: number
+ funnelsRefreshTrigger: number
+ profilesRefreshTrigger: number
+}
+
const defaultViewProjectContext: ViewProjectContextType = {
timezone: DEFAULT_TIMEZONE,
dateRange: null,
@@ -170,16 +173,6 @@ const defaultViewProjectContext: ViewProjectContextType = {
dataLoading: false,
activeTab: PROJECT_TABS.traffic,
filters: [],
- captchaRefreshTrigger: 0,
- goalsRefreshTrigger: 0,
- experimentsRefreshTrigger: 0,
- featureFlagsRefreshTrigger: 0,
- sessionsRefreshTrigger: 0,
- errorsRefreshTrigger: 0,
- performanceRefreshTrigger: 0,
- trafficRefreshTrigger: 0,
- funnelsRefreshTrigger: 0,
- profilesRefreshTrigger: 0,
isActiveCompare: false,
dateRangeCompare: null,
@@ -215,13 +208,32 @@ const defaultViewProjectContext: ViewProjectContextType = {
setIsMapFullscreen: () => {},
}
+const defaultRefreshTriggersContext: RefreshTriggersContextType = {
+ captchaRefreshTrigger: 0,
+ goalsRefreshTrigger: 0,
+ experimentsRefreshTrigger: 0,
+ featureFlagsRefreshTrigger: 0,
+ sessionsRefreshTrigger: 0,
+ errorsRefreshTrigger: 0,
+ performanceRefreshTrigger: 0,
+ trafficRefreshTrigger: 0,
+ funnelsRefreshTrigger: 0,
+ profilesRefreshTrigger: 0,
+}
+
export const ViewProjectContext = createContext<ViewProjectContextType>(defaultViewProjectContext)
+export const RefreshTriggersContext = createContext<RefreshTriggersContextType>(defaultRefreshTriggersContext)
export const useViewProjectContext = () => {
const context = useContext(ViewProjectContext)
return context
}
+export const useRefreshTriggers = () => {
+ const context = useContext(RefreshTriggersContext)
+ return context
+}
+
const ViewProjectContent = () => {
const {
id,
@@ -402,49 +414,47 @@ const ViewProjectContent = () => {
// null -> not loaded yet
const [projectViews, setProjectViews] = useState<ProjectView[]>([])
const [projectViewsLoading, setProjectViewsLoading] = useState<boolean | null>(null) // // null - not loaded, true - loading, false - loaded
- const [projectViewDeleting, setProjectViewDeleting] = useState(false)
const [projectViewToUpdate, setProjectViewToUpdate] = useState<ProjectView | undefined>()
- const mode = activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode] ? 'cumulative' : 'periodical'
+ const viewsLoadFetcher = useFetcher<ProjectViewActionData>()
- const loadProjectViews = async (forced?: boolean) => {
- if (!forced && projectViewsLoading !== null) {
- return
- }
+ const mode = activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode] ? 'cumulative' : 'periodical'
- setProjectViewsLoading(true)
+ const loadProjectViews = useCallback(
+ (forced?: boolean) => {
+ if (!forced && projectViewsLoading !== null) {
+ return
+ }
- try {
- const views = await getProjectViews(id, projectPassword)
- setProjectViews(views)
- } catch (reason: any) {
- console.error('[ERROR] (loadProjectViews)', reason)
- toast.error(reason)
- }
+ if (viewsLoadFetcher.state !== 'idle') {
+ return
+ }
- setProjectViewsLoading(false)
- }
+ setProjectViewsLoading(true)
- const onProjectViewDelete = async (viewId: string) => {
- if (projectViewDeleting) {
- return
- }
+ const formData = new FormData()
+ formData.append('intent', 'get-project-views')
+ if (projectPassword) {
+ formData.append('password', projectPassword)
+ }
- setProjectViewDeleting(true)
+ viewsLoadFetcher.submit(formData, { method: 'POST' })
+ },
+ [projectViewsLoading, viewsLoadFetcher, projectPassword],
+ )
- try {
- await deleteProjectView(id, viewId)
- } catch (reason: any) {
- console.error('[ERROR] (deleteProjectView)', reason)
- toast.error(reason)
- setProjectViewDeleting(false)
- return
+ // Handle views load fetcher response
+ useEffect(() => {
+ if (viewsLoadFetcher.state === 'idle' && viewsLoadFetcher.data) {
+ if (viewsLoadFetcher.data.success && viewsLoadFetcher.data.data) {
+ setProjectViews((viewsLoadFetcher.data.data as ProjectView[]) || [])
+ } else if (viewsLoadFetcher.data.error) {
+ console.error('[ERROR] (loadProjectViews)', viewsLoadFetcher.data.error)
+ toast.error(viewsLoadFetcher.data.error)
+ }
+ setProjectViewsLoading(false)
}
-
- toast.success(t('apiNotifications.segmentDeleted'))
- await loadProjectViews(true)
- setProjectViewDeleting(false)
- }
+ }, [viewsLoadFetcher.state, viewsLoadFetcher.data])
const getVersionFilterLink = useCallback(
(parent: string | null, version: string | null, panelType: 'br' | 'os') => {
@@ -642,18 +652,21 @@ const ViewProjectContent = () => {
setCustomMetrics([])
}
- const setDashboardTab = (key: keyof typeof PROJECT_TABS) => {
- if (dataLoading) {
- return
- }
+ const setDashboardTab = useCallback(
+ (key: keyof typeof PROJECT_TABS) => {
+ if (dataLoading) {
+ return
+ }
- setIsMapFullscreen(false)
+ setIsMapFullscreen(false)
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.set('tab', key)
- setSearchParams(newSearchParams)
- trackCustom('DASHBOARD_TAB_CHANGED', { tab: key })
- }
+ const newSearchParams = new URLSearchParams(searchParams.toString())
+ newSearchParams.set('tab', key)
+ setSearchParams(newSearchParams)
+ trackCustom('DASHBOARD_TAB_CHANGED', { tab: key })
+ },
+ [dataLoading, searchParams, setSearchParams],
+ )
const refreshStats = useCallback(
async (_isManual = true) => {
@@ -946,16 +959,6 @@ const ViewProjectContent = () => {
dataLoading,
activeTab,
filters,
- captchaRefreshTrigger,
- goalsRefreshTrigger,
- experimentsRefreshTrigger,
- featureFlagsRefreshTrigger,
- sessionsRefreshTrigger,
- errorsRefreshTrigger,
- performanceRefreshTrigger,
- trafficRefreshTrigger,
- funnelsRefreshTrigger,
- profilesRefreshTrigger,
isActiveCompare,
dateRangeCompare,
@@ -1003,16 +1006,6 @@ const ViewProjectContent = () => {
dataLoading,
activeTab,
filters,
- captchaRefreshTrigger,
- goalsRefreshTrigger,
- experimentsRefreshTrigger,
- featureFlagsRefreshTrigger,
- sessionsRefreshTrigger,
- errorsRefreshTrigger,
- performanceRefreshTrigger,
- trafficRefreshTrigger,
- funnelsRefreshTrigger,
- profilesRefreshTrigger,
isActiveCompare,
dateRangeCompare,
activePeriodCompare,
@@ -1043,6 +1036,33 @@ const ViewProjectContent = () => {
],
)
+ const refreshTriggersValue = useMemo(
+ () => ({
+ captchaRefreshTrigger,
+ goalsRefreshTrigger,
+ experimentsRefreshTrigger,
+ featureFlagsRefreshTrigger,
+ sessionsRefreshTrigger,
+ errorsRefreshTrigger,
+ performanceRefreshTrigger,
+ trafficRefreshTrigger,
+ funnelsRefreshTrigger,
+ profilesRefreshTrigger,
+ }),
+ [
+ captchaRefreshTrigger,
+ goalsRefreshTrigger,
+ experimentsRefreshTrigger,
+ featureFlagsRefreshTrigger,
+ sessionsRefreshTrigger,
+ errorsRefreshTrigger,
+ performanceRefreshTrigger,
+ trafficRefreshTrigger,
+ funnelsRefreshTrigger,
+ profilesRefreshTrigger,
+ ],
+ )
+
if (isPasswordRequired) {
return (
<>
@@ -1183,246 +1203,246 @@ const ViewProjectContent = () => {
<ClientOnly>
{() => (
<ViewProjectContext.Provider value={contextValue}>
- <>
- <div
- className={cx('flex min-h-screen flex-col bg-gray-50 dark:bg-slate-900', {
- 'min-h-including-header': !isEmbedded,
- 'min-h-screen': isEmbedded,
- })}
- >
- {!isEmbedded ? <Header /> : null}
-
- <div className='grid flex-1 grid-cols-1'>
- <div ref={fullscreenMapRef} className='z-0 col-start-1 row-start-1 min-h-full w-full empty:hidden' />
-
- <div
- className={cx(
- 'z-10 col-start-1 row-start-1 mx-auto w-full max-w-7xl px-4 py-2 sm:px-6 lg:px-8',
- isMapFullscreen ? 'pointer-events-none' : 'pointer-events-auto',
- )}
- >
- <div ref={ref} className='relative flex gap-4'>
- <ProjectSidebar
- tabs={tabs}
- activeTab={activeTab}
- onTabChange={setDashboardTab}
- projectId={id}
- projectName={project.name}
- websiteUrl={project.websiteUrl}
- dataLoading={dataLoading}
- searchParams={searchParams}
- allowedToManage={allowedToManage}
- className='pointer-events-auto z-20 hidden md:flex'
- />
- {isMobileSidebarOpen ? (
- <div className='pointer-events-auto'>
- <ProjectSidebar
- tabs={tabs}
- activeTab={activeTab}
- onTabChange={setDashboardTab}
- projectId={id}
- projectName={project.name}
- websiteUrl={project.websiteUrl}
- dataLoading={dataLoading}
- searchParams={searchParams}
- allowedToManage={allowedToManage}
- isMobileOpen={isMobileSidebarOpen}
- onMobileClose={closeMobileSidebar}
- />
- </div>
- ) : null}
- {/* Main Content */}
- <div
- className={cx(
- 'pointer-events-auto flex min-w-0 flex-1 flex-col',
- isMapFullscreen ? 'pointer-events-none' : 'pointer-events-auto',
- )}
- ref={dashboardRef}
- >
- <EventsRunningOutBanner />
- <div className='pointer-events-auto'>
- <MobileSidebarTrigger onClick={openMobileSidebar} activeTabLabel={activeTabLabel} />
- </div>
- <AnimatePresence mode='wait'>
- <motion.div
- key={activeTab}
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- transition={{ duration: 0.15 }}
- >
- {activeTab === PROJECT_TABS.ai ? <AskAIView projectId={id} /> : null}
- {activeTab === PROJECT_TABS.traffic ? (
- <TrafficView
- tnMapping={tnMapping}
- customMetrics={customMetrics}
- onRemoveCustomMetric={onRemoveCustomMetric}
- resetCustomMetrics={resetCustomMetrics}
- mode={mode}
- projectViews={projectViews}
- projectViewsLoading={projectViewsLoading}
- projectViewDeleting={projectViewDeleting}
- loadProjectViews={loadProjectViews}
- onProjectViewDelete={onProjectViewDelete}
- setProjectViewToUpdate={setProjectViewToUpdate}
- setIsAddAViewOpened={setIsAddAViewOpened}
- onCustomMetric={onCustomMetric}
- />
- ) : null}
- {activeTab === PROJECT_TABS.performance ? <PerformanceView tnMapping={tnMapping} /> : null}
- {activeTab === PROJECT_TABS.funnels ? <FunnelsView /> : null}
- {activeTab === PROJECT_TABS.alerts ? <ProjectAlertsView /> : null}
- {activeTab === PROJECT_TABS.profiles ? <ProfilesView tnMapping={tnMapping} /> : null}
- {activeTab === PROJECT_TABS.sessions ? (
- <SessionsView tnMapping={tnMapping} rotateXAxis={rotateXAxis} />
- ) : null}
- {activeTab === PROJECT_TABS.errors ? <ErrorsView /> : null}
- {activeTab === PROJECT_TABS.goals ? (
- <GoalsView
- period={period}
- from={dateRange ? getFormatDate(dateRange[0]) : ''}
- to={dateRange ? getFormatDate(dateRange[1]) : ''}
- timezone={timezone}
- />
- ) : null}
- {activeTab === PROJECT_TABS.experiments ? (
- <ExperimentsView
- period={period}
- from={dateRange ? getFormatDate(dateRange[0]) : ''}
- to={dateRange ? getFormatDate(dateRange[1]) : ''}
- timezone={timezone}
- />
- ) : null}
- {activeTab === PROJECT_TABS.featureFlags ? (
- <FeatureFlagsView
- period={period}
- from={dateRange ? getFormatDate(dateRange[0]) : ''}
- to={dateRange ? getFormatDate(dateRange[1]) : ''}
- timezone={timezone}
- />
- ) : null}
- {activeTab === PROJECT_TABS.captcha ? <CaptchaView projectId={id} /> : null}
- </motion.div>
- </AnimatePresence>
-
- {isEmbedded ? null : (
- <>
- <div className='flex-1' />
- <div className='pointer-events-auto mt-4 flex w-full items-center justify-between gap-2'>
- <Dropdown
- items={whitelist}
- buttonClassName='relative rounded-md border border-transparent bg-gray-50 p-2 hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden ring-inset dark:bg-slate-900 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200 inline-flex items-center [&>svg]:w-4 [&>svg]:h-4 [&>svg]:mr-0 [&>svg]:ml-1 font-medium !text-sm text-slate-900 dark:text-gray-50'
- title={
- <span className='inline-flex items-center'>
- <Flag
- className='mr-2 rounded-xs'
- country={languageFlag[language]}
- size={16}
- alt={languages[language]}
- />
- {languages[language]}
- </span>
- }
- labelExtractor={(lng: string) => (
- <div className='flex items-center'>
- <Flag
- className='mr-2 rounded-xs'
- country={languageFlag[lng]}
- size={16}
- alt={languageFlag[lng]}
- />
- {languages[lng]}
- </div>
- )}
- onSelect={(lng: string) => {
- changeLanguage(lng)
- }}
- headless
- />
- <div className='flex items-center gap-2'>
- <button
- type='button'
- onClick={() => setIsHotkeysHelpOpened(true)}
- aria-label={t('modals.shortcuts.title')}
- className='relative rounded-md border border-transparent bg-gray-50 p-2 transition-colors ring-inset 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'
- >
- <KeyboardIcon className='h-6 w-6 text-slate-700 dark:text-gray-200' />
- </button>
+ <RefreshTriggersContext.Provider value={refreshTriggersValue}>
+ <>
+ <div
+ className={cx('flex min-h-screen flex-col bg-gray-50 dark:bg-slate-900', {
+ 'min-h-including-header': !isEmbedded,
+ 'min-h-screen': isEmbedded,
+ })}
+ >
+ {!isEmbedded ? <Header /> : null}
+
+ <div className='grid flex-1 grid-cols-1'>
+ <div ref={fullscreenMapRef} className='z-0 col-start-1 row-start-1 min-h-full w-full empty:hidden' />
+
+ <div
+ className={cx(
+ 'z-10 col-start-1 row-start-1 mx-auto w-full max-w-7xl px-4 py-2 sm:px-6 lg:px-8',
+ isMapFullscreen ? 'pointer-events-none' : 'pointer-events-auto',
+ )}
+ >
+ <div ref={ref} className='relative flex gap-4'>
+ <ProjectSidebar
+ tabs={tabs}
+ activeTab={activeTab}
+ onTabChange={setDashboardTab}
+ projectId={id}
+ projectName={project.name}
+ websiteUrl={project.websiteUrl}
+ dataLoading={dataLoading}
+ searchParams={searchParams}
+ allowedToManage={allowedToManage}
+ className='pointer-events-auto z-20 hidden md:flex'
+ />
+ {isMobileSidebarOpen ? (
+ <div className='pointer-events-auto'>
+ <ProjectSidebar
+ tabs={tabs}
+ activeTab={activeTab}
+ onTabChange={setDashboardTab}
+ projectId={id}
+ projectName={project.name}
+ websiteUrl={project.websiteUrl}
+ dataLoading={dataLoading}
+ searchParams={searchParams}
+ allowedToManage={allowedToManage}
+ isMobileOpen={isMobileSidebarOpen}
+ onMobileClose={closeMobileSidebar}
+ />
+ </div>
+ ) : null}
+ {/* Main Content */}
+ <div
+ className={cx(
+ 'pointer-events-auto flex min-w-0 flex-1 flex-col',
+ isMapFullscreen ? 'pointer-events-none' : 'pointer-events-auto',
+ )}
+ ref={dashboardRef}
+ >
+ <EventsRunningOutBanner />
+ <div className='pointer-events-auto'>
+ <MobileSidebarTrigger onClick={openMobileSidebar} activeTabLabel={activeTabLabel} />
+ </div>
+ <AnimatePresence mode='wait'>
+ <motion.div
+ key={activeTab}
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: 0.15 }}
+ >
+ {activeTab === PROJECT_TABS.ai ? <AskAIView projectId={id} /> : null}
+ {activeTab === PROJECT_TABS.traffic ? (
+ <TrafficView
+ tnMapping={tnMapping}
+ customMetrics={customMetrics}
+ onRemoveCustomMetric={onRemoveCustomMetric}
+ resetCustomMetrics={resetCustomMetrics}
+ mode={mode}
+ projectViews={projectViews}
+ projectViewsLoading={projectViewsLoading}
+ loadProjectViews={loadProjectViews}
+ setProjectViewToUpdate={setProjectViewToUpdate}
+ setIsAddAViewOpened={setIsAddAViewOpened}
+ onCustomMetric={onCustomMetric}
+ />
+ ) : null}
+ {activeTab === PROJECT_TABS.performance ? <PerformanceView tnMapping={tnMapping} /> : null}
+ {activeTab === PROJECT_TABS.funnels ? <FunnelsView /> : null}
+ {activeTab === PROJECT_TABS.alerts ? <ProjectAlertsView /> : null}
+ {activeTab === PROJECT_TABS.profiles ? <ProfilesView tnMapping={tnMapping} /> : null}
+ {activeTab === PROJECT_TABS.sessions ? (
+ <SessionsView tnMapping={tnMapping} rotateXAxis={rotateXAxis} />
+ ) : null}
+ {activeTab === PROJECT_TABS.errors ? <ErrorsView /> : null}
+ {activeTab === PROJECT_TABS.goals ? (
+ <GoalsView
+ period={period}
+ from={dateRange ? getFormatDate(dateRange[0]) : ''}
+ to={dateRange ? getFormatDate(dateRange[1]) : ''}
+ timezone={timezone}
+ />
+ ) : null}
+ {activeTab === PROJECT_TABS.experiments ? (
+ <ExperimentsView
+ period={period}
+ from={dateRange ? getFormatDate(dateRange[0]) : ''}
+ to={dateRange ? getFormatDate(dateRange[1]) : ''}
+ timezone={timezone}
+ />
+ ) : null}
+ {activeTab === PROJECT_TABS.featureFlags ? (
+ <FeatureFlagsView
+ period={period}
+ from={dateRange ? getFormatDate(dateRange[0]) : ''}
+ to={dateRange ? getFormatDate(dateRange[1]) : ''}
+ timezone={timezone}
+ />
+ ) : null}
+ {activeTab === PROJECT_TABS.captcha ? <CaptchaView projectId={id} /> : null}
+ </motion.div>
+ </AnimatePresence>
+
+ {isEmbedded ? null : (
+ <>
+ <div className='flex-1' />
+ <div className='pointer-events-auto mt-4 flex w-full items-center justify-between gap-2'>
<Dropdown
+ items={whitelist}
+ buttonClassName='relative rounded-md border border-transparent bg-gray-50 p-2 hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden ring-inset dark:bg-slate-900 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200 inline-flex items-center [&>svg]:w-4 [&>svg]:h-4 [&>svg]:mr-0 [&>svg]:ml-1 font-medium !text-sm text-slate-900 dark:text-gray-50'
title={
- <span className='flex items-center justify-center'>
- <span className='sr-only'>{t('header.switchTheme')}</span>
- {theme === 'dark' ? (
- <SunIcon className='h-6 w-6 text-gray-200' aria-hidden='true' />
- ) : (
- <MoonIcon className='h-6 w-6 text-slate-700' aria-hidden='true' />
- )}
+ <span className='inline-flex items-center'>
+ <Flag
+ className='mr-2 rounded-xs'
+ country={languageFlag[language]}
+ size={16}
+ alt={languages[language]}
+ />
+ {languages[language]}
</span>
}
- items={[
- { key: 'light', label: t('header.light'), icon: SunIcon },
- { key: 'dark', label: t('header.dark'), icon: MoonIcon },
- ]}
- keyExtractor={(item) => item.key}
- labelExtractor={(item) => (
- <div
- className={cx('flex w-full items-center', {
- 'light:text-indigo-600': item.key === 'light',
- 'dark:text-indigo-400': item.key === 'dark',
- })}
- >
- <item.icon
- className={cx('mr-2 h-5 w-5', {
- 'dark:text-gray-300': item.key === 'light',
- 'light:text-gray-400': item.key === 'dark',
- })}
- aria-hidden='true'
+ labelExtractor={(lng: string) => (
+ <div className='flex items-center'>
+ <Flag
+ className='mr-2 rounded-xs'
+ country={languageFlag[lng]}
+ size={16}
+ alt={languageFlag[lng]}
/>
- {item.label}
+ {languages[lng]}
</div>
)}
- onSelect={(item) => setTheme(item.key as 'light' | 'dark')}
- className='flex'
- chevron={null}
+ onSelect={(lng: string) => {
+ changeLanguage(lng)
+ }}
headless
- buttonClassName='relative rounded-md border border-transparent bg-gray-50 p-2 md:px-2 hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden ring-inset dark:bg-slate-900 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200'
- menuItemsClassName='top-5'
- selectItemClassName='font-semibold'
/>
+ <div className='flex items-center gap-2'>
+ <button
+ type='button'
+ onClick={() => setIsHotkeysHelpOpened(true)}
+ aria-label={t('modals.shortcuts.title')}
+ className='relative rounded-md border border-transparent bg-gray-50 p-2 transition-colors ring-inset 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'
+ >
+ <KeyboardIcon className='h-6 w-6 text-slate-700 dark:text-gray-200' />
+ </button>
+ <Dropdown
+ title={
+ <span className='flex items-center justify-center'>
+ <span className='sr-only'>{t('header.switchTheme')}</span>
+ {theme === 'dark' ? (
+ <SunIcon className='h-6 w-6 text-gray-200' aria-hidden='true' />
+ ) : (
+ <MoonIcon className='h-6 w-6 text-slate-700' aria-hidden='true' />
+ )}
+ </span>
+ }
+ items={[
+ { key: 'light', label: t('header.light'), icon: SunIcon },
+ { key: 'dark', label: t('header.dark'), icon: MoonIcon },
+ ]}
+ keyExtractor={(item) => item.key}
+ labelExtractor={(item) => (
+ <div
+ className={cx('flex w-full items-center', {
+ 'light:text-indigo-600': item.key === 'light',
+ 'dark:text-indigo-400': item.key === 'dark',
+ })}
+ >
+ <item.icon
+ className={cx('mr-2 h-5 w-5', {
+ 'dark:text-gray-300': item.key === 'light',
+ 'light:text-gray-400': item.key === 'dark',
+ })}
+ aria-hidden='true'
+ />
+ {item.label}
+ </div>
+ )}
+ onSelect={(item) => setTheme(item.key as 'light' | 'dark')}
+ className='flex'
+ chevron={null}
+ headless
+ buttonClassName='relative rounded-md border border-transparent bg-gray-50 p-2 md:px-2 hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden ring-inset dark:bg-slate-900 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200'
+ menuItemsClassName='top-5'
+ selectItemClassName='font-semibold'
+ />
+ </div>
</div>
- </div>
- </>
- )}
+ </>
+ )}
+ </div>
</div>
</div>
</div>
- </div>
- {isEmbedded ? null : <Footer showDBIPMessage />}
- </div>
- <ViewProjectHotkeys isOpened={isHotkeysHelpOpened} onClose={() => setIsHotkeysHelpOpened(false)} />
- <SearchFilters
- type={activeTab === PROJECT_TABS.errors ? 'errors' : 'traffic'}
- showModal={showFiltersSearch}
- setShowModal={setShowFiltersSearch}
- tnMapping={tnMapping}
- filters={filters}
- />
- <AddAViewModal
- showModal={isAddAViewOpened}
- setShowModal={(show) => {
- setIsAddAViewOpened(show)
- setProjectViewToUpdate(undefined)
- }}
- onSubmit={() => {
- setProjectViews([])
- setProjectViewsLoading(null)
- setProjectViewToUpdate(undefined)
- }}
- defaultView={projectViewToUpdate}
- tnMapping={tnMapping}
- />
- </>
+ {isEmbedded ? null : <Footer showDBIPMessage />}
+ </div>
+ <ViewProjectHotkeys isOpened={isHotkeysHelpOpened} onClose={() => setIsHotkeysHelpOpened(false)} />
+ <SearchFilters
+ type={activeTab === PROJECT_TABS.errors ? 'errors' : 'traffic'}
+ showModal={showFiltersSearch}
+ setShowModal={setShowFiltersSearch}
+ tnMapping={tnMapping}
+ filters={filters}
+ />
+ <AddAViewModal
+ showModal={isAddAViewOpened}
+ setShowModal={(show) => {
+ setIsAddAViewOpened(show)
+ setProjectViewToUpdate(undefined)
+ }}
+ onSubmit={() => {
+ setProjectViews([])
+ setProjectViewsLoading(null)
+ setProjectViewToUpdate(undefined)
+ }}
+ defaultView={projectViewToUpdate}
+ tnMapping={tnMapping}
+ />
+ </>
+ </RefreshTriggersContext.Provider>
</ViewProjectContext.Provider>
)}
</ClientOnly>
diff --git a/web/app/pages/Project/View/components/AddAViewModal.tsx b/web/app/pages/Project/View/components/AddAViewModal.tsx
index e67d2e4e1..1560a28a1 100644
--- a/web/app/pages/Project/View/components/AddAViewModal.tsx
+++ b/web/app/pages/Project/View/components/AddAViewModal.tsx
@@ -4,13 +4,15 @@ import _find from 'lodash/find'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import _size from 'lodash/size'
-import React, { useState, useEffect, useMemo, useCallback } from 'react'
+import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { getFilters, createProjectView, updateProjectView } from '~/api'
+import { useFiltersProxy } from '~/hooks/useAnalyticsProxy'
import { FILTERS_PANELS_ORDER } from '~/lib/constants'
-import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+import { ProjectViewActionData } from '~/routes/projects.$id'
import Combobox from '~/ui/Combobox'
import Input from '~/ui/Input'
import Modal from '~/ui/Modal'
@@ -189,26 +191,26 @@ const MAX_METRICS_IN_VIEW = 3
const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultView }: AddAViewModalProps) => {
const { id } = useCurrentProject()
- const projectPassword = useProjectPassword(id)
const {
t,
i18n: { language },
} = useTranslation('common')
+ const fetcher = useFetcher<ProjectViewActionData>()
const [name, setName] = useState(defaultView?.name || '')
const [filterType, setFilterType] = useState('')
const [searchList, setSearchList] = useState<any[]>([])
const [activeFilters, setActiveFilters] = useState<FilterType[]>(defaultView?.filters || [])
const [customEvents, setCustomEvents] = useState<Partial<ProjectViewCustomEvent>[]>(defaultView?.customEvents || [])
- const [isViewSubmitting, setIsViewSubmitting] = useState(false)
const [errors, setErrors] = useState<AddAViewModalErrors>({})
+ const { fetchFilters } = useFiltersProxy()
const getFiltersList = useCallback(
async (category: string) => {
- const result = await getFilters(id, category, projectPassword)
+ const result = await fetchFilters(id, category)
- setSearchList(result)
+ setSearchList(result || [])
},
- [id, projectPassword],
+ [id, fetchFilters],
)
useEffect(() => {
@@ -237,7 +239,7 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
getFiltersList(filterType)
}, [filterType, showModal, getFiltersList])
- const closeModal = () => {
+ const closeModal = useCallback(() => {
setShowModal(false)
setTimeout(() => {
setName('')
@@ -246,7 +248,7 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
setCustomEvents([])
setErrors({})
}, 300)
- }
+ }, [setShowModal])
const onItemSelect = (item: string) => {
let processedItem = item
@@ -308,7 +310,30 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
return valid
}
- const onViewCreate = async () => {
+ const isViewSubmitting = fetcher.state !== 'idle'
+ const hasHandledResponse = useRef(false)
+
+ // Reset the handled flag when fetcher starts submitting
+ useEffect(() => {
+ if (fetcher.state === 'submitting') {
+ hasHandledResponse.current = false
+ }
+ }, [fetcher.state])
+
+ // Handle fetcher response
+ useEffect(() => {
+ if (fetcher.state === 'idle' && fetcher.data && !hasHandledResponse.current) {
+ hasHandledResponse.current = true
+ if (fetcher.data.success) {
+ onSubmit()
+ closeModal()
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ }
+ }, [fetcher.state, fetcher.data, onSubmit, closeModal])
+
+ const onViewCreate = () => {
if (isViewSubmitting) {
return
}
@@ -317,24 +342,20 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
return
}
- setIsViewSubmitting(true)
-
- try {
- // updating an existing view
- if (defaultView?.id) {
- await updateProjectView(id, defaultView?.id, name, activeFilters, customEvents)
- } else {
- // crating a new one
- await createProjectView(id, name, 'traffic', activeFilters, customEvents)
- }
- } catch (reason) {
- console.error('[ERROR] onViewCreate:', reason)
- toast.error(t('apiNotifications.somethingWentWrong'))
+ const formData = new FormData()
+ formData.append('filters', JSON.stringify(activeFilters))
+ formData.append('customEvents', JSON.stringify(customEvents))
+ formData.append('name', name)
+
+ if (defaultView?.id) {
+ formData.append('intent', 'update-project-view')
+ formData.append('viewId', defaultView.id)
+ } else {
+ formData.append('intent', 'create-project-view')
+ formData.append('type', 'traffic')
}
- setIsViewSubmitting(false)
- onSubmit()
- closeModal()
+ fetcher.submit(formData, { method: 'POST' })
}
return (
diff --git a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx
index c2d47f174..95041376b 100644
--- a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx
+++ b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx
@@ -4,7 +4,8 @@ import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router'
-import { getLiveVisitorsInfo, GetLiveVisitorsInfo } from '~/api'
+import type { LiveVisitorInfo } from '~/api/api.server'
+import { useLiveVisitorsProxy } from '~/hooks/useAnalyticsProxy'
import { PROJECT_TABS } from '~/lib/constants'
import Flag from '~/ui/Flag'
import PulsatingCircle from '~/ui/icons/PulsatingCircle'
@@ -12,23 +13,23 @@ import Spin from '~/ui/icons/Spin'
import OutsideClickHandler from '~/ui/OutsideClickHandler'
import { cn } from '~/utils/generic'
-import { useCurrentProject, useProjectPassword } from '../../../../providers/CurrentProjectProvider'
+import { useCurrentProject } from '../../../../providers/CurrentProjectProvider'
const LiveVisitorsDropdown = () => {
const { id, liveVisitors, updateLiveVisitors } = useCurrentProject()
- const projectPassword = useProjectPassword(id)
const { t } = useTranslation()
const [isDropdownVisible, setIsDropdownVisible] = useState(false)
const [isLoading, setIsLoading] = useState(true)
- const [liveInfo, setLiveInfo] = useState<GetLiveVisitorsInfo[]>([])
+ const [liveInfo, setLiveInfo] = useState<LiveVisitorInfo[]>([])
+ const { fetchLiveVisitorsInfo } = useLiveVisitorsProxy()
const getLiveVisitors = async () => {
setIsLoading(true)
try {
// Getting live sessions list and updating live visitors count to make sure it matches the list length
- const [info] = await Promise.all([getLiveVisitorsInfo(id, projectPassword), updateLiveVisitors()])
- setLiveInfo(info)
+ const [info] = await Promise.all([fetchLiveVisitorsInfo(id), updateLiveVisitors()])
+ setLiveInfo(info || [])
} catch (reason) {
console.error('[LiveVisitorsDropdown] getLiveVisitors:', reason)
}
diff --git a/web/app/pages/Project/View/components/ProjectSidebar.tsx b/web/app/pages/Project/View/components/ProjectSidebar.tsx
index 36bc55776..dafd664ca 100644
--- a/web/app/pages/Project/View/components/ProjectSidebar.tsx
+++ b/web/app/pages/Project/View/components/ProjectSidebar.tsx
@@ -8,7 +8,7 @@ import {
XIcon,
MenuIcon,
} from 'lucide-react'
-import React, { useState, useMemo, useCallback, useEffect, useRef } from 'react'
+import React, { useState, useMemo, useCallback, useEffect, useRef, memo } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, LinkProps } from 'react-router'
@@ -108,7 +108,7 @@ const CollapsibleGroup: React.FC<{
searchParams: URLSearchParams
isCollapsed?: boolean
onMobileClose?: () => void
-}> = ({ group, activeTab, onTabChange, projectId, dataLoading, searchParams, isCollapsed, onMobileClose }) => {
+}> = memo(({ group, activeTab, onTabChange, projectId, dataLoading, searchParams, isCollapsed, onMobileClose }) => {
const [isExpanded, setIsExpanded] = useState(() => getGroupExpandedState(group.id))
const hasActiveTab = useMemo(() => {
@@ -259,7 +259,9 @@ const CollapsibleGroup: React.FC<{
</div>
</div>
)
-}
+})
+
+CollapsibleGroup.displayName = 'CollapsibleGroup'
const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
tabs,
@@ -620,4 +622,21 @@ export const MobileSidebarTrigger: React.FC<MobileSidebarTriggerProps> = ({ onCl
)
}
-export default ProjectSidebar
+const MemoizedProjectSidebar = memo(ProjectSidebar, (prevProps, nextProps) => {
+ return (
+ prevProps.activeTab === nextProps.activeTab &&
+ prevProps.projectId === nextProps.projectId &&
+ prevProps.projectName === nextProps.projectName &&
+ prevProps.websiteUrl === nextProps.websiteUrl &&
+ prevProps.dataLoading === nextProps.dataLoading &&
+ prevProps.allowedToManage === nextProps.allowedToManage &&
+ prevProps.isMobileOpen === nextProps.isMobileOpen &&
+ prevProps.className === nextProps.className &&
+ prevProps.searchParams.toString() === nextProps.searchParams.toString() &&
+ prevProps.tabs === nextProps.tabs &&
+ prevProps.onTabChange === nextProps.onTabChange &&
+ prevProps.onMobileClose === nextProps.onMobileClose
+ )
+})
+
+export default MemoizedProjectSidebar
diff --git a/web/app/pages/Project/View/components/RefreshStatsButton.tsx b/web/app/pages/Project/View/components/RefreshStatsButton.tsx
index b82c91acc..ab3a30528 100644
--- a/web/app/pages/Project/View/components/RefreshStatsButton.tsx
+++ b/web/app/pages/Project/View/components/RefreshStatsButton.tsx
@@ -26,11 +26,17 @@ export const RefreshStatsButton = ({ onRefresh }: RefreshStatsButtonProps) => {
useEffect(() => {
let animationFrameId: number
+ let lastRenderedProgress = 0
const animate = () => {
const elapsed = Date.now() - startTimeRef.current
const newProgress = Math.min((elapsed / REFRESH_INTERVAL_MS) * 100, 100)
- setProgress(newProgress)
+
+ // Only update state if progress changed by at least 1% (reduces re-renders)
+ if (Math.abs(newProgress - lastRenderedProgress) >= 1 || newProgress >= 100) {
+ lastRenderedProgress = newProgress
+ setProgress(newProgress)
+ }
// Check if we should trigger auto-refresh
if (newProgress >= 100 && !hasTriggeredRefresh.current && !isRefreshing && !authLoading && !dataLoading) {
diff --git a/web/app/pages/Project/View/components/SearchFilters.tsx b/web/app/pages/Project/View/components/SearchFilters.tsx
index 3828e2ad9..cde55504f 100644
--- a/web/app/pages/Project/View/components/SearchFilters.tsx
+++ b/web/app/pages/Project/View/components/SearchFilters.tsx
@@ -6,9 +6,9 @@ import { useState, useEffect, useCallback, Fragment } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate, useSearchParams } from 'react-router'
-import { getFilters, getErrorsFilters, getVersionFilters } from '~/api'
+import { useFiltersProxy } from '~/hooks/useAnalyticsProxy'
import { FILTERS_PANELS_ORDER, ERRORS_FILTERS_PANELS_ORDER } from '~/lib/constants'
-import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
import FilterValueInput, { filterCategoryIcons, createVersionValue, parseVersionValue } from '~/ui/FilterValueInput'
import Modal from '~/ui/Modal'
@@ -108,7 +108,6 @@ interface SearchFiltersProps {
const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: SearchFiltersProps) => {
const { id } = useCurrentProject()
- const projectPassword = useProjectPassword(id)
const { theme } = useTheme()
const {
t,
@@ -119,6 +118,7 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
const [loadingColumns, setLoadingColumns] = useState<Set<string>>(new Set())
const [searchParams] = useSearchParams()
const navigate = useNavigate()
+ const { fetchFilters, fetchErrorsFilters, fetchVersionFilters } = useFiltersProxy()
const panelOptions = type === 'traffic' ? FILTERS_PANELS_ORDER : ERRORS_FILTERS_PANELS_ORDER
@@ -128,22 +128,26 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
setLoadingColumns((prev) => new Set(prev).add(column))
try {
- let result: string[]
+ let result: string[] = []
// For browser/OS versions, fetch valid combinations from the backend
if (column === 'brv') {
const dataType = type === 'errors' ? 'errors' : 'traffic'
- const pairs = await getVersionFilters(id, dataType, 'br', projectPassword)
- result = pairs.map((p) => createVersionValue(p.name, p.version))
+ const pairs = await fetchVersionFilters(id, dataType, 'br')
+ if (pairs) {
+ result = pairs.map((p) => createVersionValue(p.name, p.version))
+ }
} else if (column === 'osv') {
const dataType = type === 'errors' ? 'errors' : 'traffic'
- const pairs = await getVersionFilters(id, dataType, 'os', projectPassword)
- result = pairs.map((p) => createVersionValue(p.name, p.version))
+ const pairs = await fetchVersionFilters(id, dataType, 'os')
+ if (pairs) {
+ result = pairs.map((p) => createVersionValue(p.name, p.version))
+ }
} else {
if (type === 'errors') {
- result = await getErrorsFilters(id, column, projectPassword)
+ result = (await fetchErrorsFilters(id, column)) || []
} else {
- result = await getFilters(id, column, projectPassword)
+ result = (await fetchFilters(id, column)) || []
}
}
setFilterValuesCache((prev) => ({ ...prev, [column]: result }))
@@ -158,7 +162,7 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
})
}
},
- [id, projectPassword, type, filterValuesCache, loadingColumns],
+ [id, type, filterValuesCache, loadingColumns, fetchFilters, fetchErrorsFilters, fetchVersionFilters],
)
// Pre-fetch all filter values when modal opens
diff --git a/web/app/pages/Project/tabs/Alerts/ProjectAlertsSettings.tsx b/web/app/pages/Project/tabs/Alerts/ProjectAlertsSettings.tsx
index 0eeced497..75f88581e 100644
--- a/web/app/pages/Project/tabs/Alerts/ProjectAlertsSettings.tsx
+++ b/web/app/pages/Project/tabs/Alerts/ProjectAlertsSettings.tsx
@@ -7,16 +7,16 @@ import _size from 'lodash/size'
import _split from 'lodash/split'
import _toNumber from 'lodash/toNumber'
import _values from 'lodash/values'
-import React, { useEffect, useMemo, useState } from 'react'
+import React, { useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { Link } from 'react-router'
+import { Link, useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { createAlert, updateAlert, deleteAlert, CreateAlert, getAlert } from '~/api'
import { QUERY_CONDITION, QUERY_METRIC, QUERY_TIME } from '~/lib/constants'
import { Alerts } from '~/lib/models/Alerts'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
import { useAuth } from '~/providers/AuthProvider'
+import type { ProjectViewActionData } from '~/routes/projects.$id'
import Button from '~/ui/Button'
import Checkbox from '~/ui/Checkbox'
import Input from '~/ui/Input'
@@ -48,6 +48,9 @@ const ProjectAlertsSettings = ({
const { user, isLoading: authLoading } = useAuth()
const { t } = useTranslation('common')
+ const fetcher = useFetcher<ProjectViewActionData>()
+ const lastHandledData = useRef<ProjectViewActionData | null>(null)
+
const [form, setForm] = useState<Partial<Alerts>>({
pid: projectId,
name: '',
@@ -60,7 +63,6 @@ const ProjectAlertsSettings = ({
alertOnNewErrorsOnly: true,
alertOnEveryCustomEvent: false,
})
- const [validated, setValidated] = useState(false)
const [errors, setErrors] = useState<Record<string, string>>({})
const [beenSubmitted, setBeenSubmitted] = useState(false)
const [showModal, setShowModal] = useState(false)
@@ -79,42 +81,55 @@ const ProjectAlertsSettings = ({
)
}, [user])
- const loadAlert = async (id: string) => {
- if (!isSettings) {
- setIsLoading(false)
- return
- }
-
- if (isLoading) {
- return
- }
-
- setIsLoading(true)
-
- try {
- const result = await getAlert(id)
- setAlert(result)
- setForm(result)
- } catch (reason: any) {
- setError(reason)
- } finally {
- setIsLoading(false)
+ // Handle fetcher responses
+ useEffect(() => {
+ if (fetcher.state !== 'idle' || !fetcher.data) return
+ if (lastHandledData.current === fetcher.data) return
+ lastHandledData.current = fetcher.data
+
+ const { intent, success, data, error: fetcherError } = fetcher.data
+
+ if (success) {
+ if (intent === 'get-alert' && data) {
+ const alertData = data as Alerts
+ setAlert(alertData)
+ setForm(alertData)
+ setIsLoading(false)
+ } else if (intent === 'create-alert') {
+ toast.success(t('alertsSettings.alertCreated'))
+ onSave?.()
+ } else if (intent === 'update-alert' && data) {
+ setAlert(data as Alerts)
+ toast.success(t('alertsSettings.alertUpdated'))
+ onSave?.()
+ } else if (intent === 'delete-alert') {
+ toast.success(t('alertsSettings.alertDeleted'))
+ onSave?.()
+ }
+ } else if (fetcherError) {
+ if (intent === 'get-alert') {
+ setError(fetcherError)
+ setIsLoading(false)
+ } else {
+ toast.error(fetcherError)
+ }
}
- }
+ }, [fetcher.state, fetcher.data, t, onSave])
useEffect(() => {
if (authLoading) {
return
}
- if (alertId) {
- loadAlert(alertId)
+ if (alertId && isSettings) {
+ setIsLoading(true)
+ fetcher.submit({ intent: 'get-alert', alertId }, { method: 'POST', action: `/projects/${projectId}` })
} else {
setIsLoading(false)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [authLoading, alertId, isSettings])
+ }, [authLoading, alertId, isSettings, projectId])
const queryTimeTMapping: Record<string, string> = useMemo(() => {
const values = _values(QUERY_TIME)
@@ -223,63 +238,18 @@ const ProjectAlertsSettings = ({
const valid = _isEmpty(_keys(allErrors))
setErrors(allErrors)
- setValidated(valid)
- }
- const onSubmit = (data: Partial<Alerts>) => {
- let submissionData = { ...data }
- if (data.queryMetric === QUERY_METRIC.ERRORS) {
- submissionData = {
- ...submissionData,
- queryCondition: null,
- queryValue: null,
- queryTime: null,
- }
- } else if (data.queryMetric === QUERY_METRIC.CUSTOM_EVENTS && data.alertOnEveryCustomEvent) {
- submissionData = {
- ...submissionData,
- queryCondition: null,
- queryValue: null,
- queryTime: null,
- }
- }
-
- if (isSettings && alertId) {
- updateAlert(alertId, submissionData)
- .then((res) => {
- setAlert(res)
- toast.success(t('alertsSettings.alertUpdated'))
- onSave?.()
- })
- .catch((reason) => {
- toast.error(reason.message || reason || 'Something went wrong')
- })
- } else {
- createAlert(submissionData as CreateAlert)
- .then(() => {
- toast.success(t('alertsSettings.alertCreated'))
- onSave?.()
- })
- .catch((reason) => {
- toast.error(reason.message || reason || 'Something went wrong')
- })
- }
+ return valid
}
+ const shouldIncludeQueryFields =
+ form.queryMetric !== QUERY_METRIC.ERRORS &&
+ !(form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS && form.alertOnEveryCustomEvent)
+
const onDeleteAlert = () => {
- if (!alertId) {
- toast.error('Something went wrong')
- return
- }
+ if (!alertId || fetcher.state !== 'idle') return
- deleteAlert(alertId)
- .then(() => {
- toast.success(t('alertsSettings.alertDeleted'))
- onSave?.()
- })
- .catch((reason) => {
- toast.error(reason.message || reason || 'Something went wrong')
- })
+ fetcher.submit({ intent: 'delete-alert', alertId }, { method: 'POST', action: `/projects/${projectId}` })
}
useEffect(() => {
@@ -296,29 +266,12 @@ const ProjectAlertsSettings = ({
}
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
- e.preventDefault()
- e.stopPropagation()
setBeenSubmitted(true)
- let currentForm = { ...form }
- if (form.queryMetric === QUERY_METRIC.ERRORS) {
- currentForm = {
- ...currentForm,
- queryCondition: null,
- queryValue: null,
- queryTime: null,
- }
- } else if (form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS && form.alertOnEveryCustomEvent) {
- currentForm = {
- ...currentForm,
- queryCondition: null,
- queryValue: null,
- queryTime: null,
- }
- }
+ const isValid = validate()
- if (validated) {
- onSubmit(currentForm)
+ if (!isValid) {
+ e.preventDefault()
}
}
@@ -387,7 +340,17 @@ const ProjectAlertsSettings = ({
</Text>
}
/>
- <form className='w-full pb-4' onSubmit={handleSubmit}>
+ <fetcher.Form method='POST' action={`/projects/${projectId}`} className='w-full pb-4' onSubmit={handleSubmit}>
+ <input type='hidden' name='intent' value={isSettings && alertId ? 'update-alert' : 'create-alert'} />
+ {isSettings && alertId ? <input type='hidden' name='alertId' value={alertId} /> : null}
+ <input type='hidden' name='queryMetric' value={form.queryMetric || QUERY_METRIC.PAGE_VIEWS} />
+ {shouldIncludeQueryFields && form.queryCondition ? (
+ <input type='hidden' name='queryCondition' value={form.queryCondition} />
+ ) : null}
+ {shouldIncludeQueryFields && form.queryTime ? (
+ <input type='hidden' name='queryTime' value={form.queryTime} />
+ ) : null}
+
{!authLoading && !isIntegrationLinked ? (
<div className='mt-2 flex items-center rounded-sm bg-blue-50 px-5 py-3 text-base whitespace-pre-wrap dark:bg-slate-800 dark:text-gray-50'>
<ExclamationTriangleIcon className='mr-1 h-5 w-5' />
@@ -577,7 +540,7 @@ const ProjectAlertsSettings = ({
</Button>
</div>
)}
- </form>
+ </fetcher.Form>
<Modal
onClose={() => setShowModal(false)}
onSubmit={onDeleteAlert}
diff --git a/web/app/pages/Project/tabs/Alerts/ProjectAlertsView.tsx b/web/app/pages/Project/tabs/Alerts/ProjectAlertsView.tsx
index b073c6637..c825f3ceb 100644
--- a/web/app/pages/Project/tabs/Alerts/ProjectAlertsView.tsx
+++ b/web/app/pages/Project/tabs/Alerts/ProjectAlertsView.tsx
@@ -17,17 +17,18 @@ import {
FileTextIcon,
BellOffIcon,
} from 'lucide-react'
-import { useMemo, useState, useEffect } from 'react'
+import { useMemo, useState, useEffect, useRef, Suspense, use } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link, useSearchParams } from 'react-router'
+import { Link, useSearchParams, useFetcher, useLoaderData, useRevalidator } from 'react-router'
import { toast } from 'sonner'
-import { deleteAlert as deleteAlertApi, getProjectAlerts } from '~/api'
+import type { AlertsResponse } from '~/api/api.server'
import { QUERY_METRIC, PLAN_LIMITS, DEFAULT_ALERTS_TAKE } from '~/lib/constants'
import { Alerts } from '~/lib/models/Alerts'
import PaidFeature from '~/modals/PaidFeature'
import { useAuth } from '~/providers/AuthProvider'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+import type { ProjectLoaderData, ProjectViewActionData } from '~/routes/projects.$id'
import { Badge, type BadgeProps } from '~/ui/Badge'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
@@ -211,20 +212,48 @@ const AlertRow = ({
)
}
-const ProjectAlerts = () => {
+interface DeferredAlertsData {
+ alertsData: AlertsResponse | null
+}
+
+function AlertsDataResolver({ children }: { children: (data: DeferredAlertsData) => React.ReactNode }) {
+ const { alertsData: alertsDataPromise } = useLoaderData<ProjectLoaderData>()
+ const alertsData = alertsDataPromise ? use(alertsDataPromise) : null
+ return <>{children({ alertsData })}</>
+}
+
+function ProjectAlertsWrapper() {
+ return (
+ <Suspense fallback={<Loader />}>
+ <AlertsDataResolver>{(deferredData) => <ProjectAlertsInner deferredData={deferredData} />}</AlertsDataResolver>
+ </Suspense>
+ )
+}
+
+interface ProjectAlertsInnerProps {
+ deferredData: DeferredAlertsData
+}
+
+const ProjectAlertsInner = ({ deferredData }: ProjectAlertsInnerProps) => {
const { id, project } = useCurrentProject()
+ const revalidator = useRevalidator()
const { t } = useTranslation()
const { user, isAuthenticated } = useAuth()
const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)
const [searchParams, setSearchParams] = useSearchParams()
+ const fetcher = useFetcher<ProjectViewActionData>()
+ const lastHandledData = useRef<ProjectViewActionData | null>(null)
- const [isLoading, setIsLoading] = useState<boolean | null>(null)
- const [total, setTotal] = useState(0)
- const [alerts, setAlerts] = useState<Alerts[]>([])
+ // Track if we're in pagination mode
+ const [isSearchMode, setIsSearchMode] = useState(false)
+ const [total, setTotal] = useState(() => deferredData.alertsData?.total || 0)
+ const [alerts, setAlerts] = useState<Alerts[]>(() => deferredData.alertsData?.results || [])
const [page, setPage] = useState(1)
const [error, setError] = useState<string | null>(null)
+ const isLoading = revalidator.state === 'loading' || fetcher.state !== 'idle'
+
const pageAmount = Math.ceil(total / DEFAULT_ALERTS_TAKE)
const limits = PLAN_LIMITS[user?.planCode || 'trial']
@@ -245,30 +274,58 @@ const ProjectAlerts = () => {
return newSearchParams.toString()
}, [searchParams])
- const loadAlerts = async (take: number, skip: number) => {
- if (isLoading) {
- return
- }
- setIsLoading(true)
-
- try {
- const result = await getProjectAlerts(id, take, skip)
- setAlerts(result.results)
- setTotal(result.total)
- } catch (reason: any) {
- setError(reason)
- } finally {
- setIsLoading(false)
+ // Sync state when loader provides new data
+ useEffect(() => {
+ if (deferredData.alertsData && revalidator.state === 'idle' && !isSearchMode) {
+ setAlerts(deferredData.alertsData.results || [])
+ setTotal(deferredData.alertsData.total || 0)
}
+ }, [revalidator.state, deferredData.alertsData, isSearchMode])
+
+ const loadAlerts = (take: number, skip: number) => {
+ if (fetcher.state !== 'idle') return
+ setIsSearchMode(true)
+
+ fetcher.submit(
+ { intent: 'get-project-alerts', take: String(take), skip: String(skip) },
+ { method: 'POST', action: `/projects/${id}` },
+ )
}
+ // Handle fetcher responses
useEffect(() => {
- if (!canManageAlerts) {
- return
+ if (fetcher.state !== 'idle' || !fetcher.data) return
+ if (lastHandledData.current === fetcher.data) return
+ lastHandledData.current = fetcher.data
+
+ const { intent, success, data, error: fetcherError } = fetcher.data
+
+ if (success) {
+ if (intent === 'get-project-alerts' && data) {
+ const result = data as { results: Alerts[]; total: number }
+ setAlerts(result.results)
+ setTotal(result.total)
+ } else if (intent === 'delete-alert') {
+ toast.success(t('alertsSettings.alertDeleted'))
+ if (page === 1) {
+ setIsSearchMode(false)
+ revalidator.revalidate()
+ } else {
+ loadAlerts(DEFAULT_ALERTS_TAKE, (page - 1) * DEFAULT_ALERTS_TAKE)
+ }
+ }
+ } else if (fetcherError) {
+ setError(fetcherError)
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetcher.state, fetcher.data, t, page, revalidator])
- loadAlerts(DEFAULT_ALERTS_TAKE, (page - 1) * DEFAULT_ALERTS_TAKE)
-
+ // Handle page changes - use fetcher for pagination
+ useEffect(() => {
+ if (!canManageAlerts) return
+ if (page > 1 || isSearchMode) {
+ loadAlerts(DEFAULT_ALERTS_TAKE, (page - 1) * DEFAULT_ALERTS_TAKE)
+ }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page, canManageAlerts])
@@ -322,20 +379,20 @@ const ProjectAlerts = () => {
const handleAlertSaved = () => {
closeAlertSettings()
// Reload alerts after saving
- loadAlerts(DEFAULT_ALERTS_TAKE, (page - 1) * DEFAULT_ALERTS_TAKE)
- }
-
- const onDelete = async (alertId: string) => {
- try {
- await deleteAlertApi(alertId)
- toast.success(t('alertsSettings.alertDeleted'))
- // Reload alerts after deletion
+ if (page === 1) {
+ setIsSearchMode(false)
+ revalidator.revalidate()
+ } else {
loadAlerts(DEFAULT_ALERTS_TAKE, (page - 1) * DEFAULT_ALERTS_TAKE)
- } catch (reason: any) {
- toast.error(reason?.response?.data?.message || reason?.message || 'Something went wrong')
}
}
+ const onDelete = (alertId: string) => {
+ if (fetcher.state !== 'idle') return
+
+ fetcher.submit({ intent: 'delete-alert', alertId }, { method: 'POST', action: `/projects/${id}` })
+ }
+
if (!canManageAlerts) {
return (
<div className='mt-5 rounded-lg bg-gray-700 p-5'>
@@ -355,7 +412,7 @@ const ProjectAlerts = () => {
)
}
- if (error && isLoading === false) {
+ if (error && !isLoading) {
return (
<StatusPage
type='error'
@@ -369,14 +426,6 @@ const ProjectAlerts = () => {
)
}
- if (isLoading || isLoading === null) {
- return (
- <div className='mt-4'>
- <Loader />
- </div>
- )
- }
-
// Show alert settings view when editing or creating an alert
if (activeAlertId || isCreatingAlert) {
return (
@@ -456,4 +505,6 @@ const ProjectAlerts = () => {
)
}
+const ProjectAlerts = ProjectAlertsWrapper
+
export default ProjectAlerts
diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
index ab201fff1..5c8463075 100644
--- a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
+++ b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
@@ -23,21 +23,13 @@ import {
import { marked } from 'marked'
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSearchParams } from 'react-router'
+import { useSearchParams, useFetcher } from 'react-router'
import sanitizeHtml from 'sanitize-html'
import { toast } from 'sonner'
import { useStickToBottom } from 'use-stick-to-bottom'
-import {
- askAI,
- getRecentAIChats,
- getAllAIChats,
- getAIChat,
- createAIChat,
- updateAIChat,
- deleteAIChat,
- AIChatSummary,
-} from '~/api'
+import { askAI } from '~/api'
+import { ProjectViewActionData } from '~/routes/projects.$id'
import SwetrixLogo from '~/ui/icons/SwetrixLogo'
import Modal from '~/ui/Modal'
import { Text } from '~/ui/Text'
@@ -53,6 +45,13 @@ interface MessagePart {
args?: unknown
}
+interface AIChatSummary {
+ id: string
+ name: string | null
+ created: string
+ updated: string
+}
+
interface Message {
id: string
role: 'user' | 'assistant'
@@ -474,6 +473,16 @@ const getSuggestionPrompts = (t: any) => [
t('project.askAi.suggestions.deviceTypesChart'),
]
+interface AIChat {
+ id: string
+ name: string | null
+ messages: { role: 'user' | 'assistant'; content: string }[]
+ isOwner?: boolean
+ branched?: boolean
+ created: string
+ updated: string
+}
+
const AskAIView = ({ projectId }: AskAIViewProps) => {
const { t } = useTranslation('common')
const [searchParams, setSearchParams] = useSearchParams()
@@ -490,11 +499,20 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const [recentChats, setRecentChats] = useState<AIChatSummary[]>([])
const [allChats, setAllChats] = useState<AIChatSummary[]>([])
const [allChatsTotal, setAllChatsTotal] = useState(0)
- const [isLoadingChats, setIsLoadingChats] = useState(false)
const [isViewAllModalOpen, setIsViewAllModalOpen] = useState(false)
const [chatToDelete, setChatToDelete] = useState<string | null>(null)
const hasInitializedRef = useRef(false)
+ const recentChatsFetcher = useFetcher<ProjectViewActionData>()
+ const allChatsFetcher = useFetcher<ProjectViewActionData>()
+ const loadChatFetcher = useFetcher<ProjectViewActionData>()
+ const saveChatFetcher = useFetcher<ProjectViewActionData>()
+ const deleteChatFetcher = useFetcher<ProjectViewActionData>()
+ const lastProcessedSaveDataRef = useRef<ProjectViewActionData | null>(null)
+ const lastProcessedLoadDataRef = useRef<ProjectViewActionData | null>(null)
+
+ const isLoadingChats = allChatsFetcher.state !== 'idle'
+
const { scrollRef, contentRef, isAtBottom, scrollToBottom } = useStickToBottom({
resize: 'smooth',
initial: 'smooth',
@@ -508,39 +526,92 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const generateMessageId = () => `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
- const loadRecentChats = useCallback(async () => {
- try {
- const chats = await getRecentAIChats(projectId, 3)
- setRecentChats(chats)
- } catch (err) {
- console.error('Failed to load recent chats:', err)
+ const loadRecentChats = useCallback(() => {
+ if (recentChatsFetcher.state !== 'idle') return
+
+ const formData = new FormData()
+ formData.append('intent', 'get-recent-ai-chats')
+ formData.append('limit', '3')
+
+ recentChatsFetcher.submit(formData, { method: 'POST' })
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [recentChatsFetcher.submit])
+
+ // Handle recent chats fetcher response
+ useEffect(() => {
+ if (recentChatsFetcher.state === 'idle' && recentChatsFetcher.data) {
+ if (recentChatsFetcher.data.success && recentChatsFetcher.data.data) {
+ setRecentChats(recentChatsFetcher.data.data as AIChatSummary[])
+ }
}
- }, [projectId])
+ }, [recentChatsFetcher.state, recentChatsFetcher.data])
const loadAllChats = useCallback(
- async (skip: number = 0) => {
- setIsLoadingChats(true)
- try {
- const result = await getAllAIChats(projectId, skip, 20)
- if (skip === 0) {
+ (skip: number = 0) => {
+ if (allChatsFetcher.state !== 'idle') return
+
+ const formData = new FormData()
+ formData.append('intent', 'get-all-ai-chats')
+ formData.append('skip', skip.toString())
+ formData.append('take', '20')
+
+ allChatsFetcher.submit(formData, { method: 'POST' })
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [allChatsFetcher.submit],
+ )
+
+ // Handle all chats fetcher response
+ const [pendingAllChatsSkip, setPendingAllChatsSkip] = useState<number | null>(null)
+
+ useEffect(() => {
+ if (allChatsFetcher.state === 'idle' && allChatsFetcher.data) {
+ if (allChatsFetcher.data.success && allChatsFetcher.data.data) {
+ const result = allChatsFetcher.data.data as { chats: AIChatSummary[]; total: number }
+ if (pendingAllChatsSkip === 0) {
setAllChats(result.chats)
} else {
setAllChats((prev) => [...prev, ...result.chats])
}
setAllChatsTotal(result.total)
- } catch (err) {
- console.error('Failed to load all chats:', err)
- } finally {
- setIsLoadingChats(false)
}
+ setPendingAllChatsSkip(null)
+ }
+ }, [allChatsFetcher.state, allChatsFetcher.data, pendingAllChatsSkip])
+
+ const loadAllChatsWithSkip = useCallback(
+ (skip: number) => {
+ if (allChatsFetcher.state !== 'idle') return
+
+ setPendingAllChatsSkip(skip)
+ loadAllChats(skip)
},
- [projectId],
+ [allChatsFetcher.state, loadAllChats],
)
const loadChat = useCallback(
- async (chatId: string) => {
- try {
- const chat = await getAIChat(projectId, chatId)
+ (chatId: string) => {
+ if (loadChatFetcher.state !== 'idle') return
+
+ const formData = new FormData()
+ formData.append('intent', 'get-ai-chat')
+ formData.append('chatId', chatId)
+
+ loadChatFetcher.submit(formData, { method: 'POST' })
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [loadChatFetcher.submit],
+ )
+
+ // Handle load chat fetcher response
+ useEffect(() => {
+ if (loadChatFetcher.state === 'idle' && loadChatFetcher.data) {
+ // Skip if we've already processed this response
+ if (lastProcessedLoadDataRef.current === loadChatFetcher.data) return
+ lastProcessedLoadDataRef.current = loadChatFetcher.data
+
+ if (loadChatFetcher.data.success && loadChatFetcher.data.data) {
+ const chat = loadChatFetcher.data.data as AIChat
setMessages(
chat.messages.map((m) => ({
id: generateMessageId(),
@@ -548,19 +619,47 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
content: m.content,
})),
)
- setCurrentChatId(chatId)
- } catch (err) {
- console.error('Failed to load chat:', err)
+ setCurrentChatId(chat.id)
+ } else if (loadChatFetcher.data.error) {
+ console.error('Failed to load chat:', loadChatFetcher.data.error)
const newParams = new URLSearchParams(searchParams)
newParams.delete('chat')
setSearchParams(newParams)
}
+ }
+ }, [loadChatFetcher.state, loadChatFetcher.data, searchParams, setSearchParams])
+
+ const loadChatById = useCallback(
+ (chatId: string) => {
+ loadChat(chatId)
},
- [projectId, searchParams, setSearchParams],
+ [loadChat],
)
+ // Handle save chat fetcher response
+ useEffect(() => {
+ if (saveChatFetcher.state === 'idle' && saveChatFetcher.data) {
+ // Skip if we've already processed this response
+ if (lastProcessedSaveDataRef.current === saveChatFetcher.data) return
+ lastProcessedSaveDataRef.current = saveChatFetcher.data
+
+ if (saveChatFetcher.data.success && saveChatFetcher.data.data) {
+ const result = saveChatFetcher.data.data as AIChat
+ if (result.branched || !currentChatId) {
+ setCurrentChatId(result.id)
+ const newParams = new URLSearchParams(searchParams)
+ newParams.set('chat', result.id)
+ setSearchParams(newParams, { replace: true })
+ }
+ loadRecentChats()
+ } else if (saveChatFetcher.data.error) {
+ console.error('Failed to save chat:', saveChatFetcher.data.error)
+ }
+ }
+ }, [saveChatFetcher.state, saveChatFetcher.data, currentChatId, searchParams, setSearchParams, loadRecentChats])
+
const saveChat = useCallback(
- async (messagesToSave: Message[]) => {
+ (messagesToSave: Message[]) => {
const apiMessages = messagesToSave
.filter((m) => m.content.trim().length > 0)
.map((m) => ({
@@ -570,30 +669,20 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
if (apiMessages.length === 0) return
- try {
- if (currentChatId) {
- const result = await updateAIChat(projectId, currentChatId, { messages: apiMessages })
-
- // If the chat was branched (user didn't own the original), update to the new chat ID
- if (result.branched) {
- setCurrentChatId(result.id)
- const newParams = new URLSearchParams(searchParams)
- newParams.set('chat', result.id)
- setSearchParams(newParams, { replace: true })
- }
- } else {
- const chat = await createAIChat(projectId, apiMessages)
- setCurrentChatId(chat.id)
- const newParams = new URLSearchParams(searchParams)
- newParams.set('chat', chat.id)
- setSearchParams(newParams, { replace: true })
- }
- loadRecentChats()
- } catch (err) {
- console.error('Failed to save chat:', err)
+ const formData = new FormData()
+ formData.append('messages', JSON.stringify(apiMessages))
+
+ if (currentChatId) {
+ formData.append('intent', 'update-ai-chat')
+ formData.append('chatId', currentChatId)
+ } else {
+ formData.append('intent', 'create-ai-chat')
}
+
+ saveChatFetcher.submit(formData, { method: 'POST' })
},
- [projectId, currentChatId, searchParams, setSearchParams, loadRecentChats],
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [saveChatFetcher.submit, currentChatId],
)
useEffect(() => {
@@ -602,12 +691,12 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const chatId = searchParams.get('chat')
if (chatId) {
- loadChat(chatId)
+ loadChatById(chatId)
}
loadRecentChats()
- }, [searchParams, loadChat, loadRecentChats])
+ }, [searchParams, loadChatById, loadRecentChats])
- const handleNewChat = () => {
+ const handleNewChat = useCallback(() => {
setMessages([])
setCurrentChatId(null)
setStreamingMessage(null)
@@ -615,34 +704,60 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const newParams = new URLSearchParams(searchParams)
newParams.delete('chat')
setSearchParams(newParams)
- }
+ }, [searchParams, setSearchParams])
const handleOpenChat = (chatId: string) => {
setIsViewAllModalOpen(false)
- loadChat(chatId)
+ loadChatById(chatId)
const newParams = new URLSearchParams(searchParams)
newParams.set('chat', chatId)
setSearchParams(newParams)
}
- const handleDeleteChat = async (chatId: string) => {
- try {
- await deleteAIChat(projectId, chatId)
- toast.success(t('project.askAi.chatDeleted'))
+ // Handle delete chat fetcher response
+ const [deletingChatId, setDeletingChatId] = useState<string | null>(null)
- if (chatId === currentChatId) {
- handleNewChat()
- }
+ useEffect(() => {
+ if (deleteChatFetcher.state === 'idle' && deleteChatFetcher.data) {
+ if (deleteChatFetcher.data.success) {
+ toast.success(t('project.askAi.chatDeleted'))
+
+ if (deletingChatId === currentChatId) {
+ handleNewChat()
+ }
- loadRecentChats()
- if (isViewAllModalOpen) {
- loadAllChats(0)
+ loadRecentChats()
+ if (isViewAllModalOpen) {
+ loadAllChatsWithSkip(0)
+ }
+ } else if (deleteChatFetcher.data.error) {
+ console.error('Failed to delete chat:', deleteChatFetcher.data.error)
}
- } catch (err) {
- console.error('Failed to delete chat:', err)
- } finally {
+ setDeletingChatId(null)
setChatToDelete(null)
}
+ }, [
+ deleteChatFetcher.state,
+ deleteChatFetcher.data,
+ deletingChatId,
+ currentChatId,
+ isViewAllModalOpen,
+ loadRecentChats,
+ loadAllChatsWithSkip,
+ t,
+ handleNewChat,
+ ])
+
+ const handleDeleteChat = (chatId: string) => {
+ if (deleteChatFetcher.state !== 'idle') return
+
+ setDeletingChatId(chatId)
+
+ const formData = new FormData()
+ formData.append('intent', 'delete-ai-chat')
+ formData.append('chatId', chatId)
+
+ deleteChatFetcher.submit(formData, { method: 'POST' })
}
const handleSubmit = async (e?: React.FormEvent) => {
@@ -793,7 +908,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
streamingPartsRef.current.push({ type: 'text', text: currentTextPartRef.current })
}
- if (finalContent.trim()) {
+ if (finalContent.trim() || streamingToolCallsRef.current.length > 0) {
const assistantMessage: Message = {
id: generateMessageId(),
role: 'assistant',
@@ -1060,7 +1175,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
type='button'
onClick={() => {
setIsViewAllModalOpen(true)
- loadAllChats(0)
+ loadAllChatsWithSkip(0)
}}
className='text-sm font-medium text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
>
@@ -1134,7 +1249,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
{allChats.length < allChatsTotal ? (
<button
type='button'
- onClick={() => loadAllChats(allChats.length)}
+ onClick={() => loadAllChatsWithSkip(allChats.length)}
disabled={isLoadingChats}
className='flex w-full items-center justify-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50 disabled:opacity-50 dark:border-slate-800/50 dark:bg-slate-800 dark:text-gray-200 hover:dark:bg-slate-700'
>
diff --git a/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx b/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx
index 8dcd73efc..ee210a93f 100644
--- a/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx
+++ b/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx
@@ -4,11 +4,11 @@ import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _map from 'lodash/map'
import { CompassIcon, MapPinIcon, MonitorCog, TabletSmartphoneIcon } from 'lucide-react'
-import { useState, useEffect, useMemo, useContext } from 'react'
+import { useState, useEffect, useMemo, useContext, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useSearchParams } from 'react-router'
-import { getCaptchaData } from '~/api'
+import { useCaptchaProxy } from '~/hooks/useAnalyticsProxy'
import useSize from '~/hooks/useSize'
import { chartTypes, BROWSER_LOGO_MAP, OS_LOGO_MAP, OS_LOGO_MAP_DARK } from '~/lib/constants'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
@@ -22,7 +22,7 @@ import Filters from '../../View/components/Filters'
import { Filter } from '../../View/interfaces/traffic'
import { Panel } from '../../View/Panels'
import { parseFilters } from '../../View/utils/filters'
-import { ViewProjectContext } from '../../View/ViewProject'
+import { ViewProjectContext, RefreshTriggersContext } from '../../View/ViewProject'
import { deviceIconMapping } from '../../View/ViewProject.helpers'
import { CaptchaChart } from './CaptchaChart'
@@ -53,9 +53,12 @@ interface CaptchaViewProps {
const CaptchaView = ({ projectId }: CaptchaViewProps) => {
const { theme } = useTheme()
const { project } = useCurrentProject()
- const { period, timeBucket, dateRange, captchaRefreshTrigger, timeFormat, size } = useContext(ViewProjectContext)
+ const { captchaRefreshTrigger } = useContext(RefreshTriggersContext)
+ const { period, timeBucket, dateRange, timeFormat, size } = useContext(ViewProjectContext)
const [searchParams] = useSearchParams()
const isEmbedded = searchParams.get('embedded') === 'true'
+ const isMountedRef = useRef(true)
+ const captchaProxy = useCaptchaProxy()
const {
t,
@@ -84,6 +87,13 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {
const tnMapping = captchaTypeNameMapping(t)
const [ref] = useSize() as any
+ useEffect(() => {
+ isMountedRef.current = true
+ return () => {
+ isMountedRef.current = false
+ }
+ }, [])
+
const getFormatDate = (date: Date) => {
const yyyy = date.getFullYear()
let mm: string | number = date.getMonth() + 1
@@ -97,20 +107,23 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {
setDataLoading(true)
try {
- let data
- let from
- let to
+ 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, '', '')
- }
+ const data = await captchaProxy.fetchCaptcha(projectId, {
+ timeBucket,
+ period: period === 'custom' && dateRange ? '' : period,
+ filters,
+ from: period === 'custom' && dateRange ? from : '',
+ to: period === 'custom' && dateRange ? to : '',
+ })
+
+ if (!isMountedRef.current) return
if (_isEmpty(data)) {
setAnalyticsLoading(false)
@@ -141,6 +154,7 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {
setAnalyticsLoading(false)
setDataLoading(false)
} catch (reason) {
+ if (!isMountedRef.current) return
setAnalyticsLoading(false)
setDataLoading(false)
setIsPanelsDataEmpty(true)
diff --git a/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx b/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx
index d6c4e2272..b0d8149d6 100644
--- a/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx
+++ b/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx
@@ -5,9 +5,9 @@ import { useMemo, useState, useEffect, useCallback, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useLocation } from 'react-router'
-import { getErrorSessions, type ErrorAffectedSession } from '~/api'
+import type { ErrorAffectedSession, ErrorDetailsResponse } from '~/api/api.server'
+import { useErrorSessionsProxy } from '~/hooks/useAnalyticsProxy'
import { BROWSER_LOGO_MAP, OS_LOGO_MAP, OS_LOGO_MAP_DARK } from '~/lib/constants'
-import { SwetrixErrorDetails } from '~/lib/models/Project'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
import { Badge } from '~/ui/Badge'
@@ -20,7 +20,7 @@ import { getRelativeDateIfPossible } from '~/utils/date'
const STACK_PREVIEW_LINES_COUNT = 5
interface ErrorDetailsProps {
- details: SwetrixErrorDetails
+ details: ErrorDetailsResponse['details']
period?: string
from?: string
to?: string
@@ -120,13 +120,13 @@ export const ErrorDetails = ({
from = '',
to = '',
timeBucket = 'hour',
- projectPassword,
}: ErrorDetailsProps) => {
const {
t,
i18n: { language },
} = useTranslation('common')
const { id } = useCurrentProject()
+ const { fetchErrorSessions } = useErrorSessionsProxy()
const [isStackTraceExpanded, setIsStackTraceExpanded] = useState(false)
const [isCopiedStack, setIsCopiedStack] = useState(false)
@@ -230,27 +230,26 @@ export const ErrorDetails = ({
const skip = reset ? 0 : sessionsSkip
try {
- const result = await getErrorSessions(
- id,
- details.eid,
+ const result = await fetchErrorSessions(id, details.eid, {
timeBucket,
period,
from,
to,
- SESSIONS_TAKE,
+ take: SESSIONS_TAKE,
skip,
- projectPassword,
- )
+ })
if (!isMountedRef.current) return
- if (reset) {
- setSessions(result.sessions)
- } else {
- setSessions((prev) => [...prev, ...result.sessions])
+ if (result) {
+ if (reset) {
+ setSessions(result.sessions)
+ } else {
+ setSessions((prev) => [...prev, ...result.sessions])
+ }
+ setSessionsTotal(result.total)
+ setSessionsSkip(skip + SESSIONS_TAKE)
}
- setSessionsTotal(result.total)
- setSessionsSkip(skip + SESSIONS_TAKE)
} catch (reason) {
console.error('[ErrorDetails] Failed to load sessions:', reason)
} finally {
@@ -259,7 +258,7 @@ export const ErrorDetails = ({
}
}
},
- [id, details.eid, timeBucket, period, from, to, projectPassword, sessionsLoading, sessionsSkip],
+ [id, details.eid, timeBucket, period, from, to, sessionsLoading, sessionsSkip, fetchErrorSessions],
)
useEffect(() => {
diff --git a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx b/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
index 3cd5f3866..dfe527e14 100644
--- a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
+++ b/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
@@ -16,13 +16,23 @@ import {
AlertTriangleIcon,
UserIcon,
} from 'lucide-react'
-import { useState, useEffect, useMemo, useRef, useCallback, lazy, Suspense } from 'react'
+import { useState, useEffect, useMemo, useRef, useCallback, lazy, Suspense, use } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link, useLocation, useSearchParams, useNavigate, type LinkProps } from 'react-router'
+import {
+ Link,
+ useLocation,
+ useSearchParams,
+ useNavigate,
+ useFetcher,
+ useLoaderData,
+ useRevalidator,
+ type LinkProps,
+} from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
import { toast } from 'sonner'
-import { getErrors, getErrorOverview, getError, updateErrorStatus, type ErrorOverviewResponse } from '~/api'
+import type { ErrorsResponse, ErrorDetailsResponse, ErrorOverviewResponse } from '~/api/api.server'
+import { useErrorsProxy } from '~/hooks/useAnalyticsProxy'
import {
TimeFormat,
tbsFormatMapper,
@@ -33,7 +43,7 @@ import {
ERROR_PANELS_ORDER,
} from '~/lib/constants'
import { CountryEntry, Entry } from '~/lib/models/Entry'
-import { SwetrixError, SwetrixErrorDetails } from '~/lib/models/Project'
+import { SwetrixError } from '~/lib/models/Project'
import { ErrorChart } from '~/pages/Project/tabs/Errors/ErrorChart'
import { ErrorDetails } from '~/pages/Project/tabs/Errors/ErrorDetails'
import NoErrorDetails from '~/pages/Project/tabs/Errors/NoErrorDetails'
@@ -44,7 +54,7 @@ import Filters from '~/pages/Project/View/components/Filters'
import NoEvents from '~/pages/Project/View/components/NoEvents'
import { Panel, MetadataPanel } from '~/pages/Project/View/Panels'
import { ERROR_FILTERS_MAPPING } from '~/pages/Project/View/utils/filters'
-import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
import {
getFormatDate,
typeNameMapping,
@@ -53,6 +63,7 @@ import {
} from '~/pages/Project/View/ViewProject.helpers'
import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
+import type { ProjectViewActionData, ProjectLoaderData } from '~/routes/projects.$id'
import { Badge } from '~/ui/Badge'
import BillboardChart from '~/ui/BillboardChart'
import Checkbox from '~/ui/Checkbox'
@@ -386,11 +397,51 @@ const ErrorItem = ({ error }: ErrorItemProps) => {
const ERRORS_TAKE = 30
-const ErrorsView = () => {
+interface DeferredErrorsData {
+ errorsData: ErrorsResponse | null
+ errorDetails: ErrorDetailsResponse | null
+ errorOverview: ErrorOverviewResponse | null
+}
+
+function ErrorsDataResolver({ children }: { children: (data: DeferredErrorsData) => React.ReactNode }) {
+ const {
+ errorsData: errorsDataPromise,
+ errorDetails: errorDetailsPromise,
+ errorOverview: errorOverviewPromise,
+ } = useLoaderData<ProjectLoaderData>()
+
+ const errorsData = errorsDataPromise ? use(errorsDataPromise) : null
+ const errorDetails = errorDetailsPromise ? use(errorDetailsPromise) : null
+ const errorOverview = errorOverviewPromise ? use(errorOverviewPromise) : null
+
+ // Memoize deferredData so object identity only changes when contained data changes
+ const deferredData = useMemo(
+ () => ({ errorsData, errorDetails, errorOverview }),
+ [errorsData, errorDetails, errorOverview],
+ )
+
+ return <>{children(deferredData)}</>
+}
+
+function ErrorsViewWrapper() {
+ return (
+ <Suspense fallback={<Loader />}>
+ <ErrorsDataResolver>{(deferredData) => <ErrorsViewInner deferredData={deferredData} />}</ErrorsDataResolver>
+ </Suspense>
+ )
+}
+
+interface ErrorsViewInnerProps {
+ deferredData: DeferredErrorsData
+}
+
+const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
const { id, allowedToManage, project } = useCurrentProject()
const projectPassword = useProjectPassword(id)
- const { errorsRefreshTrigger, timeBucket, timeFormat, period, dateRange, timezone, filters, size } =
- useViewProjectContext()
+ const revalidator = useRevalidator()
+ const errorsProxy = useErrorsProxy()
+ const { errorsRefreshTrigger } = useRefreshTriggers()
+ const { timeBucket, timeFormat, period, dateRange, timezone, filters, size } = useViewProjectContext()
const {
t,
i18n: { language },
@@ -399,31 +450,54 @@ const ErrorsView = () => {
const [searchParams] = useSearchParams()
const isEmbedded = searchParams.get('embedded') === 'true'
const navigate = useNavigate()
+ const errorStatusFetcher = useFetcher<ProjectViewActionData>()
+ const lastHandledStatusData = useRef<ProjectViewActionData | null>(null)
+ const pendingStatusUpdate = useRef<'resolved' | 'active' | null>(null)
const from = dateRange ? getFormatDate(dateRange[0]) : ''
const to = dateRange ? getFormatDate(dateRange[1]) : ''
const tnMapping = typeNameMapping(t)
const rotateXAxis = useMemo(() => size.width > 0 && size.width < 500, [size])
+ // Initialize state from deferred data
+ const initialDataProcessed = useRef(false)
+
const [errorOptions, setErrorOptions] = useState<Record<string, boolean>>({
[ERROR_FILTERS_MAPPING.showResolved]: false,
})
- const [overviewLoading, setOverviewLoading] = useState<boolean | null>(null)
- const [overview, setOverview] = useState<ErrorOverviewResponse | null>(null)
+ // Overview from loader
+ const overview = deferredData.errorOverview
+ const overviewLoading = revalidator.state === 'loading'
+
const isMountedRef = useRef(true)
- const [errorsLoading, setErrorsLoading] = useState<boolean | null>(null)
- const [errors, setErrors] = useState<SwetrixError[]>([])
- const [errorsSkip, setErrorsSkip] = useState(0)
- const [canLoadMoreErrors, setCanLoadMoreErrors] = useState(false)
- const errorsRequestIdRef = useRef(0)
+ const [errorsLoading, setErrorsLoading] = useState<boolean | null>(() => (deferredData.errorsData ? false : null))
+ const [errors, setErrors] = useState<SwetrixError[]>(() => deferredData.errorsData?.errors || [])
+ const [errorsSkip, setErrorsSkip] = useState(() => deferredData.errorsData?.errors?.length || 0)
+ const [canLoadMoreErrors, setCanLoadMoreErrors] = useState(
+ () => (deferredData.errorsData?.errors?.length || 0) >= ERRORS_TAKE,
+ )
const activeEID = useMemo(() => searchParams.get('eid'), [searchParams])
- const prevActiveEIDRef = useRef<string | null>(activeEID)
- const [activeError, setActiveError] = useState<{ details: SwetrixErrorDetails; [key: string]: any } | null>(null)
- const [errorLoading, setErrorLoading] = useState(false)
- const [errorStatusUpdating, setErrorStatusUpdating] = useState(false)
+
+ // Error details from loader
+ const activeError = useMemo(() => {
+ if (deferredData.errorDetails) {
+ return {
+ details: deferredData.errorDetails.details,
+ chart: deferredData.errorDetails.chart,
+ params: deferredData.errorDetails.params,
+ metadata: deferredData.errorDetails.metadata,
+ timeBucket: deferredData.errorDetails.timeBucket,
+ }
+ }
+ return null
+ }, [deferredData.errorDetails])
+
+ const errorLoading = activeEID ? revalidator.state === 'loading' : false
+
+ const errorStatusUpdating = errorStatusFetcher.state !== 'idle'
const [errorsActiveTabs, setErrorsActiveTabs] = useState<{
location: 'cc' | 'rg' | 'ct' | 'lc' | 'map'
@@ -448,113 +522,73 @@ const ErrorsView = () => {
}
}, [])
- const loadOverview = useCallback(async () => {
- if (overviewLoading) return
-
- setOverviewLoading(true)
- try {
- const result = await getErrorOverview(
- id,
- timeBucket,
- period,
- filters,
- errorOptions,
- from,
- to,
- timezone || '',
- projectPassword,
- )
- if (isMountedRef.current) {
- setOverview(result)
- }
- } catch (reason: any) {
- console.error('[ErrorsView] Failed to load overview:', reason)
- if (isMountedRef.current) {
- toast.error(reason?.message || t('apiNotifications.somethingWentWrong'))
- }
- } finally {
- if (isMountedRef.current) {
- setOverviewLoading(false)
- }
+ // Process deferred data on mount
+ useEffect(() => {
+ if (initialDataProcessed.current) return
+ initialDataProcessed.current = true
+
+ if (deferredData.errorsData) {
+ const errorsList = deferredData.errorsData.errors || []
+ setErrors(errorsList)
+ setErrorsSkip(ERRORS_TAKE)
+ setCanLoadMoreErrors(errorsList.length >= ERRORS_TAKE)
+ } else {
+ setErrors([])
+ setCanLoadMoreErrors(false)
}
- }, [id, timeBucket, period, filters, errorOptions, from, to, timezone, projectPassword, overviewLoading, t])
-
- const loadErrors = useCallback(
- async (forcedSkip?: number, override?: boolean) => {
- if (errorsLoading && !override) return
-
- const currentRequestId = ++errorsRequestIdRef.current
- setErrorsLoading(true)
-
- const skip = forcedSkip !== undefined ? forcedSkip : errorsSkip
-
- try {
- const { errors: newErrors } = await getErrors(
- id,
- timeBucket,
- period === 'custom' ? '' : period,
- filters,
- errorOptions,
- from,
- to,
- ERRORS_TAKE,
- skip,
- timezone || '',
- projectPassword,
- )
-
- if (!isMountedRef.current || currentRequestId !== errorsRequestIdRef.current) return
+ setErrorsLoading(false)
+ }, [deferredData])
- if (skip === 0) {
- setErrors(newErrors)
- } else {
- setErrors((prev) => [...prev, ...newErrors])
- }
-
- setErrorsSkip(skip + ERRORS_TAKE)
- setCanLoadMoreErrors(newErrors.length >= ERRORS_TAKE)
- } catch (reason: any) {
- console.error('[ErrorsView] Failed to load errors:', reason)
- if (isMountedRef.current && currentRequestId === errorsRequestIdRef.current) {
- toast.error(reason?.message || t('apiNotifications.somethingWentWrong'))
- }
- } finally {
- if (isMountedRef.current && currentRequestId === errorsRequestIdRef.current) {
- setErrorsLoading(false)
- }
+ // Sync state when revalidation completes with new data
+ useEffect(() => {
+ if (!initialDataProcessed.current) return
+ if (revalidator.state === 'idle') {
+ if (deferredData.errorsData) {
+ const errorsList = deferredData.errorsData.errors || []
+ setErrors(errorsList)
+ setErrorsSkip(ERRORS_TAKE)
+ setCanLoadMoreErrors(errorsList.length >= ERRORS_TAKE)
+ } else {
+ setErrors([])
+ setCanLoadMoreErrors(false)
}
- },
- [id, timeBucket, period, filters, errorOptions, from, to, timezone, projectPassword, errorsLoading, errorsSkip, t],
- )
-
- const loadError = useCallback(
- async (eid: string) => {
- setErrorLoading(true)
-
- try {
- let error
- if (period === 'custom' && dateRange) {
- error = await getError(id, eid, timeBucket, '', filters, from, to, timezone, projectPassword)
- } else {
- error = await getError(id, eid, timeBucket, period, filters, '', '', timezone, projectPassword)
- }
+ setErrorsLoading(false)
+ } else if (revalidator.state === 'loading') {
+ setErrorsLoading(true)
+ }
+ }, [revalidator.state, deferredData])
+
+ // Load more errors via proxy
+ const loadMoreErrors = useCallback(() => {
+ if (errorsLoading) return
+
+ errorsProxy.fetchErrors(id, {
+ timeBucket,
+ period: period === 'custom' ? '' : period,
+ from: from || undefined,
+ to: to || undefined,
+ timezone: timezone || '',
+ filters,
+ take: ERRORS_TAKE,
+ skip: errorsSkip,
+ options: errorOptions,
+ })
+ }, [id, timeBucket, period, from, to, timezone, filters, errorsSkip, errorOptions, errorsLoading, errorsProxy])
- setActiveError(error)
- } catch (reason: any) {
- if (reason?.status === 400) {
- setErrorLoading(false)
- setActiveError(null)
- return
- }
+ // Handle proxy response for pagination
+ useEffect(() => {
+ if (revalidator.state === 'loading') return
- const message = _isEmpty(reason.data?.message) ? reason.data : reason.data.message
- console.error('[ErrorsView] Failed to load error:', message)
- toast.error(message)
- }
- setErrorLoading(false)
- },
- [dateRange, id, period, timeBucket, projectPassword, timezone, filters, from, to],
- )
+ if (errorsProxy.data && !errorsProxy.isLoading) {
+ const newErrors = errorsProxy.data.errors || []
+ setErrors((prev) => [...prev, ...newErrors])
+ setErrorsSkip((prev) => prev + ERRORS_TAKE)
+ setCanLoadMoreErrors(newErrors.length >= ERRORS_TAKE)
+ }
+ if (errorsProxy.error) {
+ toast.error(errorsProxy.error)
+ }
+ }, [errorsProxy.data, errorsProxy.error, errorsProxy.isLoading, revalidator.state])
const updateStatusInErrors = useCallback(
(status: 'active' | 'resolved') => {
@@ -572,44 +606,48 @@ const ErrorsView = () => {
[activeError?.details?.eid],
)
- const markErrorAsResolved = async () => {
- if (errorStatusUpdating || !activeEID || !activeError?.details?.eid) return
+ // Handle error status update response
+ useEffect(() => {
+ if (errorStatusFetcher.state !== 'idle' || !errorStatusFetcher.data) return
+ if (lastHandledStatusData.current === errorStatusFetcher.data) return
+ lastHandledStatusData.current = errorStatusFetcher.data
+
+ const { intent, success, error } = errorStatusFetcher.data
- setErrorStatusUpdating(true)
-
- try {
- await updateErrorStatus(id, 'resolved', activeEID)
- await loadError(activeEID)
- updateStatusInErrors('resolved')
- } catch (reason) {
- console.error('[markErrorAsResolved]', reason)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.updateErrorStatusFailed'))
- setErrorStatusUpdating(false)
- return
+ if (intent === 'update-error-status') {
+ if (success && pendingStatusUpdate.current) {
+ updateStatusInErrors(pendingStatusUpdate.current)
+ if (activeEID) {
+ revalidator.revalidate()
+ }
+ toast.success(t('apiNotifications.errorStatusUpdated'))
+ pendingStatusUpdate.current = null
+ } else if (error) {
+ toast.error(error)
+ pendingStatusUpdate.current = null
+ }
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [errorStatusFetcher.state, errorStatusFetcher.data, t, activeEID])
- toast.success(t('apiNotifications.errorStatusUpdated'))
- setErrorStatusUpdating(false)
+ const markErrorAsResolved = () => {
+ if (errorStatusUpdating || !activeEID || !activeError?.details?.eid) return
+
+ pendingStatusUpdate.current = 'resolved'
+ errorStatusFetcher.submit(
+ { intent: 'update-error-status', eid: activeEID, status: 'resolved' },
+ { method: 'POST', action: `/projects/${id}` },
+ )
}
- const markErrorAsActive = async () => {
+ const markErrorAsActive = () => {
if (errorStatusUpdating || !activeEID || !activeError?.details?.eid) return
- setErrorStatusUpdating(true)
-
- try {
- await updateErrorStatus(id, 'active', activeEID)
- await loadError(activeEID)
- updateStatusInErrors('active')
- } catch (reason) {
- console.error('[markErrorAsActive]', reason)
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.updateErrorStatusFailed'))
- setErrorStatusUpdating(false)
- return
- }
-
- toast.success(t('apiNotifications.errorStatusUpdated'))
- setErrorStatusUpdating(false)
+ pendingStatusUpdate.current = 'active'
+ errorStatusFetcher.submit(
+ { intent: 'update-error-status', eid: activeEID, status: 'active' },
+ { method: 'POST', action: `/projects/${id}` },
+ )
}
const switchActiveErrorFilter = useMemo(
@@ -631,47 +669,11 @@ const ErrorsView = () => {
]
}, [t, errorOptions])
- // Load data on mount and when params change (only for list view)
+ // Handle refresh trigger - use revalidator for URL-based data
useEffect(() => {
- if (!id || !timeBucket || !period || activeEID) return
-
- loadOverview()
- setErrorsSkip(0)
- loadErrors(0, true)
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [id, period, from, to, timeBucket, timezone, filters, errorOptions])
-
- // Handle activeEID changes
- useEffect(() => {
- if (!activeEID) {
- setActiveError(null)
- // Coming back from error detail to list: reset and reload
- if (prevActiveEIDRef.current) {
- setErrorsSkip(0)
- loadErrors(0, true)
- loadOverview()
- }
- prevActiveEIDRef.current = null
- return
+ if (errorsRefreshTrigger > 0) {
+ revalidator.revalidate()
}
-
- loadError(activeEID)
- prevActiveEIDRef.current = activeEID
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [period, dateRange, timeBucket, activeEID, filters])
-
- // Handle refresh trigger (list + detail)
- useEffect(() => {
- if (errorsRefreshTrigger <= 0) return
-
- if (activeEID) {
- loadError(activeEID)
- return
- }
-
- setErrorsSkip(0)
- loadErrors(0, true)
- loadOverview()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [errorsRefreshTrigger])
@@ -683,7 +685,17 @@ const ErrorsView = () => {
})
}, [overview?.chart, timeBucket, timeFormat, t])
- const hasErrors = !_isEmpty(errors) || overview?.stats?.totalErrors
+ const hasErrorsRaw = !_isEmpty(errors) || overview?.stats?.totalErrors
+
+ // Track if we've ever shown actual content to prevent NoEvents flash during exit animation
+ const hasShownContentRef = useRef(false)
+
+ if (hasErrorsRaw) {
+ hasShownContentRef.current = true
+ }
+
+ // Don't show NoEvents if we've previously shown content (prevents flash during tab switch)
+ const hasErrors = hasErrorsRaw || hasShownContentRef.current
const getFilterLink = useCallback(
(column: string, value: string | null): LinkProps['to'] => {
@@ -893,7 +905,6 @@ const ErrorsView = () => {
? () => {
const countryData = activeError?.params?.cc || []
const regionData = activeError?.params?.rg || []
- // @ts-expect-error
const total = countryData.reduce((acc, curr) => acc + curr.count, 0)
return (
@@ -1132,7 +1143,7 @@ const ErrorsView = () => {
<button
type='button'
title={t('project.loadMore')}
- onClick={() => loadErrors()}
+ onClick={loadMoreErrors}
className={cx(
'relative mx-auto mt-2 flex items-center rounded-md border border-transparent p-2 text-sm font-medium text-gray-700 ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:bg-slate-900 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
{
@@ -1150,4 +1161,6 @@ const ErrorsView = () => {
)
}
+const ErrorsView = ErrorsViewWrapper
+
export default ErrorsView
diff --git a/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx b/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx
index a2d464d81..0f1d87a21 100644
--- a/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx
+++ b/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx
@@ -22,16 +22,14 @@ import {
import { useState, useEffect, useRef, useMemo, memo } from 'react'
import { useTranslation } from 'react-i18next'
-import {
- getExperiment,
- getExperimentResults,
- getGoal,
- type Experiment,
- type ExperimentResults as ExperimentResultsType,
- type ExperimentChartData,
- type ExperimentVariantResult,
- type Goal,
-} from '~/api'
+import type {
+ Experiment,
+ ExperimentResults as ExperimentResultsType,
+ ExperimentChartData,
+ ExperimentVariantResult,
+ Goal,
+} from '~/api/api.server'
+import { useExperimentProxy, useExperimentResultsProxy, useGoalProxy } from '~/hooks/useAnalyticsProxy'
import {
TimeFormat,
tbsFormatMapper,
@@ -619,6 +617,9 @@ const ExperimentResults = ({
}: ExperimentResultsProps) => {
const { t } = useTranslation()
const isMountedRef = useRef(true)
+ const experimentProxy = useExperimentProxy()
+ const resultsProxy = useExperimentResultsProxy()
+ const goalProxy = useGoalProxy()
const [experiment, setExperiment] = useState<Experiment | null>(null)
const [results, setResults] = useState<ExperimentResultsType | null>(null)
@@ -645,14 +646,14 @@ const ExperimentResults = ({
try {
const [experimentData, resultsData] = await Promise.all([
- getExperiment(experimentId),
- getExperimentResults(experimentId, period, timeBucket, from, to, timezone),
+ experimentProxy.fetchExperiment(experimentId),
+ resultsProxy.fetchResults(experimentId, { period, timeBucket, from, to, timezone }),
])
let goalData: Goal | null = null
- if (experimentData.goalId) {
+ if (experimentData?.goalId) {
try {
- goalData = await getGoal(experimentData.goalId)
+ goalData = await goalProxy.fetchGoal(experimentData.goalId)
} catch {
goalData = null
}
diff --git a/web/app/pages/Project/tabs/Experiments/ExperimentSettingsModal.tsx b/web/app/pages/Project/tabs/Experiments/ExperimentSettingsModal.tsx
index 8b0d0bc04..40bc909b1 100644
--- a/web/app/pages/Project/tabs/Experiments/ExperimentSettingsModal.tsx
+++ b/web/app/pages/Project/tabs/Experiments/ExperimentSettingsModal.tsx
@@ -4,23 +4,21 @@ import cx from 'clsx'
import _map from 'lodash/map'
import _sum from 'lodash/sum'
import { PlusIcon, Trash2Icon, ChevronDownIcon, TrendingUpIcon, TrendingDownIcon } from 'lucide-react'
-import { useState, useEffect, useMemo } from 'react'
+import { useState, useEffect, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import {
- createExperiment,
- updateExperiment,
- getExperiment,
- getProjectGoals,
- getProjectFeatureFlags,
- type ExperimentVariant,
- type Goal,
- type ProjectFeatureFlag,
- type ExposureTrigger,
- type MultipleVariantHandling,
- type FeatureFlagMode,
-} from '~/api'
+import type {
+ ExperimentVariant,
+ Goal,
+ ProjectFeatureFlag,
+ ExposureTrigger,
+ MultipleVariantHandling,
+ FeatureFlagMode,
+} from '~/api/api.server'
+import { useExperimentProxy, useProjectGoalsProxy, useProjectFeatureFlagsProxy } from '~/hooks/useAnalyticsProxy'
+import type { ProjectViewActionData } from '~/routes/projects.$id'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import Loader from '~/ui/Loader'
@@ -52,14 +50,20 @@ const ExperimentSettingsModal = ({
}: ExperimentSettingsModalProps) => {
const { t } = useTranslation()
const isEditing = !!experimentId
+ const experimentProxy = useExperimentProxy()
+ const goalsProxy = useProjectGoalsProxy()
+ const featureFlagsProxy = useProjectFeatureFlagsProxy()
+ const fetcher = useFetcher<ProjectViewActionData>()
+ const processedRef = useRef<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const [isSaving, setIsSaving] = useState(false)
const [goals, setGoals] = useState<Goal[]>([])
const [goalsLoading, setGoalsLoading] = useState(false)
const [featureFlags, setFeatureFlags] = useState<ProjectFeatureFlag[]>([])
const [featureFlagsLoading, setFeatureFlagsLoading] = useState(false)
+ const isSaving = fetcher.state === 'submitting'
+
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [featureFlagKey, setFeatureFlagKey] = useState('')
@@ -105,7 +109,10 @@ const ExperimentSettingsModal = ({
if (!experimentId) return
setIsLoading(true)
try {
- const experiment = await getExperiment(experimentId)
+ const experiment = await experimentProxy.fetchExperiment(experimentId)
+ if (!experiment) {
+ throw new Error('Failed to load experiment')
+ }
setName(experiment.name)
setDescription(experiment.description || '')
setFeatureFlagKey(experiment.featureFlagKey || '')
@@ -150,8 +157,10 @@ const ExperimentSettingsModal = ({
const loadGoals = async () => {
setGoalsLoading(true)
try {
- const result = await getProjectGoals(projectId, 100, 0)
- setGoals(result.results)
+ const result = await goalsProxy.fetchGoals(projectId, { take: 100, skip: 0 })
+ if (result) {
+ setGoals(result.results)
+ }
} catch (error) {
console.error('Failed to load goals:', error)
} finally {
@@ -160,7 +169,7 @@ const ExperimentSettingsModal = ({
}
loadGoals()
- }, [isOpen, projectId])
+ }, [isOpen, projectId, goalsProxy])
useEffect(() => {
if (!isOpen || featureFlagMode !== 'link') return
@@ -168,8 +177,10 @@ const ExperimentSettingsModal = ({
const loadFeatureFlags = async () => {
setFeatureFlagsLoading(true)
try {
- const result = await getProjectFeatureFlags(projectId, 100, 0)
- setFeatureFlags(result.results)
+ const result = await featureFlagsProxy.fetchFeatureFlags(projectId, { take: 100, skip: 0 })
+ if (result) {
+ setFeatureFlags(result.results)
+ }
} catch (error) {
console.error('Failed to load feature flags:', error)
} finally {
@@ -178,7 +189,7 @@ const ExperimentSettingsModal = ({
}
loadFeatureFlags()
- }, [isOpen, projectId, featureFlagMode])
+ }, [isOpen, projectId, featureFlagMode, featureFlagsProxy])
const validateForm = (): boolean => {
const newErrors: Record<string, string> = {}
@@ -226,43 +237,60 @@ const ExperimentSettingsModal = ({
return Object.keys(newErrors).length === 0
}
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault()
- if (!validateForm()) return
+ // Handle fetcher response
+ useEffect(() => {
+ if (!fetcher.data || fetcher.state !== 'idle') return
- setIsSaving(true)
- try {
- const effectiveFlagKey = featureFlagKey.trim() || suggestedFlagKey
-
- const data = {
- pid: projectId,
- name: name.trim(),
- description: description.trim() || undefined,
- exposureTrigger,
- customEventName: exposureTrigger === 'custom_event' ? customEventName.trim() : undefined,
- multipleVariantHandling,
- featureFlagMode,
- featureFlagKey: featureFlagMode === 'create' ? effectiveFlagKey || undefined : undefined,
- existingFeatureFlagId: featureFlagMode === 'link' ? existingFeatureFlagId : undefined,
- goalId: goalId || undefined,
- variants,
- }
+ const responseKey = `${fetcher.data.intent}-${fetcher.data.success}`
+ if (processedRef.current === responseKey) return
+ processedRef.current = responseKey
- if (experimentId) {
- await updateExperiment(experimentId, data)
- toast.success(t('experiments.updated'))
- } else {
- await createExperiment(data)
+ if (fetcher.data.success) {
+ const { intent } = fetcher.data
+ if (intent === 'create-experiment') {
toast.success(t('experiments.created'))
+ } else if (intent === 'update-experiment') {
+ toast.success(t('experiments.updated'))
}
-
onSuccess()
onClose()
- } catch (error: any) {
- toast.error(error?.response?.data?.message || error?.message || t('apiNotifications.somethingWentWrong'))
- } finally {
- setIsSaving(false)
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ }, [fetcher.data, fetcher.state, t, onSuccess, onClose])
+
+ // Reset processed ref when modal opens
+ useEffect(() => {
+ if (isOpen) {
+ processedRef.current = null
}
+ }, [isOpen])
+
+ const handleSubmit = (e: React.FormEvent) => {
+ e.preventDefault()
+ if (!validateForm()) return
+
+ processedRef.current = null
+ const effectiveFlagKey = featureFlagKey.trim() || suggestedFlagKey
+
+ const formData = new FormData()
+ formData.set('intent', isEditing ? 'update-experiment' : 'create-experiment')
+ formData.set('name', name.trim())
+ formData.set('description', description.trim())
+ formData.set('exposureTrigger', exposureTrigger)
+ formData.set('customEventName', exposureTrigger === 'custom_event' ? customEventName.trim() : '')
+ formData.set('multipleVariantHandling', multipleVariantHandling)
+ formData.set('featureFlagMode', featureFlagMode)
+ formData.set('featureFlagKey', featureFlagMode === 'create' ? effectiveFlagKey : '')
+ formData.set('existingFeatureFlagId', featureFlagMode === 'link' ? existingFeatureFlagId : '')
+ formData.set('goalId', goalId)
+ formData.set('variants', JSON.stringify(variants))
+
+ if (isEditing && experimentId) {
+ formData.set('experimentId', experimentId)
+ }
+
+ fetcher.submit(formData, { method: 'post' })
}
const distributePercentages = (variantsList: ExperimentVariant[]): ExperimentVariant[] => {
diff --git a/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx b/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
index af853376d..dbdb16adb 100644
--- a/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
+++ b/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
@@ -17,22 +17,13 @@ import {
} from 'lucide-react'
import { useState, useEffect, useMemo, useRef, useCallback, memo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSearchParams } from 'react-router'
+import { useSearchParams, useFetcher } from 'react-router'
import { toast } from 'sonner'
-import {
- deleteExperiment as deleteExperimentApi,
- getProjectExperiments,
- startExperiment as startExperimentApi,
- pauseExperiment as pauseExperimentApi,
- completeExperiment as completeExperimentApi,
- DEFAULT_EXPERIMENTS_TAKE,
- type Experiment,
- type ExperimentStatus,
-} from '~/api'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
-import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+import type { ProjectViewActionData } from '~/routes/projects.$id'
import Button from '~/ui/Button'
import Spin from '~/ui/icons/Spin'
import Loader from '~/ui/Loader'
@@ -55,6 +46,48 @@ const STATUS_COLORS: Record<ExperimentStatus, { bg: string; text: string }> = {
completed: { bg: 'bg-blue-100 dark:bg-blue-900/30', text: 'text-blue-800 dark:text-blue-400' },
}
+const DEFAULT_EXPERIMENTS_TAKE = 20
+
+type ExperimentStatus = 'draft' | 'running' | 'paused' | 'completed'
+
+type ExposureTrigger = 'feature_flag' | 'custom_event'
+
+type MultipleVariantHandling = 'exclude' | 'first_exposure'
+
+type FeatureFlagMode = 'create' | 'link'
+
+interface ExperimentVariant {
+ id?: string
+ name: string
+ key: string
+ description?: string | null
+ rolloutPercentage: number
+ isControl: boolean
+}
+
+interface Experiment {
+ id: string
+ name: string
+ description: string | null
+ hypothesis: string | null
+ status: ExperimentStatus
+ // Exposure criteria
+ exposureTrigger: ExposureTrigger
+ customEventName: string | null
+ multipleVariantHandling: MultipleVariantHandling
+ filterInternalUsers: boolean
+ // Feature flag configuration
+ featureFlagMode: FeatureFlagMode
+ featureFlagKey: string | null
+ startedAt: string | null
+ endedAt: string | null
+ pid: string
+ goalId: string | null
+ featureFlagId: string | null
+ variants: ExperimentVariant[]
+ created: string
+}
+
interface ExperimentRowProps {
experiment: Experiment
onDelete: (id: string) => void
@@ -286,19 +319,22 @@ interface ExperimentsViewProps {
const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsViewProps) => {
const { id } = useCurrentProject()
- const { experimentsRefreshTrigger, timeBucket } = useViewProjectContext()
+ const { experimentsRefreshTrigger } = useRefreshTriggers()
+ const { timeBucket } = useViewProjectContext()
const [searchParams] = useSearchParams()
const isEmbedded = searchParams.get('embedded') === 'true'
const { t } = useTranslation()
+ const listFetcher = useFetcher<ProjectViewActionData>()
+ const actionFetcher = useFetcher<ProjectViewActionData>()
const [isLoading, setIsLoading] = useState<boolean | null>(null)
- const isLoadingRef = useRef(false)
const isMountedRef = useRef(true)
const [total, setTotal] = useState(0)
const [experiments, setExperiments] = useState<Experiment[]>([])
const [page, setPage] = useState(1)
const [error, setError] = useState<string | null>(null)
const [filterQuery, setFilterQuery] = useState('')
+ const processedActionRef = useRef<string | null>(null)
// Modal state
const [isModalOpen, setIsModalOpen] = useState(false)
@@ -319,50 +355,98 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
const pageAmount = Math.ceil(total / DEFAULT_EXPERIMENTS_TAKE)
- const loadExperiments = async (take: number, skip: number, showLoading = true, search?: string) => {
- if (isLoadingRef.current) {
- return
- }
- isLoadingRef.current = true
+ const loadExperiments = useCallback(
+ (take: number, skip: number, showLoading = true, search?: string) => {
+ if (showLoading) {
+ setIsLoading(true)
+ }
- // `showLoading` means "show either initial Loader or refresh LoadingBar".
- if (showLoading) {
- setIsLoading(true)
- }
+ listFetcher.submit(
+ {
+ intent: 'get-project-experiments',
+ take: String(take),
+ skip: String(skip),
+ search: search || '',
+ },
+ { method: 'POST' },
+ )
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [listFetcher.submit],
+ )
- try {
- const result = await getProjectExperiments(id, take, skip, search)
+ // Handle list fetcher response
+ useEffect(() => {
+ if (listFetcher.data?.intent === 'get-project-experiments') {
if (isMountedRef.current) {
- setExperiments(result.results)
- setTotal(result.total)
- setError(null) // Clear any previous error on success
+ setIsLoading(false)
+ if (listFetcher.data.success && listFetcher.data.data) {
+ const result = listFetcher.data.data as { results: Experiment[]; total: number }
+ setExperiments(result.results)
+ setTotal(result.total)
+ setError(null)
+ } else if (listFetcher.data.error) {
+ setError(listFetcher.data.error)
+ }
}
- } catch (reason: any) {
- if (isMountedRef.current) {
- setError(reason?.message || reason?.toString() || 'Unknown error')
+ }
+ }, [listFetcher.data])
+
+ // Handle action fetcher responses (delete, start, pause, complete)
+ useEffect(() => {
+ if (!actionFetcher.data || actionFetcher.state !== 'idle') return
+
+ const { intent, success, error, data } = actionFetcher.data
+ const responseData = actionFetcher.data as Record<string, unknown>
+ const uniqueSuffix = responseData.requestId ?? responseData.timestamp ?? actionFetcher.state
+ const actionKey = `${intent}-${success ?? false}-${error ?? ''}-${uniqueSuffix}-${JSON.stringify(data)}`
+ if (processedActionRef.current === actionKey) return
+ processedActionRef.current = actionKey
+
+ if (actionFetcher.data.intent === 'delete-experiment') {
+ if (actionFetcher.data.success) {
+ toast.success(t('experiments.deleted'))
+ loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ } else if (actionFetcher.data.error) {
+ toast.error(actionFetcher.data.error)
}
- } finally {
- isLoadingRef.current = false
- if (isMountedRef.current && showLoading) {
- setIsLoading(false)
+ } else if (actionFetcher.data.intent === 'start-experiment') {
+ if (actionFetcher.data.success) {
+ toast.success(t('experiments.started'))
+ loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ } else if (actionFetcher.data.error) {
+ toast.error(actionFetcher.data.error)
+ }
+ } else if (actionFetcher.data.intent === 'pause-experiment') {
+ if (actionFetcher.data.success) {
+ toast.success(t('experiments.paused'))
+ loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ } else if (actionFetcher.data.error) {
+ toast.error(actionFetcher.data.error)
+ }
+ } else if (actionFetcher.data.intent === 'complete-experiment') {
+ if (actionFetcher.data.success) {
+ toast.success(t('experiments.completed'))
+ loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ } else if (actionFetcher.data.error) {
+ toast.error(actionFetcher.data.error)
}
}
- }
+ }, [actionFetcher.data, actionFetcher.state, t, loadExperiments, page, filterQuery])
const debouncedLoadExperiments = useMemo(
() =>
_debounce((search: string) => {
loadExperiments(DEFAULT_EXPERIMENTS_TAKE, 0, true, search || undefined)
}, 300),
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [id],
+ [loadExperiments],
)
const handleSearchChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
setFilterQuery(value)
- setPage(1) // Reset to first page when searching
+ setPage(1)
debouncedLoadExperiments(value)
},
[debouncedLoadExperiments],
@@ -379,8 +463,6 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page])
- // Refresh experiments data when refresh button is clicked.
- // If user is viewing results, refresh results instead and defer list refresh until they return.
useEffect(() => {
if (experimentsRefreshTrigger > 0) {
if (viewingResultsId) {
@@ -388,14 +470,11 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
setShouldRefreshListOnReturn(true)
return
}
-
- // Refresh list (show LoadingBar if we already have data)
loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [experimentsRefreshTrigger, viewingResultsId, page])
- // If refresh happened while in results view, refresh list once upon returning.
useEffect(() => {
if (!viewingResultsId && shouldRefreshListOnReturn) {
setShouldRefreshListOnReturn(false)
@@ -421,48 +500,39 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
const handleModalSuccess = useCallback(() => {
loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [page, filterQuery])
+ }, [page, filterQuery, loadExperiments])
- const handleDeleteExperiment = async (experimentId: string) => {
- try {
- await deleteExperimentApi(experimentId)
- toast.success(t('experiments.deleted'))
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
- } catch (reason: any) {
- toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))
- }
- }
+ const handleDeleteExperiment = useCallback(
+ (experimentId: string) => {
+ processedActionRef.current = null
+ actionFetcher.submit({ intent: 'delete-experiment', experimentId }, { method: 'POST' })
+ },
+ [actionFetcher],
+ )
- const handleStartExperiment = async (experimentId: string) => {
- try {
- await startExperimentApi(experimentId)
- toast.success(t('experiments.started'))
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
- } catch (reason: any) {
- toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))
- }
- }
+ const handleStartExperiment = useCallback(
+ (experimentId: string) => {
+ processedActionRef.current = null
+ actionFetcher.submit({ intent: 'start-experiment', experimentId }, { method: 'POST' })
+ },
+ [actionFetcher],
+ )
- const handlePauseExperiment = async (experimentId: string) => {
- try {
- await pauseExperimentApi(experimentId)
- toast.success(t('experiments.paused'))
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
- } catch (reason: any) {
- toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))
- }
- }
+ const handlePauseExperiment = useCallback(
+ (experimentId: string) => {
+ processedActionRef.current = null
+ actionFetcher.submit({ intent: 'pause-experiment', experimentId }, { method: 'POST' })
+ },
+ [actionFetcher],
+ )
- const handleCompleteExperiment = async (experimentId: string) => {
- try {
- await completeExperimentApi(experimentId)
- toast.success(t('experiments.completed'))
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
- } catch (reason: any) {
- toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))
- }
- }
+ const handleCompleteExperiment = useCallback(
+ (experimentId: string) => {
+ processedActionRef.current = null
+ actionFetcher.submit({ intent: 'complete-experiment', experimentId }, { method: 'POST' })
+ },
+ [actionFetcher],
+ )
const handleViewResults = (experimentId: string) => {
setViewingResultsId(experimentId)
diff --git a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx
index 49532a4b2..a8e60ebf1 100644
--- a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx
+++ b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx
@@ -13,20 +13,16 @@ import { XMarkIcon, ClipboardIcon, CheckIcon as HeroCheckIcon } from '@heroicons
import cx from 'clsx'
import _map from 'lodash/map'
import { Trash2Icon, PlusIcon, CodeIcon, ChevronDownIcon, ChevronsUpDownIcon, CheckIcon } from 'lucide-react'
-import { useState, useEffect, useCallback, Fragment } from 'react'
+import { useState, useEffect, useCallback, Fragment, useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import {
- getFeatureFlag,
- createFeatureFlag,
- updateFeatureFlag,
- getFilters,
- type CreateFeatureFlag,
- type TargetingRule,
-} from '~/api'
+import type { ProjectFeatureFlag, TargetingRule } from '~/api/api.server'
+import { useFiltersProxy } from '~/hooks/useAnalyticsProxy'
import { API_URL, isSelfhosted } from '~/lib/constants'
import { useTheme } from '~/providers/ThemeProvider'
+import type { ProjectViewActionData } from '~/routes/projects.$id'
import Button from '~/ui/Button'
import Checkbox from '~/ui/Checkbox'
import FilterValueInput, { filterCategoryIcons } from '~/ui/FilterValueInput'
@@ -64,9 +60,11 @@ const FeatureFlagSettingsModal = ({ isOpen, onClose, onSuccess, projectId, flagI
} = useTranslation()
const { theme } = useTheme()
const isNew = !flagId
+ const fetcher = useFetcher<ProjectViewActionData>()
+ const lastHandledData = useRef<ProjectViewActionData | null>(null)
+ const { fetchFilters } = useFiltersProxy()
const [isLoading, setIsLoading] = useState(false)
- const [isSaving, setIsSaving] = useState(false)
const [showImplementation, setShowImplementation] = useState(false)
const [copiedCode, setCopiedCode] = useState<string | null>(null)
@@ -82,6 +80,8 @@ const FeatureFlagSettingsModal = ({ isOpen, onClose, onSuccess, projectId, flagI
const [targetingRules, setTargetingRules] = useState<TargetingRule[]>([])
const [enabled, setEnabled] = useState(true)
+ const isSaving = fetcher.state === 'submitting' || fetcher.state === 'loading'
+
const resetForm = () => {
setKey('')
setDescription('')
@@ -94,15 +94,16 @@ const FeatureFlagSettingsModal = ({ isOpen, onClose, onSuccess, projectId, flagI
const fetchFilterValues = useCallback(
async (column: string) => {
- if (filterValuesCache[column] || loadingColumns.has(column)) return
+ const cacheKey = `${projectId}-${column}`
+ if (filterValuesCache[cacheKey] || loadingColumns.has(column)) return
setLoadingColumns((prev) => new Set(prev).add(column))
try {
- const result = await getFilters(projectId, column)
- setFilterValuesCache((prev) => ({ ...prev, [column]: result }))
+ const result = await fetchFilters(projectId, column)
+ setFilterValuesCache((prev) => ({ ...prev, [cacheKey]: result || [] }))
} catch (error) {
console.error('Failed to fetch filter values:', error)
- setFilterValuesCache((prev) => ({ ...prev, [column]: [] }))
+ setFilterValuesCache((prev) => ({ ...prev, [cacheKey]: [] }))
} finally {
setLoadingColumns((prev) => {
const newSet = new Set(prev)
@@ -111,85 +112,113 @@ const FeatureFlagSettingsModal = ({ isOpen, onClose, onSuccess, projectId, flagI
})
}
},
- [projectId, filterValuesCache, loadingColumns],
+ [projectId, filterValuesCache, loadingColumns, fetchFilters],
)
// Pre-fetch filter values when modal opens
useEffect(() => {
if (isOpen) {
- // Pre-fetch values for all targeting columns
TARGETING_COLUMNS.forEach(({ value: column }) => {
- if (!filterValuesCache[column] && !loadingColumns.has(column)) {
+ const cacheKey = `${projectId}-${column}`
+ if (!filterValuesCache[cacheKey] && !loadingColumns.has(column)) {
fetchFilterValues(column)
}
})
}
- }, [isOpen, fetchFilterValues, filterValuesCache, loadingColumns])
+ }, [isOpen, fetchFilterValues, filterValuesCache, loadingColumns, projectId])
- const loadFlag = async () => {
- if (!flagId) return
- setIsLoading(true)
- try {
- const flag = await getFeatureFlag(flagId)
- setKey(flag.key)
- setDescription(flag.description || '')
- setFlagType(flag.flagType)
- setRolloutPercentage(flag.rolloutPercentage)
- setTargetingRules(flag.targetingRules || [])
- setEnabled(flag.enabled)
- } catch (err: any) {
- toast.error(err?.message || 'Failed to load feature flag')
- onClose()
- } finally {
+ // Load flag via fetcher
+ useEffect(() => {
+ if (isOpen && flagId) {
+ setIsLoading(true)
+ fetcher.submit({ intent: 'get-feature-flag', flagId }, { method: 'POST' })
+ } else if (isOpen && !flagId) {
+ resetForm()
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isOpen, flagId])
+
+ useEffect(() => {
+ if (fetcher.state !== 'idle') return
+
+ if (isLoading) {
setIsLoading(false)
}
- }
+ if (!fetcher.data) return
+ if (lastHandledData.current === fetcher.data) return
+ lastHandledData.current = fetcher.data
+
+ if (fetcher.data.intent === 'get-feature-flag') {
+ if (fetcher.data.success && fetcher.data.data) {
+ const flag = fetcher.data.data as ProjectFeatureFlag
+ setKey(flag.key)
+ setDescription(flag.description || '')
+ setFlagType(flag.flagType)
+ setRolloutPercentage(flag.rolloutPercentage)
+ setTargetingRules(flag.targetingRules || [])
+ setEnabled(flag.enabled)
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ onClose()
+ }
+ } else if (fetcher.data.intent === 'create-feature-flag') {
+ if (fetcher.data.success) {
+ toast.success(t('featureFlags.created'))
+ onSuccess()
+ onClose()
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ } else if (fetcher.data.intent === 'update-feature-flag') {
+ if (fetcher.data.success) {
+ toast.success(t('featureFlags.updated'))
+ onSuccess()
+ onClose()
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ }
+ }, [fetcher.data, fetcher.state, t, onSuccess, onClose, isLoading])
+
+ // Reset ref when modal opens to allow fresh data handling
useEffect(() => {
if (isOpen) {
- if (flagId) {
- loadFlag()
- } else {
- resetForm()
- }
+ lastHandledData.current = null
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isOpen, flagId])
+ }, [isOpen])
- const handleSubmit = async (e: React.FormEvent) => {
+ const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
- setIsSaving(true)
+ lastHandledData.current = null
- try {
- if (isNew) {
- const data: CreateFeatureFlag = {
- pid: projectId,
+ if (isNew) {
+ fetcher.submit(
+ {
+ intent: 'create-feature-flag',
key,
- description: description || undefined,
+ description: description || '',
flagType,
- rolloutPercentage: flagType === 'rollout' ? rolloutPercentage : 100,
- targetingRules: targetingRules.length > 0 ? targetingRules : undefined,
- enabled,
- }
- await createFeatureFlag(data)
- toast.success(t('featureFlags.created'))
- } else if (flagId) {
- await updateFeatureFlag(flagId, {
+ rolloutPercentage: String(flagType === 'rollout' ? rolloutPercentage : 100),
+ targetingRules: JSON.stringify(targetingRules.length > 0 ? targetingRules : []),
+ enabled: String(enabled),
+ },
+ { method: 'POST' },
+ )
+ } else if (flagId) {
+ fetcher.submit(
+ {
+ intent: 'update-feature-flag',
+ flagId,
key,
- description: description || null,
+ description: description || '',
flagType,
- rolloutPercentage: flagType === 'rollout' ? rolloutPercentage : 100,
- targetingRules: targetingRules.length > 0 ? targetingRules : null,
- enabled,
- })
- toast.success(t('featureFlags.updated'))
- }
- onSuccess()
- onClose()
- } catch (err: any) {
- toast.error(err?.message || t('apiNotifications.somethingWentWrong'))
- } finally {
- setIsSaving(false)
+ rolloutPercentage: String(flagType === 'rollout' ? rolloutPercentage : 100),
+ targetingRules: JSON.stringify(targetingRules.length > 0 ? targetingRules : []),
+ enabled: String(enabled),
+ },
+ { method: 'POST' },
+ )
}
}
@@ -203,11 +232,12 @@ const FeatureFlagSettingsModal = ({ isOpen, onClose, onSuccess, projectId, flagI
// Reset filter value when column changes
updated[index] = { ...updated[index], column: value as string, filter: '' }
// Fetch filter values for the new column if not already cached
- if (value && !filterValuesCache[value as string] && !loadingColumns.has(value as string)) {
+ const cacheKey = `${projectId}-${value as string}`
+ if (value && !filterValuesCache[cacheKey] && !loadingColumns.has(value as string)) {
fetchFilterValues(value as string)
}
} else {
- // @ts-expect-error - TypeScript doesn't like dynamic field assignment
+ // @ts-ignore - TypeScript doesn't like dynamic field assignment
updated[index][field] = value
}
setTargetingRules(updated)
@@ -525,7 +555,7 @@ const { flags } = await response.json()
{/* Value Input with Autocomplete */}
<FilterValueInput
- items={filterValuesCache[rule.column] || []}
+ items={filterValuesCache[`${projectId}-${rule.column}`] || []}
value={rule.filter}
onChange={(value) => updateTargetingRule(index, 'filter', value)}
placeholder={t('featureFlags.valuePlaceholder')}
diff --git a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx
index ec9d507fb..a24bbb208 100644
--- a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx
+++ b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx
@@ -20,25 +20,17 @@ import {
CheckIcon,
XIcon,
} from 'lucide-react'
-import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
+import { useState, useEffect, useMemo, useRef, useCallback, Suspense, use } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link, useLocation, useSearchParams } from 'react-router'
+import { Link, useLocation, useFetcher, useLoaderData, useRevalidator } from 'react-router'
import { toast } from 'sonner'
-import {
- deleteFeatureFlag as deleteFeatureFlagApi,
- getProjectFeatureFlags,
- getFeatureFlagStats,
- getFeatureFlagProfiles,
- DEFAULT_FEATURE_FLAGS_TAKE,
- DEFAULT_FEATURE_FLAG_PROFILES_TAKE,
- type ProjectFeatureFlag,
- type FeatureFlagStats,
- type FeatureFlagProfile,
-} from '~/api'
+import type { FeatureFlagsResponse, ProjectFeatureFlag, FeatureFlagStats, FeatureFlagProfile } from '~/api/api.server'
+import { useFeatureFlagStatsProxy, useFeatureFlagProfilesProxy } from '~/hooks/useAnalyticsProxy'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
-import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+import type { ProjectLoaderData, ProjectViewActionData } from '~/routes/projects.$id'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import Spin from '~/ui/icons/Spin'
@@ -57,6 +49,9 @@ import FeatureFlagSettingsModal from './FeatureFlagSettingsModal'
dayjs.extend(relativeTime)
+const DEFAULT_FEATURE_FLAGS_TAKE = 20
+const DEFAULT_FEATURE_FLAG_PROFILES_TAKE = 15
+
interface FeatureFlagProfileRowProps {
profile: FeatureFlagProfile
timeFormat: '12-hour' | '24-hour'
@@ -426,23 +421,52 @@ interface FeatureFlagsViewProps {
timezone?: string
}
-const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlagsViewProps) => {
+interface DeferredFeatureFlagsData {
+ featureFlagsData: FeatureFlagsResponse | null
+}
+
+function FeatureFlagsDataResolver({ children }: { children: (data: DeferredFeatureFlagsData) => React.ReactNode }) {
+ const { featureFlagsData: featureFlagsDataPromise } = useLoaderData<ProjectLoaderData>()
+ const featureFlagsData = featureFlagsDataPromise ? use(featureFlagsDataPromise) : null
+ return <>{children({ featureFlagsData })}</>
+}
+
+function FeatureFlagsViewWrapper(props: FeatureFlagsViewProps) {
+ return (
+ <Suspense fallback={<Loader />}>
+ <FeatureFlagsDataResolver>
+ {(deferredData) => <FeatureFlagsViewInner {...props} deferredData={deferredData} />}
+ </FeatureFlagsDataResolver>
+ </Suspense>
+ )
+}
+
+interface FeatureFlagsViewInnerProps extends FeatureFlagsViewProps {
+ deferredData: DeferredFeatureFlagsData
+}
+
+const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredData }: FeatureFlagsViewInnerProps) => {
const { id } = useCurrentProject()
- const { featureFlagsRefreshTrigger, timeFormat } = useViewProjectContext()
- const [searchParams] = useSearchParams()
- const isEmbedded = searchParams.get('embedded') === 'true'
+ const revalidator = useRevalidator()
+ const { featureFlagsRefreshTrigger } = useRefreshTriggers()
+ const { timeFormat } = useViewProjectContext()
const { t } = useTranslation()
- const [isLoading, setIsLoading] = useState<boolean | null>(null)
- const isLoadingRef = useRef(false)
- const isMountedRef = useRef(true)
- const [total, setTotal] = useState(0)
- const [flags, setFlags] = useState<ProjectFeatureFlag[]>([])
+ const listFetcher = useFetcher<ProjectViewActionData>()
+ const actionFetcher = useFetcher<ProjectViewActionData>()
+
+ // Track if we're in search/pagination mode (not using loader data)
+ const [isSearchMode, setIsSearchMode] = useState(false)
+ const [total, setTotal] = useState(() => deferredData.featureFlagsData?.total || 0)
+ const [flags, setFlags] = useState<ProjectFeatureFlag[]>(() => deferredData.featureFlagsData?.results || [])
const [flagStats, setFlagStats] = useState<Record<string, FeatureFlagStats | null>>({})
const [statsLoading, setStatsLoading] = useState<Record<string, boolean>>({})
const [page, setPage] = useState(1)
const [error, setError] = useState<string | null>(null)
const [filterQuery, setFilterQuery] = useState('')
+ const processedActionRef = useRef<string | null>(null)
+
+ const isMountedRef = useRef(true)
// Expanded flag state
const [expandedFlagId, setExpandedFlagId] = useState<string | null>(null)
@@ -455,6 +479,8 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags
const [isModalOpen, setIsModalOpen] = useState(false)
const [editingFlagId, setEditingFlagId] = useState<string | null>(null)
+ const isLoading = revalidator.state === 'loading' || listFetcher.state !== 'idle'
+
// Cleanup on unmount
useEffect(() => {
isMountedRef.current = true
@@ -463,32 +489,82 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags
}
}, [])
+ // Sync state when loader provides new data
+ useEffect(() => {
+ if (deferredData.featureFlagsData && revalidator.state === 'idle' && !isSearchMode) {
+ setFlags(deferredData.featureFlagsData.results || [])
+ setTotal(deferredData.featureFlagsData.total || 0)
+ }
+ }, [revalidator.state, deferredData.featureFlagsData, isSearchMode])
+
const pageAmount = Math.ceil(total / DEFAULT_FEATURE_FLAGS_TAKE)
- const loadFlags = async (take: number, skip: number, search?: string) => {
- if (isLoadingRef.current) {
- return
- }
- isLoadingRef.current = true
- setIsLoading(true)
+ const loadFlags = useCallback(
+ (take: number, skip: number, search?: string) => {
+ if (listFetcher.state !== 'idle') {
+ return
+ }
+ setIsSearchMode(true)
+
+ listFetcher.submit(
+ {
+ intent: 'get-project-feature-flags',
+ take: String(take),
+ skip: String(skip),
+ search: search || '',
+ },
+ { method: 'POST' },
+ )
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [listFetcher.submit],
+ )
- try {
- const result = await getProjectFeatureFlags(id, take, skip, search)
+ // Handle list fetcher response
+ useEffect(() => {
+ if (listFetcher.data?.intent === 'get-project-feature-flags' && listFetcher.state === 'idle') {
if (isMountedRef.current) {
- setFlags(result.results)
- setTotal(result.total)
+ if (listFetcher.data.success && listFetcher.data.data) {
+ const result = listFetcher.data.data as { results: ProjectFeatureFlag[]; total: number }
+ setFlags(result.results)
+ setTotal(result.total)
+ } else if (listFetcher.data.error) {
+ setError(listFetcher.data.error)
+ }
}
- } catch (reason: any) {
- if (isMountedRef.current) {
- setError(reason?.message || reason?.toString() || 'Unknown error')
+ }
+ }, [listFetcher.data, listFetcher.state])
+
+ // Handle action fetcher responses (delete, update)
+ useEffect(() => {
+ if (!actionFetcher.data || actionFetcher.state !== 'idle') return
+
+ const actionKey = `${actionFetcher.data.intent}-${JSON.stringify(actionFetcher.data.data)}`
+ if (processedActionRef.current === actionKey) return
+ processedActionRef.current = actionKey
+
+ if (actionFetcher.data.intent === 'delete-feature-flag') {
+ if (actionFetcher.data.success) {
+ toast.success(t('featureFlags.deleted'))
+ if (page === 1 && !filterQuery) {
+ setIsSearchMode(false)
+ revalidator.revalidate()
+ } else {
+ loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)
+ }
+ } else if (actionFetcher.data.error) {
+ toast.error(actionFetcher.data.error)
}
- } finally {
- isLoadingRef.current = false
- if (isMountedRef.current) {
- setIsLoading(false)
+ } else if (actionFetcher.data.intent === 'update-feature-flag') {
+ if (actionFetcher.data.success && actionFetcher.data.data) {
+ const updated = actionFetcher.data.data as ProjectFeatureFlag
+ toast.success(updated.enabled ? t('featureFlags.flagEnabled') : t('featureFlags.flagDisabled'))
+ setFlags((prev) => prev.map((f) => (f.id === updated.id ? updated : f)))
+ } else if (actionFetcher.data.error) {
+ toast.error(actionFetcher.data.error)
}
}
- }
+ }, [actionFetcher.data, actionFetcher.state, t, loadFlags, page, filterQuery, revalidator])
// Debounced search to avoid excessive API calls
const debouncedLoadFlags = useMemo(
@@ -496,8 +572,7 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags
_debounce((search: string) => {
loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, 0, search || undefined)
}, 300),
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [id],
+ [loadFlags],
)
// Handle search input change
@@ -518,158 +593,121 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags
}
}, [debouncedLoadFlags])
- const loadFlagStats = async (flagId: string) => {
- setStatsLoading((prev) => ({ ...prev, [flagId]: true }))
- try {
- const stats = await getFeatureFlagStats(flagId, period, from, to, timezone)
- if (isMountedRef.current) {
- setFlagStats((prev) => ({ ...prev, [flagId]: stats }))
- }
- } catch (err) {
- console.error('Failed to load flag stats:', err)
- if (isMountedRef.current) {
- setFlagStats((prev) => ({ ...prev, [flagId]: null }))
- }
- } finally {
- if (isMountedRef.current) {
- setStatsLoading((prev) => ({ ...prev, [flagId]: false }))
+ // Proxy hooks for stats and profiles
+ const statsProxy = useFeatureFlagStatsProxy()
+ const profilesProxy = useFeatureFlagProfilesProxy()
+
+ const loadFlagStats = useCallback(
+ async (flagId: string) => {
+ setStatsLoading((prev) => ({ ...prev, [flagId]: true }))
+ try {
+ const stats = await statsProxy.fetchStats(flagId, { period, from, to, timezone })
+ if (isMountedRef.current) {
+ setFlagStats((prev) => ({ ...prev, [flagId]: stats }))
+ }
+ } catch (err) {
+ console.error('Failed to load flag stats:', err)
+ if (isMountedRef.current) {
+ setFlagStats((prev) => ({ ...prev, [flagId]: null }))
+ }
+ } finally {
+ if (isMountedRef.current) {
+ setStatsLoading((prev) => ({ ...prev, [flagId]: false }))
+ }
}
- }
- }
+ },
+ [period, from, to, timezone, statsProxy],
+ )
- const loadFlagProfiles = async (flagId: string, append = false, resultFilter?: boolean) => {
- const currentProfiles = append ? flagProfiles[flagId] || [] : []
- const skip = append ? currentProfiles.length : 0
- const filter = resultFilter ?? flagResultFilters[flagId] ?? true
- const apiFilter = filter ? 'true' : 'false'
-
- setProfilesLoading((prev) => ({ ...prev, [flagId]: true }))
- try {
- const result = await getFeatureFlagProfiles(
- flagId,
- period,
- from,
- to,
- timezone,
- DEFAULT_FEATURE_FLAG_PROFILES_TAKE,
- skip,
- apiFilter,
- )
- if (isMountedRef.current) {
- setFlagProfiles((prev) => ({
- ...prev,
- [flagId]: append ? [...currentProfiles, ...result.profiles] : result.profiles,
- }))
- setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: result.total }))
- }
- } catch (err) {
- console.error('Failed to load flag profiles:', err)
- if (isMountedRef.current) {
- setFlagProfiles((prev) => ({ ...prev, [flagId]: append ? currentProfiles : [] }))
- setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: 0 }))
- }
- } finally {
- if (isMountedRef.current) {
- setProfilesLoading((prev) => ({ ...prev, [flagId]: false }))
+ const loadFlagProfiles = useCallback(
+ async (flagId: string, append = false, resultFilter?: boolean) => {
+ const currentProfiles = append ? flagProfiles[flagId] || [] : []
+ const skip = append ? currentProfiles.length : 0
+ const filter = resultFilter ?? flagResultFilters[flagId] ?? true
+ const apiFilter = filter ? 'true' : 'false'
+
+ setProfilesLoading((prev) => ({ ...prev, [flagId]: true }))
+ try {
+ const result = await profilesProxy.fetchProfiles(flagId, {
+ period,
+ from,
+ to,
+ timezone,
+ take: DEFAULT_FEATURE_FLAG_PROFILES_TAKE,
+ skip,
+ resultFilter: apiFilter,
+ })
+ if (isMountedRef.current && result) {
+ setFlagProfiles((prev) => ({
+ ...prev,
+ [flagId]: append ? [...currentProfiles, ...result.profiles] : result.profiles,
+ }))
+ setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: result.total }))
+ }
+ } catch (err) {
+ console.error('Failed to load flag profiles:', err)
+ if (isMountedRef.current) {
+ setFlagProfiles((prev) => ({ ...prev, [flagId]: append ? currentProfiles : [] }))
+ setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: 0 }))
+ }
+ } finally {
+ if (isMountedRef.current) {
+ setProfilesLoading((prev) => ({ ...prev, [flagId]: false }))
+ }
}
- }
- }
+ },
+ [period, from, to, timezone, flagProfiles, flagResultFilters, profilesProxy],
+ )
- const handleToggleExpand = async (flagId: string) => {
- if (expandedFlagId === flagId) {
- // Collapse if already expanded
- setExpandedFlagId(null)
- } else {
- // Expand and load profiles if not already loaded
- setExpandedFlagId(flagId)
- if (!flagProfiles[flagId] && !profilesLoading[flagId]) {
- // First try loading with true filter (served)
- setProfilesLoading((prev) => ({ ...prev, [flagId]: true }))
- try {
- const trueResult = await getFeatureFlagProfiles(
- flagId,
- period,
- from,
- to,
- timezone,
- DEFAULT_FEATURE_FLAG_PROFILES_TAKE,
- 0,
- 'true',
- )
-
- if (trueResult.total > 0) {
- // Has true results, use them
- if (isMountedRef.current) {
- setFlagProfiles((prev) => ({ ...prev, [flagId]: trueResult.profiles }))
- setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: trueResult.total }))
- setFlagResultFilters((prev) => ({ ...prev, [flagId]: true }))
- }
- } else {
- // No true results, try false
- const falseResult = await getFeatureFlagProfiles(
- flagId,
- period,
- from,
- to,
- timezone,
- DEFAULT_FEATURE_FLAG_PROFILES_TAKE,
- 0,
- 'false',
- )
-
- if (isMountedRef.current) {
- if (falseResult.total > 0) {
- // Has false results, use them and set filter to false
- setFlagProfiles((prev) => ({ ...prev, [flagId]: falseResult.profiles }))
- setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: falseResult.total }))
- setFlagResultFilters((prev) => ({ ...prev, [flagId]: false }))
- } else {
- // No results at all, default to true filter with empty
- setFlagProfiles((prev) => ({ ...prev, [flagId]: [] }))
- setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: 0 }))
- setFlagResultFilters((prev) => ({ ...prev, [flagId]: true }))
- }
- }
- }
- } catch (err) {
- console.error('Failed to load flag profiles:', err)
- if (isMountedRef.current) {
- setFlagProfiles((prev) => ({ ...prev, [flagId]: [] }))
- setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: 0 }))
- setFlagResultFilters((prev) => ({ ...prev, [flagId]: true }))
- }
- } finally {
- if (isMountedRef.current) {
- setProfilesLoading((prev) => ({ ...prev, [flagId]: false }))
- }
+ const handleToggleExpand = useCallback(
+ (flagId: string) => {
+ if (expandedFlagId === flagId) {
+ setExpandedFlagId(null)
+ } else {
+ setExpandedFlagId(flagId)
+ if (!flagProfiles[flagId] && !profilesLoading[flagId]) {
+ setFlagResultFilters((prev) => ({ ...prev, [flagId]: true }))
+ loadFlagProfiles(flagId, false, true)
}
}
- }
- }
+ },
+ [expandedFlagId, flagProfiles, profilesLoading, loadFlagProfiles],
+ )
- const handleLoadMoreProfiles = (flagId: string) => {
- loadFlagProfiles(flagId, true)
- }
+ const handleLoadMoreProfiles = useCallback(
+ (flagId: string) => {
+ loadFlagProfiles(flagId, true)
+ },
+ [loadFlagProfiles],
+ )
- const handleResultFilterChange = (flagId: string, filter: boolean) => {
- setFlagResultFilters((prev) => ({ ...prev, [flagId]: filter }))
- // Reset profiles and reload with new filter
- setFlagProfiles((prev) => ({ ...prev, [flagId]: [] }))
- loadFlagProfiles(flagId, false, filter)
- }
+ const handleResultFilterChange = useCallback(
+ (flagId: string, filter: boolean) => {
+ setFlagResultFilters((prev) => ({ ...prev, [flagId]: filter }))
+ setFlagProfiles((prev) => ({ ...prev, [flagId]: [] }))
+ loadFlagProfiles(flagId, false, filter)
+ },
+ [loadFlagProfiles],
+ )
+ // Handle page changes - use fetcher for pagination
useEffect(() => {
- loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)
+ if (page > 1 || isSearchMode) {
+ loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)
+ }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page])
// Refresh feature flags data when refresh button is clicked
useEffect(() => {
if (featureFlagsRefreshTrigger > 0) {
- loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)
- // Clear cached stats data to force reload
+ if (page === 1 && !filterQuery) {
+ setIsSearchMode(false)
+ revalidator.revalidate()
+ } else {
+ loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)
+ }
setFlagStats({})
- // Refresh profiles for expanded flag
if (expandedFlagId) {
setFlagProfiles((prev) => ({ [expandedFlagId]: prev[expandedFlagId] }))
loadFlagProfiles(expandedFlagId)
@@ -682,14 +720,12 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags
}, [featureFlagsRefreshTrigger])
useEffect(() => {
- // Load stats for all flags when flags change or date range changes
flags.forEach((flag) => {
loadFlagStats(flag.id)
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [flags, period, from, to, timezone])
- // Reload profiles when period changes for expanded flag
useEffect(() => {
if (expandedFlagId && flagProfiles[expandedFlagId]) {
loadFlagProfiles(expandedFlagId)
@@ -713,32 +749,31 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags
}
const handleModalSuccess = () => {
- loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)
- }
-
- const handleDeleteFlag = async (flagId: string) => {
- try {
- await deleteFeatureFlagApi(flagId)
- toast.success(t('featureFlags.deleted'))
+ if (page === 1 && !filterQuery) {
+ setIsSearchMode(false)
+ revalidator.revalidate()
+ } else {
loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)
- } catch (reason: any) {
- toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))
}
}
- const handleToggleFlag = async (flagId: string, enabled: boolean) => {
- try {
- const { updateFeatureFlag } = await import('~/api')
- await updateFeatureFlag(flagId, { enabled })
- toast.success(enabled ? t('featureFlags.flagEnabled') : t('featureFlags.flagDisabled'))
- // Update local state
- setFlags((prev) => prev.map((f) => (f.id === flagId ? { ...f, enabled } : f)))
- } catch (reason: any) {
- toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))
- }
- }
+ const handleDeleteFlag = useCallback(
+ (flagId: string) => {
+ processedActionRef.current = null
+ actionFetcher.submit({ intent: 'delete-feature-flag', flagId }, { method: 'POST' })
+ },
+ [actionFetcher],
+ )
+
+ const handleToggleFlag = useCallback(
+ (flagId: string, enabled: boolean) => {
+ processedActionRef.current = null
+ actionFetcher.submit({ intent: 'update-feature-flag', flagId, enabled: String(enabled) }, { method: 'POST' })
+ },
+ [actionFetcher],
+ )
- if (error && isLoading === false) {
+ if (error && !isLoading) {
return (
<StatusPage
type='error'
@@ -752,20 +787,6 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags
)
}
- // Show Loader only on initial load (no existing data)
- if ((isLoading || isLoading === null) && _isEmpty(flags)) {
- return (
- <div
- className={cx('flex flex-col bg-gray-50 dark:bg-slate-900', {
- 'min-h-including-header': !isEmbedded,
- 'min-h-screen': isEmbedded,
- })}
- >
- <Loader />
- </div>
- )
- }
-
return (
<>
<DashboardHeader showLiveVisitors />
@@ -870,4 +891,6 @@ const FeatureFlagsView = ({ period, from = '', to = '', timezone }: FeatureFlags
)
}
+const FeatureFlagsView = FeatureFlagsViewWrapper
+
export default FeatureFlagsView
diff --git a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
index 40dbd0f46..5d7c90040 100644
--- a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
+++ b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
@@ -4,33 +4,57 @@ import _find from 'lodash/find'
import _includes from 'lodash/includes'
import _isEmpty from 'lodash/isEmpty'
import { FilterIcon } from 'lucide-react'
-import { useState, useEffect, useMemo, useRef } from 'react'
+import { useState, useEffect, useMemo, useRef, Suspense, use } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link, useSearchParams } from 'react-router'
+import { Link, useSearchParams, useFetcher, useLoaderData, useRevalidator } from 'react-router'
import { toast } from 'sonner'
-import { addFunnel, updateFunnel, deleteFunnel, getFunnelData, getFunnels } from '~/api'
+import type { FunnelDataResponse } from '~/api/api.server'
import { FUNNELS_PERIOD_PAIRS } from '~/lib/constants'
import { Funnel, AnalyticsFunnel } from '~/lib/models/Project'
import NewFunnel from '~/modals/NewFunnel'
import { FunnelChart } from '~/pages/Project/tabs/Funnels/FunnelChart'
import FunnelsList from '~/pages/Project/tabs/Funnels/FunnelsList'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
-import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
-import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'
+import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
import { useAuth } from '~/providers/AuthProvider'
import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import type { ProjectLoaderData, ProjectViewActionData } from '~/routes/projects.$id'
import Loader from '~/ui/Loader'
import LoadingBar from '~/ui/LoadingBar'
import { Text } from '~/ui/Text'
import { nLocaleFormatter } from '~/utils/generic'
import routes from '~/utils/routes'
-const FunnelsView = () => {
+interface DeferredFunnelData {
+ funnelData: FunnelDataResponse | null
+}
+
+function FunnelDataResolver({ children }: { children: (data: DeferredFunnelData) => React.ReactNode }) {
+ const { funnelData: funnelDataPromise } = useLoaderData<ProjectLoaderData>()
+ const funnelData = funnelDataPromise ? use(funnelDataPromise) : null
+ return <>{children({ funnelData })}</>
+}
+
+function FunnelsViewWrapper() {
+ return (
+ <Suspense fallback={<Loader />}>
+ <FunnelDataResolver>{(deferredData) => <FunnelsViewInner deferredData={deferredData} />}</FunnelDataResolver>
+ </Suspense>
+ )
+}
+
+interface FunnelsViewInnerProps {
+ deferredData: DeferredFunnelData
+}
+
+const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
const { id, project, mergeProject, allowedToManage } = useCurrentProject()
const projectPassword = useProjectPassword(id)
+ const revalidator = useRevalidator()
const { isAuthenticated } = useAuth()
- const { timezone, period, dateRange, periodPairs, funnelsRefreshTrigger } = useViewProjectContext()
+ const { funnelsRefreshTrigger } = useRefreshTriggers()
+ const { periodPairs } = useViewProjectContext()
// Filter periods to only include those valid for funnels
const timeBucketSelectorItems = useMemo(() => {
@@ -43,17 +67,30 @@ const FunnelsView = () => {
const isEmbedded = searchParams.get('embedded') === 'true'
const isMountedRef = useRef(true)
+ const fetcher = useFetcher<ProjectViewActionData>()
+ const lastHandledData = useRef<ProjectViewActionData | null>(null)
// Funnels state
const [isNewFunnelOpened, setIsNewFunnelOpened] = useState(false)
const [funnelToEdit, setFunnelToEdit] = useState<Funnel | undefined>(undefined)
- const [funnelActionLoading, setFunnelActionLoading] = useState(false)
const [dataLoading, setDataLoading] = useState(false)
- const [analyticsLoading, setAnalyticsLoading] = useState(true)
+
+ // Initialize funnelAnalytics from loader data
const [funnelAnalytics, setFunnelAnalytics] = useState<{
funnel: AnalyticsFunnel[]
totalPageviews: number
- } | null>(null)
+ } | null>(() => {
+ if (deferredData.funnelData) {
+ return {
+ funnel: deferredData.funnelData.funnel,
+ totalPageviews: deferredData.funnelData.totalPageviews,
+ }
+ }
+ return null
+ })
+
+ const funnelActionLoading = fetcher.state !== 'idle'
+ const analyticsLoading = revalidator.state === 'loading'
// Search params without the funnel id. Needed for the back button.
const pureSearchParams = useMemo(() => {
@@ -85,119 +122,86 @@ const FunnelsView = () => {
}
}, [])
- const onFunnelCreate = async (name: string, steps: string[]) => {
- if (funnelActionLoading) {
- return
- }
-
- setFunnelActionLoading(true)
-
- try {
- await addFunnel(id, name, steps)
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelCreate)(addFunnel)', reason)
- toast.error(reason)
+ // Handle fetcher responses
+ useEffect(() => {
+ if (fetcher.state !== 'idle' || !fetcher.data) return
+ if (lastHandledData.current === fetcher.data) return
+ lastHandledData.current = fetcher.data
+
+ const { intent, success, error } = fetcher.data
+
+ if (success) {
+ if (intent === 'create-funnel') {
+ toast.success(t('apiNotifications.funnelCreated'))
+ setIsNewFunnelOpened(false)
+ setFunnelToEdit(undefined)
+ // Reload funnels list
+ fetcher.submit(
+ { intent: 'get-funnels', password: projectPassword },
+ { method: 'POST', action: `/projects/${id}` },
+ )
+ } else if (intent === 'update-funnel') {
+ toast.success(t('apiNotifications.funnelUpdated'))
+ setIsNewFunnelOpened(false)
+ setFunnelToEdit(undefined)
+ fetcher.submit(
+ { intent: 'get-funnels', password: projectPassword },
+ { method: 'POST', action: `/projects/${id}` },
+ )
+ // If the updated funnel is currently being viewed, revalidate to refresh analytics
+ const updatedFunnelId = (fetcher.data.data as { id?: string })?.id
+ if (updatedFunnelId && activeFunnel?.id === updatedFunnelId) {
+ setDataLoading(true)
+ revalidator.revalidate()
+ }
+ } else if (intent === 'delete-funnel') {
+ toast.success(t('apiNotifications.funnelDeleted'))
+ fetcher.submit(
+ { intent: 'get-funnels', password: projectPassword },
+ { method: 'POST', action: `/projects/${id}` },
+ )
+ } else if (intent === 'get-funnels' && fetcher.data.data) {
+ mergeProject({ funnels: fetcher.data.data as Funnel[] })
+ }
+ } else if (error) {
+ toast.error(error)
}
+ }, [fetcher.state, fetcher.data, t, id, projectPassword, fetcher, mergeProject, activeFunnel?.id, revalidator])
- try {
- const funnels = await getFunnels(id, projectPassword)
- mergeProject({ funnels })
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelCreate)(getFunnels)', reason)
- }
+ const onFunnelCreate = (name: string, steps: string[]) => {
+ if (funnelActionLoading) return
- toast.success(t('apiNotifications.funnelCreated'))
- setFunnelActionLoading(false)
+ fetcher.submit(
+ { intent: 'create-funnel', name, steps: JSON.stringify(steps) },
+ { method: 'POST', action: `/projects/${id}` },
+ )
}
- const onFunnelEdit = async (funnelId: string, name: string, steps: string[]) => {
- if (funnelActionLoading) {
- return
- }
-
- setFunnelActionLoading(true)
+ const onFunnelEdit = (funnelId: string, name: string, steps: string[]) => {
+ if (funnelActionLoading) return
- try {
- await updateFunnel(funnelId, id, name, steps)
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelEdit)(updateFunnel)', reason)
- toast.error(reason)
- }
-
- try {
- const funnels = await getFunnels(id, projectPassword)
- mergeProject({ funnels })
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelEdit)(getFunnels)', reason)
- }
-
- toast.success(t('apiNotifications.funnelUpdated'))
- setFunnelActionLoading(false)
+ fetcher.submit(
+ { intent: 'update-funnel', funnelId, name, steps: JSON.stringify(steps) },
+ { method: 'POST', action: `/projects/${id}` },
+ )
}
- const onFunnelDelete = async (funnelId: string) => {
- if (funnelActionLoading) {
- return
- }
-
- setFunnelActionLoading(true)
+ const onFunnelDelete = (funnelId: string) => {
+ if (funnelActionLoading) return
- try {
- await deleteFunnel(funnelId, id)
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelDelete)(deleteFunnel)', reason)
- toast.error(reason)
- }
-
- try {
- const funnels = await getFunnels(id, projectPassword)
- mergeProject({ funnels })
- } catch (reason: any) {
- console.error('[ERROR] (onFunnelDelete)(getFunnels)', reason)
- }
-
- toast.success(t('apiNotifications.funnelDeleted'))
- setFunnelActionLoading(false)
+ fetcher.submit({ intent: 'delete-funnel', funnelId }, { method: 'POST', action: `/projects/${id}` })
}
- const loadFunnelsData = async () => {
- if (!activeFunnel?.id) {
- return
- }
-
- setDataLoading(true)
-
- try {
- let dataFunnel: { funnel: AnalyticsFunnel[]; totalPageviews: number }
- let from
- let to
-
- if (dateRange) {
- from = getFormatDate(dateRange[0])
- to = getFormatDate(dateRange[1])
- }
-
- if (period === 'custom' && dateRange) {
- dataFunnel = await getFunnelData(id, '', from, to, timezone, activeFunnel.id, projectPassword)
- } else {
- dataFunnel = await getFunnelData(id, period, '', '', timezone, activeFunnel.id, projectPassword)
- }
-
- const { funnel, totalPageviews } = dataFunnel
-
- if (isMountedRef.current) {
- setFunnelAnalytics({ funnel, totalPageviews })
- setAnalyticsLoading(false)
- setDataLoading(false)
- }
- } catch (reason) {
- if (isMountedRef.current) {
- setAnalyticsLoading(false)
- setDataLoading(false)
- console.error('[ERROR](loadFunnelsData) Loading funnels data failed:', reason)
- }
+ // Sync funnelAnalytics when loader data changes
+ useEffect(() => {
+ if (deferredData.funnelData && revalidator.state === 'idle') {
+ setFunnelAnalytics({
+ funnel: deferredData.funnelData.funnel,
+ totalPageviews: deferredData.funnelData.totalPageviews,
+ })
+ setDataLoading(false)
}
- }
+ }, [deferredData.funnelData, revalidator.state])
const funnelSummary = useMemo(() => {
if (!funnelAnalytics || _isEmpty(funnelAnalytics.funnel)) {
@@ -217,24 +221,38 @@ const FunnelsView = () => {
}
}, [funnelAnalytics])
- // Load funnels data when activeFunnel changes
+ // When activeFunnel changes (URL params) and we have loader data, sync it
+ // The actual data fetching happens via the loader when URL changes
useEffect(() => {
- if (!project) return
-
- loadFunnelsData()
+ if (!project || !activeFunnel) return
+
+ // If we have loader data for this funnel, use it
+ if (deferredData.funnelData) {
+ setFunnelAnalytics({
+ funnel: deferredData.funnelData.funnel,
+ totalPageviews: deferredData.funnelData.totalPageviews,
+ })
+ } else {
+ // No loader data yet, trigger revalidation
+ setDataLoading(true)
+ revalidator.revalidate()
+ }
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [activeFunnel, project, dateRange, period])
+ }, [activeFunnel?.id])
// Handle refresh trigger from parent
useEffect(() => {
if (funnelsRefreshTrigger > 0) {
- loadFunnelsData()
+ if (activeFunnel?.id) {
+ setDataLoading(true)
+ }
+ revalidator.revalidate()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [funnelsRefreshTrigger])
- // Show loader during initial load when viewing a specific funnel
- if (activeFunnel && analyticsLoading) {
+ // Show loader during initial load when viewing a specific funnel (only when no data yet)
+ if (activeFunnel && analyticsLoading && !funnelAnalytics) {
return (
<div
className={cx('flex flex-col bg-gray-50 dark:bg-slate-900', {
@@ -407,4 +425,6 @@ const FunnelsView = () => {
)
}
+const FunnelsView = FunnelsViewWrapper
+
export default FunnelsView
diff --git a/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx b/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
index 5585b5170..556aa6dc6 100644
--- a/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
+++ b/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
@@ -2,11 +2,13 @@ import { Dialog, DialogBackdrop, DialogPanel, DialogTitle } from '@headlessui/re
import { XMarkIcon } from '@heroicons/react/24/outline'
import _map from 'lodash/map'
import { Trash2Icon, PlusIcon } from 'lucide-react'
-import { useState, useEffect } from 'react'
+import { useState, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { getGoal, createGoal, updateGoal, type CreateGoal } from '~/api'
+import { useGoalProxy } from '~/hooks/useAnalyticsProxy'
+import type { ProjectViewActionData } from '~/routes/projects.$id'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import Loader from '~/ui/Loader'
@@ -30,12 +32,14 @@ interface GoalSettingsModalProps {
goalId?: string | null
}
-const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId, goalId }: GoalSettingsModalProps) => {
+const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId: _projectId, goalId }: GoalSettingsModalProps) => {
const { t } = useTranslation()
+ const fetcher = useFetcher<ProjectViewActionData>()
+ const processedRef = useRef<string | null>(null)
+ const goalProxy = useGoalProxy()
const isNew = !goalId
const [isLoading, setIsLoading] = useState(false)
- const [isSaving, setIsSaving] = useState(false)
// Form state
const [name, setName] = useState('')
@@ -44,6 +48,8 @@ const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId, goalId }: Go
const [value, setValue] = useState('')
const [metadataFilters, setMetadataFilters] = useState<{ key: string; value: string }[]>([])
+ const isSaving = fetcher.state === 'submitting'
+
const resetForm = () => {
setName('')
setType('pageview')
@@ -56,7 +62,10 @@ const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId, goalId }: Go
if (!goalId) return
setIsLoading(true)
try {
- const goal = await getGoal(goalId)
+ const goal = await goalProxy.fetchGoal(goalId)
+ if (!goal) {
+ throw new Error('Failed to load goal')
+ }
setName(goal.name)
setType(goal.type)
setMatchType(goal.matchType)
@@ -81,39 +90,52 @@ const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId, goalId }: Go
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen, goalId])
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault()
- setIsSaving(true)
+ // Handle fetcher responses
+ useEffect(() => {
+ if (!fetcher.data || fetcher.state !== 'idle') return
- try {
- if (isNew) {
- const data: CreateGoal = {
- pid: projectId,
- name,
- type,
- matchType,
- value: value || undefined,
- metadataFilters: metadataFilters.length > 0 ? metadataFilters : undefined,
- }
- await createGoal(data)
+ const responseKey = `${fetcher.data.intent}-${fetcher.data.success}`
+ if (processedRef.current === responseKey) return
+ processedRef.current = responseKey
+
+ if (fetcher.data.success) {
+ const { intent } = fetcher.data
+ if (intent === 'create-goal') {
toast.success(t('goals.created'))
- } else if (goalId) {
- await updateGoal(goalId, {
- name,
- type,
- matchType,
- value: value || null,
- metadataFilters: metadataFilters.length > 0 ? metadataFilters : null,
- })
+ } else if (intent === 'update-goal') {
toast.success(t('goals.updated'))
}
onSuccess()
onClose()
- } catch (err: any) {
- toast.error(err?.message || t('apiNotifications.somethingWentWrong'))
- } finally {
- setIsSaving(false)
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ }, [fetcher.data, fetcher.state, t, onSuccess, onClose])
+
+ // Reset processed ref when modal opens
+ useEffect(() => {
+ if (isOpen) {
+ processedRef.current = null
}
+ }, [isOpen])
+
+ const handleSubmit = (e: React.FormEvent) => {
+ e.preventDefault()
+ processedRef.current = null
+
+ const formData = new FormData()
+ formData.set('intent', isNew ? 'create-goal' : 'update-goal')
+ formData.set('name', name)
+ formData.set('type', type)
+ formData.set('matchType', matchType)
+ formData.set('value', value)
+ formData.set('metadataFilters', JSON.stringify(metadataFilters))
+
+ if (!isNew && goalId) {
+ formData.set('goalId', goalId)
+ }
+
+ fetcher.submit(formData, { method: 'post' })
}
const addMetadataFilter = () => {
diff --git a/web/app/pages/Project/tabs/Goals/GoalsView.tsx b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
index 602111077..80cba11d5 100644
--- a/web/app/pages/Project/tabs/Goals/GoalsView.tsx
+++ b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
@@ -17,21 +17,13 @@ import {
MousePointerClickIcon,
ChevronDownIcon,
} from 'lucide-react'
-import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
+import { useState, useEffect, useMemo, useRef, useCallback, Suspense, use } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSearchParams } from 'react-router'
+import { useSearchParams, useFetcher, useLoaderData, useRevalidator } from 'react-router'
import { toast } from 'sonner'
-import {
- deleteGoal as deleteGoalApi,
- getProjectGoals,
- getGoalStats,
- getGoalChart,
- DEFAULT_GOALS_TAKE,
- type Goal,
- type GoalStats,
- type GoalChartData,
-} from '~/api'
+import type { GoalsResponse, Goal, GoalStats, GoalChartData } from '~/api/api.server'
+import { useGoalStatsProxy, useGoalChartProxy } from '~/hooks/useAnalyticsProxy'
import {
TimeFormat,
tbsFormatMapper,
@@ -41,8 +33,9 @@ import {
chartTypes,
} from '~/lib/constants'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
-import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+import type { ProjectLoaderData, ProjectViewActionData } from '~/routes/projects.$id'
import BillboardChart from '~/ui/BillboardChart'
import Button from '~/ui/Button'
import Spin from '~/ui/icons/Spin'
@@ -58,6 +51,8 @@ import routes from '~/utils/routes'
import GoalSettingsModal from './GoalSettingsModal'
+const DEFAULT_GOALS_TAKE = 20
+
// Calculate optimal Y axis ticks
const calculateOptimalTicks = (data: number[], targetCount: number = 6): number[] => {
const validData = data.filter((n) => n !== undefined && n !== null && Number.isFinite(n))
@@ -427,18 +422,44 @@ interface GoalsViewProps {
timezone?: string
}
-const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) => {
+interface DeferredGoalsData {
+ goalsData: GoalsResponse | null
+}
+
+function GoalsDataResolver({ children }: { children: (data: DeferredGoalsData) => React.ReactNode }) {
+ const { goalsData: goalsDataPromise } = useLoaderData<ProjectLoaderData>()
+ const goalsData = goalsDataPromise ? use(goalsDataPromise) : null
+ return <>{children({ goalsData })}</>
+}
+
+function GoalsViewWrapper(props: GoalsViewProps) {
+ return (
+ <Suspense fallback={<Loader />}>
+ <GoalsDataResolver>
+ {(deferredData) => <GoalsViewInner {...props} deferredData={deferredData} />}
+ </GoalsDataResolver>
+ </Suspense>
+ )
+}
+
+interface GoalsViewInnerProps extends GoalsViewProps {
+ deferredData: DeferredGoalsData
+}
+
+const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }: GoalsViewInnerProps) => {
const { id } = useCurrentProject()
- const { goalsRefreshTrigger, timeBucket, timeFormat } = useViewProjectContext()
- const [searchParams] = useSearchParams()
- const isEmbedded = searchParams.get('embedded') === 'true'
+ const revalidator = useRevalidator()
+ const { goalsRefreshTrigger } = useRefreshTriggers()
+ const { timeBucket, timeFormat } = useViewProjectContext()
+ const [_searchParams] = useSearchParams()
const { t } = useTranslation()
+ const fetcher = useFetcher<ProjectViewActionData>()
- const [isLoading, setIsLoading] = useState<boolean | null>(null)
- const isLoadingRef = useRef(false) // Use ref to avoid stale closure issues in loadGoals
- const isMountedRef = useRef(true) // Track if component is mounted to prevent memory leaks
- const [total, setTotal] = useState(0)
- const [goals, setGoals] = useState<Goal[]>([])
+ // Track if we're in search/pagination mode
+ const [isSearchMode, setIsSearchMode] = useState(false)
+ const isMountedRef = useRef(true)
+ const [total, setTotal] = useState(() => deferredData.goalsData?.total || 0)
+ const [goals, setGoals] = useState<Goal[]>(() => deferredData.goalsData?.results || [])
const [goalStats, setGoalStats] = useState<Record<string, GoalStats | null>>({})
const [statsLoading, setStatsLoading] = useState<Record<string, boolean>>({})
const [page, setPage] = useState(1)
@@ -455,6 +476,8 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
const [isModalOpen, setIsModalOpen] = useState(false)
const [editingGoalId, setEditingGoalId] = useState<string | null>(null)
+ const isLoading = revalidator.state === 'loading' || fetcher.state !== 'idle'
+
// Cleanup on unmount
useEffect(() => {
isMountedRef.current = true
@@ -463,6 +486,14 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
}
}, [])
+ // Sync state when loader provides new data
+ useEffect(() => {
+ if (deferredData.goalsData && revalidator.state === 'idle' && !isSearchMode) {
+ setGoals(deferredData.goalsData.results || [])
+ setTotal(deferredData.goalsData.total || 0)
+ }
+ }, [revalidator.state, deferredData.goalsData, isSearchMode])
+
const pageAmount = Math.ceil(total / DEFAULT_GOALS_TAKE)
// Debounced search handler
@@ -483,35 +514,49 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
}
}, [filterQuery, debouncedSetSearch])
- const loadGoals = async (take: number, skip: number, search?: string) => {
- if (isLoadingRef.current) {
- return
- }
- isLoadingRef.current = true
- setIsLoading(true)
+ const loadGoals = useCallback(
+ (take: number, skip: number, search?: string) => {
+ if (fetcher.state !== 'idle') return
+ setIsSearchMode(true)
+ setError(null)
+
+ fetcher.submit(
+ {
+ intent: 'get-project-goals',
+ take: String(take),
+ skip: String(skip),
+ search: search || '',
+ },
+ { method: 'POST' },
+ )
+ },
+ [fetcher],
+ )
- try {
- const result = await getProjectGoals(id, take, skip, search)
- if (isMountedRef.current) {
- setGoals(result.results)
- setTotal(result.total)
- }
- } catch (reason: any) {
- if (isMountedRef.current) {
- setError(reason?.message || reason?.toString() || 'Unknown error')
- }
- } finally {
- isLoadingRef.current = false
+ // Handle fetcher response for goals list
+ useEffect(() => {
+ if (fetcher.data?.intent === 'get-project-goals' && fetcher.state === 'idle') {
if (isMountedRef.current) {
- setIsLoading(false)
+ if (fetcher.data.success && fetcher.data.data) {
+ const result = fetcher.data.data as { results: Goal[]; total: number }
+ setGoals(result.results)
+ setTotal(result.total)
+ setError(null)
+ } else if (fetcher.data.error) {
+ setError(fetcher.data.error)
+ }
}
}
- }
+ }, [fetcher.data, fetcher.state])
+
+ // Proxy hooks for stats and chart
+ const statsProxy = useGoalStatsProxy()
+ const chartProxy = useGoalChartProxy()
const loadGoalStats = async (goalId: string) => {
setStatsLoading((prev) => ({ ...prev, [goalId]: true }))
try {
- const stats = await getGoalStats(goalId, period, from, to, timezone)
+ const stats = await statsProxy.fetchStats(goalId, { period, from, to, timezone })
if (isMountedRef.current) {
setGoalStats((prev) => ({ ...prev, [goalId]: stats }))
}
@@ -530,8 +575,8 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
const loadGoalChartData = async (goalId: string, showLoading = true) => {
setChartLoading((prev) => ({ ...prev, [goalId]: showLoading ? true : prev[goalId] }))
try {
- const result = await getGoalChart(goalId, period, from, to, timeBucket, timezone)
- if (isMountedRef.current) {
+ const result = await chartProxy.fetchChart(goalId, { period, from, to, timeBucket, timezone })
+ if (isMountedRef.current && result) {
setGoalChartData((prev) => ({ ...prev, [goalId]: result.chart }))
}
} catch (err) {
@@ -540,7 +585,6 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
setGoalChartData((prev) => ({ ...prev, [goalId]: null }))
}
} finally {
- // Always clear loading state
if (isMountedRef.current) {
setChartLoading((prev) => ({ ...prev, [goalId]: false }))
}
@@ -560,8 +604,11 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
}
}
+ // Handle page/search changes - use fetcher for pagination
useEffect(() => {
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
+ if (page > 1 || debouncedSearch || isSearchMode) {
+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
+ }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page, debouncedSearch])
@@ -586,15 +633,17 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
// Refresh goals data when refresh button is clicked
useEffect(() => {
if (goalsRefreshTrigger > 0) {
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
+ if (page === 1 && !debouncedSearch) {
+ setIsSearchMode(false)
+ revalidator.revalidate()
+ } else {
+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
+ }
// Clear cached chart data for non-expanded goals, silently refresh expanded goal
if (expandedGoalId) {
- // Keep only the expanded goal's data while we fetch fresh data
setGoalChartData((prev) => ({ [expandedGoalId]: prev[expandedGoalId] }))
- // Silently fetch new data without showing loading indicator
loadGoalChartData(expandedGoalId, false)
} else {
- // No expanded goal, just clear all cached data
setGoalChartData({})
}
}
@@ -617,21 +666,37 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
}
const handleModalSuccess = () => {
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
+ if (page === 1 && !debouncedSearch) {
+ setIsSearchMode(false)
+ revalidator.revalidate()
+ } else {
+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
+ }
}
- const handleDeleteGoal = async (goalId: string) => {
- try {
- await deleteGoalApi(goalId)
+ // Handle fetcher responses for delete
+ useEffect(() => {
+ if (fetcher.data?.success && fetcher.data?.intent === 'delete-goal') {
toast.success(t('goals.deleted'))
- // Reload goals
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
- } catch (reason: any) {
- toast.error(reason?.response?.data?.message || reason?.message || t('apiNotifications.somethingWentWrong'))
+ if (page === 1 && !debouncedSearch) {
+ setIsSearchMode(false)
+ revalidator.revalidate()
+ } else {
+ loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
+ }
+ } else if (fetcher.data?.error && fetcher.data?.intent === 'delete-goal') {
+ toast.error(fetcher.data.error)
}
+ }, [fetcher.data, t, page, debouncedSearch, revalidator]) // eslint-disable-line react-hooks/exhaustive-deps
+
+ const handleDeleteGoal = (goalId: string) => {
+ const formData = new FormData()
+ formData.set('intent', 'delete-goal')
+ formData.set('goalId', goalId)
+ fetcher.submit(formData, { method: 'post' })
}
- if (error && isLoading === false) {
+ if (error && !isLoading) {
return (
<StatusPage
type='error'
@@ -645,20 +710,6 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
)
}
- // Show Loader only on initial load (no existing data)
- if ((isLoading || isLoading === null) && _isEmpty(goals)) {
- return (
- <div
- className={cx('flex flex-col bg-gray-50 dark:bg-slate-900', {
- 'min-h-including-header': !isEmbedded,
- 'min-h-screen': isEmbedded,
- })}
- >
- <Loader />
- </div>
- )
- }
-
return (
<>
<DashboardHeader showLiveVisitors />
@@ -753,4 +804,6 @@ const GoalsView = ({ period, from = '', to = '', timezone }: GoalsViewProps) =>
)
}
+const GoalsView = GoalsViewWrapper
+
export default GoalsView
diff --git a/web/app/pages/Project/tabs/Performance/PerformanceView.tsx b/web/app/pages/Project/tabs/Performance/PerformanceView.tsx
index 998e42082..1ed461d86 100644
--- a/web/app/pages/Project/tabs/Performance/PerformanceView.tsx
+++ b/web/app/pages/Project/tabs/Performance/PerformanceView.tsx
@@ -1,19 +1,16 @@
import cx from 'clsx'
-import dayjs from 'dayjs'
-import _find from 'lodash/find'
import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _map from 'lodash/map'
import { EyeIcon, PercentIcon } from 'lucide-react'
-import { useState, useEffect, useMemo, useRef, lazy, Suspense } from 'react'
+import { useState, useEffect, useMemo, useRef, lazy, Suspense, use } from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
-import { useNavigate, useSearchParams } from 'react-router'
-import { toast } from 'sonner'
+import { useNavigate, useSearchParams, useLoaderData, useRevalidator } from 'react-router'
-import { getPerfData, getPerformanceCompareData, getPerformanceOverallStats, getOverallStats } from '~/api'
+import type { PerformanceDataResponse, PerformanceOverallObject } from '~/api/api.server'
import { useAnnotations } from '~/hooks/useAnnotations'
-import { PERFORMANCE_PANELS_ORDER, chartTypes, PERIOD_PAIRS_COMPARE, type TimeBucket } from '~/lib/constants'
+import { PERFORMANCE_PANELS_ORDER, chartTypes } from '~/lib/constants'
import { CountryEntry } from '~/lib/models/Entry'
import { OverallPerformanceObject } from '~/lib/models/Project'
import AnnotationModal from '~/modals/AnnotationModal'
@@ -26,16 +23,16 @@ import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
import Filters from '~/pages/Project/View/components/Filters'
import NoEvents from '~/pages/Project/View/components/NoEvents'
import { Panel } from '~/pages/Project/View/Panels'
-import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
import {
- getFormatDate,
panelIconMapping,
CHART_METRICS_MAPPING_PERF,
CHART_MEASURES_MAPPING_PERF,
getDeviceRowMapper,
} from '~/pages/Project/View/ViewProject.helpers'
-import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
+import type { ProjectLoaderData } from '~/routes/projects.$id'
import Dropdown from '~/ui/Dropdown'
import Loader from '~/ui/Loader'
import LoadingBar from '~/ui/LoadingBar'
@@ -43,109 +40,48 @@ import { getStringFromTime, getTimeFromSeconds } from '~/utils/generic'
const InteractiveMap = lazy(() => import('~/pages/Project/View/components/InteractiveMap'))
-// Period to compare date mapping
-const periodToCompareDate = [
- {
- period: '1d',
- formula: (date?: Date[]) =>
- date
- ? { from: getFormatDate(dayjs(date[0]).subtract(1, 'day').toDate()), to: getFormatDate(date[0]) }
- : {
- from: dayjs().subtract(2, 'day').format('YYYY-MM-DD'),
- to: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
- },
- },
- {
- period: '1h',
- formula: () => ({
- from: dayjs().subtract(2, 'hour').format('YYYY-MM-DD HH:mm:ss'),
- to: dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
- }),
- },
- {
- period: 'today',
- formula: () => ({ from: dayjs().subtract(1, 'day').format('YYYY-MM-DD'), to: dayjs().format('YYYY-MM-DD') }),
- },
- {
- period: 'yesterday',
- formula: () => ({
- from: dayjs().subtract(2, 'day').format('YYYY-MM-DD'),
- to: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
- }),
- },
- {
- period: '7d',
- formula: (date?: Date[]) =>
- date
- ? { from: getFormatDate(dayjs(date[0]).subtract(7, 'day').toDate()), to: getFormatDate(date[0]) }
- : {
- from: dayjs().subtract(14, 'day').format('YYYY-MM-DD'),
- to: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
- },
- },
- {
- period: '4w',
- formula: (date?: Date[]) =>
- date
- ? { from: getFormatDate(dayjs(date[0]).subtract(4, 'week').toDate()), to: getFormatDate(date[0]) }
- : {
- from: dayjs().subtract(8, 'week').format('YYYY-MM-DD'),
- to: dayjs().subtract(4, 'week').format('YYYY-MM-DD'),
- },
- },
- {
- period: '3M',
- formula: (date?: Date[]) =>
- date
- ? { from: getFormatDate(dayjs(date[0]).subtract(3, 'month').toDate()), to: getFormatDate(date[0]) }
- : {
- from: dayjs().subtract(6, 'month').format('YYYY-MM-DD'),
- to: dayjs().subtract(3, 'month').format('YYYY-MM-DD'),
- },
- },
- {
- period: '12M',
- formula: (date?: Date[]) =>
- date
- ? { from: getFormatDate(dayjs(date[0]).subtract(12, 'month').toDate()), to: getFormatDate(date[0]) }
- : {
- from: dayjs().subtract(24, 'month').format('YYYY-MM-DD'),
- to: dayjs().subtract(12, 'month').format('YYYY-MM-DD'),
- },
- },
- {
- period: '24M',
- formula: (date?: Date[]) =>
- date
- ? { from: getFormatDate(dayjs(date[0]).subtract(24, 'month').toDate()), to: getFormatDate(date[0]) }
- : {
- from: dayjs().subtract(48, 'month').format('YYYY-MM-DD'),
- to: dayjs().subtract(24, 'month').format('YYYY-MM-DD'),
- },
- },
-]
-
interface PerformanceViewProps {
tnMapping: Record<string, string>
}
-const PerformanceView = ({ tnMapping }: PerformanceViewProps) => {
+interface DeferredPerfData {
+ perfData: PerformanceDataResponse | null
+ perfOverallStats: Record<string, PerformanceOverallObject> | null
+}
+
+function PerfDataResolver({ children }: { children: (data: DeferredPerfData) => React.ReactNode }) {
+ const { perfData: perfDataPromise, perfOverallStats: perfOverallStatsPromise } = useLoaderData<ProjectLoaderData>()
+
+ const perfData = perfDataPromise ? use(perfDataPromise) : null
+ const perfOverallStats = perfOverallStatsPromise ? use(perfOverallStatsPromise) : null
+
+ return <>{children({ perfData, perfOverallStats })}</>
+}
+
+function PerformanceViewWrapper(props: PerformanceViewProps) {
+ return (
+ <Suspense fallback={<Loader />}>
+ <PerfDataResolver>
+ {(deferredData) => <PerformanceViewInner {...props} deferredData={deferredData} />}
+ </PerfDataResolver>
+ </Suspense>
+ )
+}
+
+interface PerformanceViewInnerProps extends PerformanceViewProps {
+ deferredData: DeferredPerfData
+}
+
+const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerProps) => {
const { id, project, allowedToManage } = useCurrentProject()
- const projectPassword = useProjectPassword(id)
+ const revalidator = useRevalidator()
+ const { performanceRefreshTrigger } = useRefreshTriggers()
const {
- performanceRefreshTrigger,
- timezone,
- period,
- dateRange,
filters,
timeFormat,
timeBucket,
- activePeriod,
- // Comparison state from context
- isActiveCompare,
- dateRangeCompare,
+ // Comparison state from context (not implemented via SSR yet)
activePeriodCompare,
- compareDisable,
// Chart state from context
chartType,
setChartTypeOnClick,
@@ -184,21 +120,77 @@ const PerformanceView = ({ tnMapping }: PerformanceViewProps) => {
const { theme } = useTheme()
const navigate = useNavigate()
const [searchParams, setSearchParams] = useSearchParams()
- const isEmbedded = searchParams.get('embedded') === 'true'
- // Performance-specific state
+ // State for data - initialized from loader, can be overridden by client-side fetches
const [dataLoading, setDataLoading] = useState(false)
- const [analyticsLoading, setAnalyticsLoading] = useState(true)
- const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)
- const [panelsData, setPanelsData] = useState<any>({})
- const [chartData, setChartData] = useState<any>({})
- const [overall, setOverall] = useState<Partial<OverallPerformanceObject>>({})
- const [overallCompare, setOverallCompare] = useState<Partial<OverallPerformanceObject>>({})
- const [chartDataCompare, setChartDataCompare] = useState<any>({})
-
- // Chart metrics and measures
- const [activeChartMetrics, setActiveChartMetrics] = useState(CHART_METRICS_MAPPING_PERF.timing)
- const [activeMeasure, setActiveMeasure] = useState(CHART_MEASURES_MAPPING_PERF.median)
+ const [panelsData, setPanelsData] = useState<any>(() => {
+ if (deferredData.perfData?.params) {
+ return {
+ types: _keys(deferredData.perfData.params),
+ data: deferredData.perfData.params,
+ }
+ }
+ return { data: {} }
+ })
+ const [chartData, setChartData] = useState<any>(() => deferredData.perfData?.chart || {})
+ const [overall, setOverall] = useState<Partial<OverallPerformanceObject>>(() => {
+ if (deferredData.perfOverallStats && id) {
+ return deferredData.perfOverallStats[id] || {}
+ }
+ return {}
+ })
+
+ // Track if we've ever shown actual content to prevent NoEvents flash during exit animation
+ const hasShownContentRef = useRef(false)
+
+ const isPanelsDataEmptyRaw = _isEmpty(panelsData.data)
+
+ // Track when we've shown content to prevent NoEvents flash during exit animation
+ if (!isPanelsDataEmptyRaw) {
+ hasShownContentRef.current = true
+ }
+
+ // Don't show NoEvents if we've previously shown content (prevents flash during tab switch)
+ const isPanelsDataEmpty = isPanelsDataEmptyRaw && !hasShownContentRef.current
+
+ // Sync state when loader provides new data (e.g., after URL changes)
+ useEffect(() => {
+ if (revalidator.state === 'idle' && deferredData.perfData) {
+ const { chart, params } = deferredData.perfData
+ setChartData(chart || {})
+ setPanelsData({
+ types: _keys(params),
+ data: params,
+ })
+ if (deferredData.perfOverallStats && id) {
+ setOverall(deferredData.perfOverallStats[id] || {})
+ }
+ setDataLoading(false)
+ } else if (revalidator.state === 'loading') {
+ setDataLoading(true)
+ }
+ }, [revalidator.state, deferredData, id])
+
+ // Get chart metrics and measure from URL params (SSR-friendly)
+ const activeChartMetrics = searchParams.get('perfMetric') || CHART_METRICS_MAPPING_PERF.timing
+ const activeMeasure = searchParams.get('measure') || CHART_MEASURES_MAPPING_PERF.median
+
+ // Update URL when changing chart metrics or measure
+ const setActiveChartMetrics = (metric: string) => {
+ const newParams = new URLSearchParams(searchParams.toString())
+ newParams.set('perfMetric', metric)
+ setSearchParams(newParams)
+ }
+
+ const setActiveMeasure = (measure: string) => {
+ const newParams = new URLSearchParams(searchParams.toString())
+ newParams.set('measure', measure)
+ setSearchParams(newParams)
+ }
+
+ // Compare mode not implemented via SSR yet - use empty defaults
+ const overallCompare: Partial<OverallPerformanceObject> = {}
+ const chartDataCompare: any = {}
// Panel active tabs
const [activeTabs, setActiveTabs] = useState<{
@@ -211,16 +203,6 @@ const PerformanceView = ({ tnMapping }: PerformanceViewProps) => {
device: 'br',
})
- const isMountedRef = useRef(true)
-
- // Cleanup on unmount
- useEffect(() => {
- isMountedRef.current = true
- return () => {
- isMountedRef.current = false
- }
- }, [])
-
const chartMetrics = useMemo(
() => [
{
@@ -322,202 +304,14 @@ const PerformanceView = ({ tnMapping }: PerformanceViewProps) => {
return { browserVersions }
}, [panelsData.data?.brv])
- const loadAnalytics = async () => {
- if (!project) return
-
- setDataLoading(true)
-
- try {
- let dataPerf: { timeBucket?: TimeBucket[]; params?: any; chart?: any }
- let from
- let to
- let dataCompare
- let fromCompare: string | undefined
- let toCompare: string | undefined
- let rawOverall: any
-
- const measure =
- activeChartMetrics === CHART_METRICS_MAPPING_PERF.quantiles
- ? CHART_METRICS_MAPPING_PERF.quantiles
- : activeMeasure
-
- if (isActiveCompare) {
- if (dateRangeCompare && activePeriodCompare === PERIOD_PAIRS_COMPARE.CUSTOM) {
- let start
- let end
- let diff
- const startCompare = dayjs.utc(dateRangeCompare[0])
- const endCompare = dayjs.utc(dateRangeCompare[1])
- const diffCompare = endCompare.diff(startCompare, 'day')
-
- if (activePeriod?.period === 'custom' && dateRange) {
- start = dayjs.utc(dateRange[0])
- end = dayjs.utc(dateRange[1])
- diff = end.diff(start, 'day')
- }
-
- // @ts-expect-error
- if (activePeriod?.period === 'custom' ? diffCompare <= diff : diffCompare <= activePeriod?.countDays) {
- fromCompare = getFormatDate(dateRangeCompare[0])
- toCompare = getFormatDate(dateRangeCompare[1])
- } else {
- toast.error(t('project.compareDateRangeError'))
- compareDisable()
- }
- } else {
- let date
- if (dateRange) {
- date = _find(periodToCompareDate, (item) => item.period === period)?.formula(dateRange)
- } else {
- date = _find(periodToCompareDate, (item) => item.period === period)?.formula()
- }
-
- if (date) {
- fromCompare = date.from
- toCompare = date.to
- }
- }
-
- if (!_isEmpty(fromCompare) && !_isEmpty(toCompare)) {
- dataCompare = await getPerformanceCompareData(
- id,
- timeBucket,
- '',
- filters,
- fromCompare,
- toCompare,
- timezone,
- measure,
- projectPassword,
- )
- const compareOverall = await getPerformanceOverallStats(
- [id],
- 'custom',
- fromCompare,
- toCompare,
- timezone,
- filters,
- measure,
- projectPassword,
- )
- dataCompare.overall = compareOverall[id]
- }
- }
-
- if (dateRange) {
- from = getFormatDate(dateRange[0])
- to = getFormatDate(dateRange[1])
- }
-
- if (period === 'custom' && dateRange) {
- dataPerf = await getPerfData(id, timeBucket, '', filters, from, to, timezone, measure, projectPassword)
- rawOverall = await getOverallStats([id], timeBucket, period, from, to, timezone, filters, projectPassword)
- } else {
- dataPerf = await getPerfData(id, timeBucket, period, filters, '', '', timezone, measure, projectPassword)
- rawOverall = await getPerformanceOverallStats([id], period, '', '', timezone, filters, measure, projectPassword)
- }
-
- // @ts-expect-error
- dataPerf.overall = rawOverall[id]
-
- if (isMountedRef.current) {
- setOverall(rawOverall[id])
-
- if (_keys(dataPerf).length < 2) {
- setIsPanelsDataEmpty(true)
- setDataLoading(false)
- setAnalyticsLoading(false)
- return
- }
-
- let newTimebucket = timeBucket
-
- if (period === 'all' && !_isEmpty(dataPerf.timeBucket)) {
- newTimebucket = dataPerf.timeBucket?.includes(timeBucket as TimeBucket)
- ? timeBucket
- : (dataPerf.timeBucket?.[0] as TimeBucket)
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.set('timeBucket', newTimebucket)
- setSearchParams(newSearchParams)
- }
-
- if (!_isEmpty(dataCompare)) {
- if (!_isEmpty(dataCompare?.chart)) {
- setChartDataCompare(dataCompare.chart)
- }
-
- if (!_isEmpty(dataCompare?.overall)) {
- setOverallCompare(dataCompare.overall)
- }
- }
-
- if (_isEmpty(dataPerf.params)) {
- setIsPanelsDataEmpty(true)
- } else {
- const { chart: chartPerf } = dataPerf
- setChartData(chartPerf)
-
- setPanelsData({
- types: _keys(dataPerf.params),
- data: dataPerf.params,
- })
-
- setIsPanelsDataEmpty(false)
- }
-
- setAnalyticsLoading(false)
- setDataLoading(false)
- }
- } catch (reason) {
- if (isMountedRef.current) {
- setAnalyticsLoading(false)
- setDataLoading(false)
- setIsPanelsDataEmpty(true)
- console.error('[ERROR](loadAnalytics) Loading analytics data failed:', reason)
- }
- }
- }
-
- // Load analytics on mount and when dependencies change
- useEffect(() => {
- if (!project) return
- loadAnalytics()
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [
- activeMeasure,
- activeChartMetrics,
- filters,
- project,
- isActiveCompare,
- dateRange,
- period,
- timeBucket,
- dateRangeCompare,
- activePeriodCompare,
- ])
-
// Handle refresh trigger
useEffect(() => {
if (performanceRefreshTrigger > 0) {
- loadAnalytics()
+ revalidator.revalidate()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [performanceRefreshTrigger])
- // Show loader during initial load
- if (analyticsLoading) {
- return (
- <div
- className={cx('flex flex-col bg-gray-50 dark:bg-slate-900', {
- 'min-h-including-header': !isEmbedded,
- 'min-h-screen': isEmbedded,
- })}
- >
- <Loader />
- </div>
- )
- }
-
// Show no events if data is empty
if (isPanelsDataEmpty) {
return (
@@ -615,7 +409,7 @@ const PerformanceView = ({ tnMapping }: PerformanceViewProps) => {
<>
<DashboardHeader />
{dataLoading && !isPanelsDataEmpty ? <LoadingBar /> : null}
- <div className={cx({ hidden: isPanelsDataEmpty || analyticsLoading })}>
+ <div className={cx({ hidden: isPanelsDataEmpty })}>
{!isPanelsDataEmpty ? <Filters className='mb-3' tnMapping={tnMapping} /> : null}
<div className='relative overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-800/25'>
<div className='mb-3 flex w-full items-center justify-end gap-2 lg:absolute lg:top-2 lg:right-2 lg:mb-0 lg:w-auto lg:justify-normal'>
@@ -893,4 +687,6 @@ const PerformanceView = ({ tnMapping }: PerformanceViewProps) => {
)
}
+const PerformanceView = PerformanceViewWrapper
+
export default PerformanceView
diff --git a/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx b/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
index 056321227..52dc71be5 100644
--- a/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
+++ b/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
@@ -5,13 +5,14 @@ import { useState, useEffect, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useSearchParams } from 'react-router'
-import { getProfiles, getProfile, getProfileSessions } from '~/api'
+import { ApiProfile } from '~/api/api.server'
+import { useProfilesProxy, useProfileProxy, useProfileSessionsProxy } from '~/hooks/useAnalyticsProxy'
import { Profile, ProfileDetails as ProfileDetailsType, Session } from '~/lib/models/Project'
import NoProfiles from '~/pages/Project/tabs/Profiles/components/NoProfiles'
import { ProfileDetails } from '~/pages/Project/tabs/Profiles/ProfileDetails'
import { Profiles, ProfilesFilter } from '~/pages/Project/tabs/Profiles/Profiles'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
-import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'
import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
import Loader from '~/ui/Loader'
@@ -19,6 +20,21 @@ import LoadingBar from '~/ui/LoadingBar'
import Filters from '../../View/components/Filters'
+const mapApiProfileToUI = (apiProfile: ApiProfile): Profile => ({
+ profileId: apiProfile.profileId,
+ isIdentified: apiProfile.isIdentified,
+ sessionsCount: apiProfile.sessionsCount,
+ pageviewsCount: apiProfile.pageviewsCount,
+ eventsCount: apiProfile.eventsCount,
+ errorsCount: apiProfile.errorsCount,
+ firstSeen: apiProfile.firstSeen,
+ lastSeen: apiProfile.lastSeen,
+ cc: apiProfile.cc,
+ os: apiProfile.os,
+ br: apiProfile.br,
+ dv: apiProfile.dv,
+})
+
const SESSIONS_TAKE = 30
interface ProfilesViewProps {
@@ -28,9 +44,13 @@ interface ProfilesViewProps {
const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
const { id, project } = useCurrentProject()
const projectPassword = useProjectPassword(id)
- const { timezone, period, dateRange, filters, timeFormat, profilesRefreshTrigger } = useViewProjectContext()
+ const { profilesRefreshTrigger } = useRefreshTriggers()
+ const { timezone, period, dateRange, filters, timeFormat } = useViewProjectContext()
const { t } = useTranslation('common')
const [searchParams] = useSearchParams()
+ const profilesProxy = useProfilesProxy()
+ const profileProxy = useProfileProxy()
+ const profileSessionsProxy = useProfileSessionsProxy()
// Profiles state
const [profilesSkip, setProfilesSkip] = useState(0)
@@ -51,6 +71,8 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
const prevActiveProfileIdRef = useRef<string | null>(activeProfileId)
const profilesRequestIdRef = useRef(0)
+ const profileRequestIdRef = useRef(0)
+ const profileSessionsRequestIdRef = useRef(0)
const skipNextProfilesAutoLoadRef = useRef(false)
const isMountedRef = useRef(true)
@@ -67,53 +89,36 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
return
}
- const requestId = profilesRequestIdRef.current
+ const requestId = ++profilesRequestIdRef.current
setProfilesLoading(true)
try {
const skip = typeof forcedSkip === 'number' ? forcedSkip : profilesSkip
- let dataProfiles: { profiles: Profile[] }
- let from
- let to
+ let from = ''
+ let to = ''
if (dateRange) {
from = getFormatDate(dateRange[0])
to = getFormatDate(dateRange[1])
}
- if (period === 'custom' && dateRange) {
- dataProfiles = await getProfiles(
- id,
- '',
- filters,
- from,
- to,
- SESSIONS_TAKE,
- skip,
- timezone,
- profileTypeFilter,
- projectPassword,
- )
- } else {
- dataProfiles = await getProfiles(
- id,
- period,
- filters,
- '',
- '',
- SESSIONS_TAKE,
- skip,
- timezone,
- profileTypeFilter,
- projectPassword,
- )
- }
+ const dataProfiles = await profilesProxy.fetchProfiles(id, {
+ period: period === 'custom' && dateRange ? '' : period,
+ filters,
+ from: period === 'custom' && dateRange ? from : '',
+ to: period === 'custom' && dateRange ? to : '',
+ take: SESSIONS_TAKE,
+ skip,
+ timezone,
+ profileType: profileTypeFilter,
+ })
if (requestId === profilesRequestIdRef.current && isMountedRef.current) {
+ const profilesList = (dataProfiles?.profiles || []).map(mapApiProfileToUI)
if (override) {
- setProfiles(dataProfiles?.profiles || [])
+ setProfiles(profilesList)
} else {
- setProfiles((prev) => [...prev, ...(dataProfiles?.profiles || [])])
+ setProfiles((prev) => [...prev, ...profilesList])
}
setProfilesSkip((prev) => {
if (typeof forcedSkip === 'number') {
@@ -122,7 +127,7 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
return SESSIONS_TAKE + prev
})
- if (dataProfiles?.profiles?.length < SESSIONS_TAKE) {
+ if (!dataProfiles?.profiles || dataProfiles.profiles.length < SESSIONS_TAKE) {
setCanLoadMoreProfiles(false)
} else {
setCanLoadMoreProfiles(true)
@@ -138,6 +143,7 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
}
const loadProfile = async (profileId: string) => {
+ const requestId = ++profileRequestIdRef.current
const hasExistingProfileData = !!activeProfile && activeProfile.profileId === profileId
setProfileLoading(true)
@@ -150,36 +156,33 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
}
try {
- let from
- let to
+ let from = ''
+ let to = ''
- if (dateRange) {
+ if (period === 'custom' && dateRange) {
from = getFormatDate(dateRange[0])
to = getFormatDate(dateRange[1])
}
- const data = await getProfile(
- id,
- profileId,
- period === 'custom' ? '' : period,
- from || '',
- to || '',
+ const data = await profileProxy.fetchProfile(id, profileId, {
+ period: period === 'custom' && dateRange ? '' : period,
+ from,
+ to,
timezone,
- projectPassword,
- )
+ })
- if (isMountedRef.current) {
- setActiveProfile(data)
+ if (requestId === profileRequestIdRef.current && isMountedRef.current && data) {
+ setActiveProfile(data as unknown as ProfileDetailsType)
// Load initial sessions for the profile (override existing on refresh)
loadProfileSessionsData(profileId, 0, true)
}
} catch (reason) {
console.error('[ERROR](loadProfile) Loading profile data failed:', reason)
- if (isMountedRef.current) {
+ if (requestId === profileRequestIdRef.current && isMountedRef.current) {
setActiveProfile(null)
}
} finally {
- if (isMountedRef.current) {
+ if (requestId === profileRequestIdRef.current && isMountedRef.current) {
setProfileLoading(false)
}
}
@@ -190,52 +193,35 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
return
}
+ const requestId = ++profileSessionsRequestIdRef.current
setProfileSessionsLoading(true)
try {
const skip = typeof forcedSkip === 'number' ? forcedSkip : profileSessionsSkip
- let dataSessions: { sessions: Session[] }
- let from
- let to
+ let from = ''
+ let to = ''
- if (dateRange) {
+ if (period === 'custom' && dateRange) {
from = getFormatDate(dateRange[0])
to = getFormatDate(dateRange[1])
}
- if (period === 'custom' && dateRange) {
- dataSessions = await getProfileSessions(
- id,
- profileId,
- '',
- filters,
- from,
- to,
- SESSIONS_TAKE,
- skip,
- timezone,
- projectPassword,
- )
- } else {
- dataSessions = await getProfileSessions(
- id,
- profileId,
- period,
- filters,
- '',
- '',
- SESSIONS_TAKE,
- skip,
- timezone,
- projectPassword,
- )
- }
+ const dataSessions = await profileSessionsProxy.fetchProfileSessions(id, profileId, {
+ period: period === 'custom' && dateRange ? '' : period,
+ filters,
+ from,
+ to,
+ take: SESSIONS_TAKE,
+ skip,
+ timezone,
+ })
- if (isMountedRef.current) {
+ if (requestId === profileSessionsRequestIdRef.current && isMountedRef.current) {
+ const sessionsList = (dataSessions?.sessions || []) as unknown as Session[]
if (override) {
- setProfileSessions(dataSessions?.sessions || [])
+ setProfileSessions(sessionsList)
} else {
- setProfileSessions((prev) => [...prev, ...(dataSessions?.sessions || [])])
+ setProfileSessions((prev) => [...prev, ...sessionsList])
}
setProfileSessionsSkip((prev) => {
if (typeof forcedSkip === 'number') {
@@ -244,7 +230,7 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
return SESSIONS_TAKE + prev
})
- if (dataSessions?.sessions?.length < SESSIONS_TAKE) {
+ if (!dataSessions?.sessions || dataSessions.sessions.length < SESSIONS_TAKE) {
setCanLoadMoreProfileSessions(false)
} else {
setCanLoadMoreProfileSessions(true)
@@ -253,7 +239,7 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
} catch (reason) {
console.error('[ERROR](loadProfileSessions) Loading profile sessions failed:', reason)
} finally {
- if (isMountedRef.current) {
+ if (requestId === profileSessionsRequestIdRef.current && isMountedRef.current) {
setProfileSessionsLoading(false)
}
}
diff --git a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx b/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
index 6e46c559a..abc317e3d 100644
--- a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
+++ b/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
@@ -1,26 +1,63 @@
import cx from 'clsx'
import _isEmpty from 'lodash/isEmpty'
import { DownloadIcon } from 'lucide-react'
-import { useState, useEffect, useMemo, useRef } from 'react'
+import { Component, useState, useEffect, useMemo, useRef, Suspense, use } from 'react'
+import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSearchParams } from 'react-router'
+import { useSearchParams, useLoaderData, useRevalidator } from 'react-router'
-import { getSessions, getSession } from '~/api'
+import type { SessionsResponse, SessionDetailsResponse } from '~/api/api.server'
+import { useSessionsProxy } from '~/hooks/useAnalyticsProxy'
import { Session, SessionDetails as SessionDetailsType } from '~/lib/models/Project'
import NoSessions from '~/pages/Project/tabs/Sessions/components/NoSessions'
import { SessionDetailView } from '~/pages/Project/tabs/Sessions/SessionDetailView'
import { Sessions } from '~/pages/Project/tabs/Sessions/Sessions'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
import Filters from '~/pages/Project/View/components/Filters'
-import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'
-import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+import type { ProjectLoaderData } from '~/routes/projects.$id'
import Spin from '~/ui/icons/Spin'
import Loader from '~/ui/Loader'
import LoadingBar from '~/ui/LoadingBar'
import StatusPage from '~/ui/StatusPage'
import routes from '~/utils/routes'
+interface SessionsErrorBoundaryState {
+ hasError: boolean
+ error: Error | null
+}
+
+class SessionsErrorBoundary extends Component<{ children: ReactNode }, SessionsErrorBoundaryState> {
+ constructor(props: { children: ReactNode }) {
+ super(props)
+ this.state = { hasError: false, error: null }
+ }
+
+ static getDerivedStateFromError(error: Error): SessionsErrorBoundaryState {
+ return { hasError: true, error }
+ }
+
+ render() {
+ if (this.state.hasError) {
+ return (
+ <StatusPage
+ type='error'
+ title='Failed to load sessions'
+ description={this.state.error?.message || 'An unexpected error occurred'}
+ actions={[
+ { label: 'Reload page', onClick: () => window.location.reload(), primary: true },
+ { label: 'Support', to: routes.contact },
+ ]}
+ />
+ )
+ }
+
+ return this.props.children
+ }
+}
+
const SESSIONS_TAKE = 30
interface PageflowItem {
@@ -47,29 +84,101 @@ interface SessionsViewProps {
rotateXAxis: boolean
}
-const SessionsView = ({ tnMapping, rotateXAxis }: SessionsViewProps) => {
+interface DeferredSessionsData {
+ sessionsData: SessionsResponse | null
+ sessionDetails: SessionDetailsResponse | null
+}
+
+function SessionsDataResolver({ children }: { children: (data: DeferredSessionsData) => React.ReactNode }) {
+ const { sessionsData: sessionsDataPromise, sessionDetails: sessionDetailsPromise } =
+ useLoaderData<ProjectLoaderData>()
+
+ const sessionsData = sessionsDataPromise ? use(sessionsDataPromise) : null
+ const sessionDetails = sessionDetailsPromise ? use(sessionDetailsPromise) : null
+
+ return <>{children({ sessionsData, sessionDetails })}</>
+}
+
+function SessionsViewWrapper(props: SessionsViewProps) {
+ return (
+ <SessionsErrorBoundary>
+ <Suspense fallback={<Loader />}>
+ <SessionsDataResolver>
+ {(deferredData) => <SessionsViewInner {...props} deferredData={deferredData} />}
+ </SessionsDataResolver>
+ </Suspense>
+ </SessionsErrorBoundary>
+ )
+}
+
+interface SessionsViewInnerProps extends SessionsViewProps {
+ deferredData: DeferredSessionsData
+}
+
+const SessionsViewInner = ({ tnMapping, rotateXAxis, deferredData }: SessionsViewInnerProps) => {
const { id, project } = useCurrentProject()
- const projectPassword = useProjectPassword(id)
- const { sessionsRefreshTrigger, timezone, period, dateRange, filters, timeFormat } = useViewProjectContext()
+ const revalidator = useRevalidator()
+ const { sessionsRefreshTrigger } = useRefreshTriggers()
+ const { timezone, period, dateRange, filters, timeFormat } = useViewProjectContext()
const { t } = useTranslation('common')
const [searchParams] = useSearchParams()
- // Session list state
- const [sessions, setSessions] = useState<Session[]>([])
- const [sessionsLoading, setSessionsLoading] = useState<boolean | null>(null)
- const [sessionsSkip, setSessionsSkip] = useState(0)
- const [canLoadMoreSessions, setCanLoadMoreSessions] = useState(false)
- const sessionsRequestIdRef = useRef(0)
+ // Proxy for pagination
+ const sessionsProxy = useSessionsProxy()
- // Session detail state
- const [activeSession, setActiveSession] = useState<ActiveSession | null>(null)
- const [sessionLoading, setSessionLoading] = useState(false)
+ // Session list state - derived from loader
+ const [sessions, setSessions] = useState<Session[]>(() => deferredData.sessionsData?.sessions || [])
+ const [sessionsSkip, setSessionsSkip] = useState(SESSIONS_TAKE)
+ const [canLoadMoreSessions, setCanLoadMoreSessions] = useState(
+ () => (deferredData.sessionsData?.sessions?.length || 0) >= SESSIONS_TAKE,
+ )
+
+ // Session detail - derived from loader when available
+ const activeSession: ActiveSession | null = useMemo(() => {
+ if (deferredData.sessionDetails) {
+ const apiDetails = deferredData.sessionDetails.details
+ const details: SessionDetailsType = {
+ cc: apiDetails.cc,
+ os: apiDetails.os,
+ osv: null,
+ br: apiDetails.br,
+ brv: null,
+ lc: null,
+ ref: null,
+ so: null,
+ me: null,
+ ca: null,
+ te: null,
+ co: null,
+ rg: null,
+ ct: null,
+ dv: apiDetails.dv,
+ profileId: apiDetails.profileId,
+ sdur: apiDetails.sdur,
+ isLive: false,
+ }
+ return {
+ details,
+ chart: deferredData.sessionDetails.chart,
+ pages: deferredData.sessionDetails.pages,
+ timeBucket: deferredData.sessionDetails.timeBucket,
+ }
+ }
+ return null
+ }, [deferredData.sessionDetails])
+
+ const sessionsLoading = revalidator.state === 'loading' || sessionsProxy.isLoading
const [error, setError] = useState<string | null>(null)
const isMountedRef = useRef(true)
- const prevActivePSIDRef = useRef<string | null>(null)
- const skipNextSessionsAutoLoadRef = useRef(false)
+
+ // Track when loader data was last applied to detect stale proxy responses
+ const loaderUpdateCounterRef = useRef(0)
+ const proxyRequestCounterRef = useRef(0)
+
+ // Track if we've shown content in the current data set to prevent NoSessions flash during exit animation
+ const hasShownContentRef = useRef(false)
const activePSID = useMemo(() => {
return searchParams.get('psid')
@@ -99,143 +208,88 @@ const SessionsView = ({ tnMapping, rotateXAxis }: SessionsViewProps) => {
}
}, [])
- // Reset sessions when filters change
+ // Sync sessions state when loader provides new data
useEffect(() => {
- sessionsRequestIdRef.current += 1
- setSessionsSkip(0)
- setSessions([])
- setSessionsLoading(null)
- }, [filters])
-
- const loadSessions = async (forcedSkip?: number, override?: boolean) => {
- if (sessionsLoading) {
- return
- }
-
- const requestId = sessionsRequestIdRef.current
- setSessionsLoading(true)
-
- try {
- const skip = typeof forcedSkip === 'number' ? forcedSkip : sessionsSkip
- let dataSessions: { sessions: Session[] }
- let from
- let to
-
- if (dateRange) {
- from = getFormatDate(dateRange[0])
- to = getFormatDate(dateRange[1])
- }
-
- if (period === 'custom' && dateRange) {
- dataSessions = await getSessions(id, '', filters, from, to, SESSIONS_TAKE, skip, timezone, projectPassword)
+ if (deferredData.sessionsData && revalidator.state === 'idle') {
+ const sessionsList = deferredData.sessionsData.sessions || []
+ setSessions(sessionsList)
+ setSessionsSkip(SESSIONS_TAKE)
+ setCanLoadMoreSessions(sessionsList.length >= SESSIONS_TAKE)
+ // Increment counter to invalidate any in-flight proxy responses
+ loaderUpdateCounterRef.current += 1
+ // Reset content tracking when loader provides empty results (e.g., after filter change)
+ if (_isEmpty(sessionsList)) {
+ hasShownContentRef.current = false
} else {
- dataSessions = await getSessions(id, period, filters, '', '', SESSIONS_TAKE, skip, timezone, projectPassword)
- }
-
- if (requestId === sessionsRequestIdRef.current && isMountedRef.current) {
- if (override) {
- setSessions(dataSessions?.sessions || [])
- } else {
- setSessions((prev) => [...prev, ...(dataSessions?.sessions || [])])
- }
- setSessionsSkip((prev) => {
- if (typeof forcedSkip === 'number') {
- return SESSIONS_TAKE + forcedSkip
- }
-
- return SESSIONS_TAKE + prev
- })
-
- if (dataSessions?.sessions?.length < SESSIONS_TAKE) {
- setCanLoadMoreSessions(false)
- } else {
- setCanLoadMoreSessions(true)
- }
- }
- } catch (reason: any) {
- console.error('[ERROR](loadSessions) Loading sessions data failed:', reason)
- if (isMountedRef.current) {
- setError(reason?.message || reason?.toString() || 'Unknown error')
+ hasShownContentRef.current = true
}
- } finally {
- if (requestId === sessionsRequestIdRef.current && isMountedRef.current) {
- setSessionsLoading(false)
- }
- }
- }
-
- const loadSession = async (psid: string) => {
- if (sessionLoading) {
- return
}
+ }, [revalidator.state, deferredData.sessionsData])
- setSessionLoading(true)
+ // Handle proxy response for pagination
+ useEffect(() => {
+ if (revalidator.state === 'loading') return
- try {
- const session = await getSession(id, psid, timezone, projectPassword)
- if (isMountedRef.current) {
- setActiveSession(session)
- }
- } catch (reason: any) {
- console.error('[ERROR] (loadSession)(getSession)', reason)
- if (isMountedRef.current) {
- setError(reason?.message || reason?.toString() || 'Unknown error')
+ if (sessionsProxy.data && !sessionsProxy.isLoading) {
+ // Ignore stale proxy responses that were initiated before the last loader update
+ if (proxyRequestCounterRef.current < loaderUpdateCounterRef.current) {
+ return
}
- } finally {
- if (isMountedRef.current) {
- setSessionLoading(false)
- }
- }
- }
- // Handle session detail loading
- useEffect(() => {
- if (!activePSID) {
- setActiveSession(null)
- // Coming back from a session detail to the list: reset pagination and reload first page
- if (prevActivePSIDRef.current) {
- skipNextSessionsAutoLoadRef.current = true
- setSessionsSkip(0)
- loadSessions(0, true)
- }
- prevActivePSIDRef.current = null
- return
+ const newSessions = sessionsProxy.data.sessions || []
+ setSessions((prev) => {
+ // Deduplicate: only add sessions whose psid is not already present
+ const existingIds = new Set(prev.map((s) => s.psid))
+ const uniqueNewSessions = newSessions.filter((s) => !existingIds.has(s.psid))
+ return [...prev, ...uniqueNewSessions]
+ })
+ setSessionsSkip((prev) => prev + SESSIONS_TAKE)
+ setCanLoadMoreSessions(newSessions.length >= SESSIONS_TAKE)
+ }
+ if (sessionsProxy.error) {
+ setError(sessionsProxy.error)
}
+ }, [sessionsProxy.data, sessionsProxy.error, sessionsProxy.isLoading, revalidator.state])
- loadSession(activePSID)
- prevActivePSIDRef.current = activePSID
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [period, dateRange, activePSID])
+ // Load more sessions via proxy
+ const loadMoreSessions = () => {
+ if (sessionsLoading) return
- // Load sessions list
- useEffect(() => {
- if (!project || activePSID) {
- return
- }
+ let from: string | undefined
+ let to: string | undefined
- if (skipNextSessionsAutoLoadRef.current) {
- skipNextSessionsAutoLoadRef.current = false
- return
+ if (dateRange) {
+ from = getFormatDate(dateRange[0])
+ to = getFormatDate(dateRange[1])
}
- loadSessions()
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [dateRange, filters, id, period, timezone, project, activePSID])
+ // Track when this proxy request was initiated relative to loader updates
+ proxyRequestCounterRef.current = loaderUpdateCounterRef.current
+
+ sessionsProxy.fetchSessions(id, {
+ timeBucket: 'day',
+ period: period === 'custom' ? '' : period,
+ from,
+ to,
+ timezone,
+ filters,
+ take: SESSIONS_TAKE,
+ skip: sessionsSkip,
+ })
+ }
- // Handle refresh trigger
+ // Handle refresh trigger - use revalidator for URL-based data
useEffect(() => {
if (sessionsRefreshTrigger > 0) {
- if (activePSID) {
- loadSession(activePSID)
- } else {
- setSessionsSkip(0)
- loadSessions(0, true)
- }
+ revalidator.revalidate()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sessionsRefreshTrigger])
- if (error && sessionsLoading === false) {
+ // Session detail loading state
+ const sessionLoading = activePSID ? revalidator.state === 'loading' : false
+
+ if (error && !sessionsLoading) {
return (
<StatusPage
type='error'
@@ -277,8 +331,8 @@ const SessionsView = ({ tnMapping, rotateXAxis }: SessionsViewProps) => {
{sessionsLoading && !_isEmpty(sessions) ? <LoadingBar /> : null}
<div>
{!_isEmpty(sessions) ? <Filters className='mb-3' tnMapping={tnMapping} /> : null}
- {(sessionsLoading === null || sessionsLoading) && _isEmpty(sessions) ? <Loader /> : null}
- {typeof sessionsLoading === 'boolean' && !sessionsLoading && _isEmpty(sessions) ? (
+ {sessionsLoading && _isEmpty(sessions) ? <Loader /> : null}
+ {!sessionsLoading && _isEmpty(sessions) && !hasShownContentRef.current ? (
<NoSessions filters={filters} />
) : null}
<Sessions sessions={sessions} timeFormat={timeFormat} currency={project?.revenueCurrency} />
@@ -286,11 +340,11 @@ const SessionsView = ({ tnMapping, rotateXAxis }: SessionsViewProps) => {
<button
type='button'
title={t('project.loadMore')}
- onClick={() => loadSessions()}
+ onClick={loadMoreSessions}
className={cx(
'relative mx-auto mt-2 flex items-center rounded-md border border-transparent p-2 text-sm font-medium text-gray-700 ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:bg-slate-900 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
{
- 'cursor-not-allowed opacity-50': sessionsLoading || sessionsLoading === null,
+ 'cursor-not-allowed opacity-50': sessionsLoading,
hidden: sessionsLoading && _isEmpty(sessions),
},
)}
@@ -308,4 +362,6 @@ const SessionsView = ({ tnMapping, rotateXAxis }: SessionsViewProps) => {
)
}
+const SessionsView = SessionsViewWrapper
+
export default SessionsView
diff --git a/web/app/pages/Project/tabs/Traffic/TrafficHeaderActions.tsx b/web/app/pages/Project/tabs/Traffic/TrafficHeaderActions.tsx
index 493b972b3..35408264c 100644
--- a/web/app/pages/Project/tabs/Traffic/TrafficHeaderActions.tsx
+++ b/web/app/pages/Project/tabs/Traffic/TrafficHeaderActions.tsx
@@ -2,10 +2,12 @@ import cx from 'clsx'
import _filter from 'lodash/filter'
import _isEmpty from 'lodash/isEmpty'
import { BookmarkIcon, DownloadIcon, PencilIcon, Trash2Icon } from 'lucide-react'
-import React from 'react'
+import React, { useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { useSearchParams } from 'react-router'
+import { useSearchParams, useFetcher } from 'react-router'
+import { toast } from 'sonner'
+import { ProjectViewActionData } from '~/routes/projects.$id'
import Dropdown from '~/ui/Dropdown'
import { Text } from '~/ui/Text'
import { trackCustom } from '~/utils/analytics'
@@ -22,9 +24,7 @@ interface TrafficHeaderActionsProps {
// Segments dropdown props
projectViews: ProjectView[]
projectViewsLoading: boolean | null
- projectViewDeleting: boolean
- loadProjectViews: () => Promise<void>
- onProjectViewDelete: (viewId: string) => Promise<void>
+ loadProjectViews: (forced?: boolean) => void
setProjectViewToUpdate: (view: ProjectView | undefined) => void
setIsAddAViewOpened: (value: boolean) => void
onCustomMetric: (metrics: ProjectViewCustomEvent[]) => void
@@ -40,9 +40,7 @@ interface TrafficHeaderActionsProps {
const TrafficHeaderActions = ({
projectViews,
projectViewsLoading,
- projectViewDeleting,
loadProjectViews,
- onProjectViewDelete,
setProjectViewToUpdate,
setIsAddAViewOpened,
onCustomMetric,
@@ -53,6 +51,31 @@ const TrafficHeaderActions = ({
}: TrafficHeaderActionsProps) => {
const { t } = useTranslation('common')
const [searchParams, setSearchParams] = useSearchParams()
+ const deleteFetcher = useFetcher<ProjectViewActionData>()
+ const isDeleting = deleteFetcher.state !== 'idle'
+ const hasHandledDelete = useRef(false)
+
+ useEffect(() => {
+ if (deleteFetcher.state === 'submitting') {
+ hasHandledDelete.current = false
+ }
+ }, [deleteFetcher.state])
+
+ useEffect(() => {
+ if (
+ deleteFetcher.state === 'idle' &&
+ deleteFetcher.data?.intent === 'delete-project-view' &&
+ !hasHandledDelete.current
+ ) {
+ hasHandledDelete.current = true
+ if (deleteFetcher.data.success) {
+ toast.success(t('apiNotifications.segmentDeleted'))
+ loadProjectViews(true)
+ } else if (deleteFetcher.data.error) {
+ toast.error(deleteFetcher.data.error)
+ }
+ }
+ }, [deleteFetcher.state, deleteFetcher.data, loadProjectViews, t])
return (
<>
@@ -110,22 +133,27 @@ const TrafficHeaderActions = ({
>
<PencilIcon className='size-3' />
</button>
- <button
- onClick={(e) => {
- e.stopPropagation()
- close()
- onProjectViewDelete(item.id)
- }}
- aria-label={t('common.settings')}
- className={cx(
- 'rounded-md p-1 hover:bg-gray-50 hover:text-gray-900 dark:hover:bg-slate-800 dark:hover:text-slate-200',
- {
- 'cursor-not-allowed': projectViewDeleting,
- },
- )}
- >
- <Trash2Icon className='size-3' />
- </button>
+ <deleteFetcher.Form method='post' className='inline'>
+ <input type='hidden' name='intent' value='delete-project-view' />
+ <input type='hidden' name='viewId' value={item.id} />
+ <button
+ type='submit'
+ onClick={(e) => {
+ e.stopPropagation()
+ close()
+ }}
+ disabled={isDeleting}
+ aria-label={t('common.delete')}
+ className={cx(
+ 'rounded-md p-1 hover:bg-gray-50 hover:text-gray-900 dark:hover:bg-slate-800 dark:hover:text-slate-200',
+ {
+ 'cursor-not-allowed opacity-50': isDeleting,
+ },
+ )}
+ >
+ <Trash2Icon className='size-3' />
+ </button>
+ </deleteFetcher.Form>
</div>
) : null}
</div>
diff --git a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
index cf8369ae2..cac8cac8e 100644
--- a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
+++ b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
@@ -1,32 +1,40 @@
import cx from 'clsx'
-import dayjs from 'dayjs'
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 _some from 'lodash/some'
import { BanIcon, ChartColumnBigIcon, ChartLineIcon, EyeIcon } from 'lucide-react'
-import React, { useState, useEffect, useMemo, useRef, lazy, Suspense, useCallback } from 'react'
+import React, {
+ useState,
+ useEffect,
+ useMemo,
+ useRef,
+ lazy,
+ Suspense,
+ useCallback,
+ use,
+ Component,
+ type ReactNode,
+} from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
-import { useNavigate, Link, useSearchParams } from 'react-router'
+import { useNavigate, Link, useSearchParams, useLoaderData, useRevalidator } from 'react-router'
import { toast } from 'sonner'
+import type {
+ TrafficLogResponse as ServerTrafficLogResponse,
+ OverallObject as ServerOverallObject,
+} from '~/api/api.server'
import {
- getProjectData,
- getOverallStats,
- getProjectDataCustomEvents,
- getTrafficCompareData,
- getCustomEventsMetadata,
- getPropertyMetadata,
- getGSCKeywords,
- getRevenueData,
- getRevenueStatus,
-} from '~/api'
+ useCustomEventsMetadataProxy,
+ usePropertyMetadataProxy,
+ useGSCKeywordsProxy,
+ useRevenueProxy,
+} from '~/hooks/useAnalyticsProxy'
import { useAnnotations } from '~/hooks/useAnnotations'
-import { TRAFFIC_PANELS_ORDER, chartTypes, PERIOD_PAIRS_COMPARE, isSelfhosted, type TimeBucket } from '~/lib/constants'
+import { TRAFFIC_PANELS_ORDER, chartTypes, isSelfhosted } from '~/lib/constants'
import { CountryEntry, Entry } from '~/lib/models/Entry'
import { OverallObject } from '~/lib/models/Project'
import AnnotationModal from '~/modals/AnnotationModal'
@@ -51,11 +59,10 @@ import {
ProjectView,
ProjectViewCustomEvent,
Properties,
- TrafficLogResponse,
} from '~/pages/Project/View/interfaces/traffic'
import { Panel, CustomEvents, MetadataKeyPanel } from '~/pages/Project/View/Panels'
import { FILTER_CHART_METRICS_MAPPING_FOR_COMPARE } from '~/pages/Project/View/utils/filters'
-import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
+import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
import {
getFormatDate,
panelIconMapping,
@@ -64,13 +71,13 @@ import {
getDeviceRowMapper,
onCSVExportClick,
} from '~/pages/Project/View/ViewProject.helpers'
-import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
+import type { ProjectLoaderData } from '~/routes/projects.$id'
import Checkbox from '~/ui/Checkbox'
import Dropdown from '~/ui/Dropdown'
import Loader from '~/ui/Loader'
import LoadingBar from '~/ui/LoadingBar'
-import { periodToCompareDate } from '~/utils/compareConvertDate'
import { getLocaleDisplayName, nLocaleFormatter } from '~/utils/generic'
import { groupRefEntries } from '~/utils/referrers'
import routes from '~/utils/routes'
@@ -96,33 +103,116 @@ interface TrafficViewProps {
// Segment/View props
projectViews: ProjectView[]
projectViewsLoading: boolean | null
- projectViewDeleting: boolean
- loadProjectViews: () => Promise<void>
- onProjectViewDelete: (viewId: string) => Promise<void>
+ loadProjectViews: (forced?: boolean) => void
setProjectViewToUpdate: (view: ProjectView | undefined) => void
setIsAddAViewOpened: (value: boolean) => void
onCustomMetric: (metrics: ProjectViewCustomEvent[]) => void
}
-const TrafficView = ({
+interface DeferredTrafficData {
+ trafficData: ServerTrafficLogResponse | null
+ overallStats: Record<string, ServerOverallObject> | null
+ trafficCompareData: ServerTrafficLogResponse | null
+ overallCompareStats: Record<string, ServerOverallObject> | null
+ customEventsData: { chart?: { events?: Record<string, unknown> } } | null
+}
+
+interface TrafficErrorBoundaryState {
+ hasError: boolean
+ error: Error | null
+}
+
+class TrafficErrorBoundary extends Component<{ children: ReactNode }, TrafficErrorBoundaryState> {
+ constructor(props: { children: ReactNode }) {
+ super(props)
+ this.state = { hasError: false, error: null }
+ }
+
+ static getDerivedStateFromError(error: Error): TrafficErrorBoundaryState {
+ return { hasError: true, error }
+ }
+
+ render() {
+ if (this.state.hasError) {
+ return (
+ <div className='flex min-h-[300px] flex-col items-center justify-center rounded-lg border border-red-200 bg-red-50 p-8 dark:border-red-800/50 dark:bg-red-900/20'>
+ <p className='text-center text-lg font-semibold text-red-600 dark:text-red-400'>
+ Failed to load traffic data
+ </p>
+ <p className='mt-2 text-center text-sm text-red-500 dark:text-red-300'>
+ {this.state.error?.message || 'An unexpected error occurred. Please try again.'}
+ </p>
+ <button
+ type='button'
+ onClick={() => window.location.reload()}
+ className='mt-4 rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700 focus:ring-2 focus:ring-red-500 focus:ring-offset-2 focus:outline-hidden'
+ >
+ Reload page
+ </button>
+ </div>
+ )
+ }
+
+ return this.props.children
+ }
+}
+
+function TrafficDataResolver({ children }: { children: (data: DeferredTrafficData) => React.ReactNode }) {
+ const {
+ trafficData: trafficDataPromise,
+ overallStats: overallStatsPromise,
+ trafficCompareData: trafficComparePromise,
+ overallCompareStats: overallComparePromise,
+ customEventsData: customEventsPromise,
+ } = useLoaderData<ProjectLoaderData>()
+
+ const trafficData = trafficDataPromise ? use(trafficDataPromise) : null
+ const overallStats = overallStatsPromise ? use(overallStatsPromise) : null
+ const trafficCompareData = trafficComparePromise ? use(trafficComparePromise) : null
+ const overallCompareStats = overallComparePromise ? use(overallComparePromise) : null
+ const customEventsData = customEventsPromise ? use(customEventsPromise) : null
+
+ return <>{children({ trafficData, overallStats, trafficCompareData, overallCompareStats, customEventsData })}</>
+}
+
+function TrafficViewWrapper(props: TrafficViewProps) {
+ return (
+ <TrafficErrorBoundary>
+ <Suspense fallback={<Loader />}>
+ <TrafficDataResolver>
+ {(deferredData) => <TrafficViewInner {...props} deferredData={deferredData} />}
+ </TrafficDataResolver>
+ </Suspense>
+ </TrafficErrorBoundary>
+ )
+}
+
+interface TrafficViewInnerProps extends TrafficViewProps {
+ deferredData: DeferredTrafficData
+}
+
+const TrafficViewInner = ({
tnMapping,
customMetrics,
onRemoveCustomMetric,
resetCustomMetrics,
- mode,
+ mode: _mode,
projectViews,
projectViewsLoading,
- projectViewDeleting,
loadProjectViews,
- onProjectViewDelete,
setProjectViewToUpdate,
setIsAddAViewOpened,
onCustomMetric,
-}: TrafficViewProps) => {
+ deferredData,
+}: TrafficViewInnerProps) => {
const { id, project, allowedToManage } = useCurrentProject()
- const projectPassword = useProjectPassword(id)
+ const revalidator = useRevalidator()
+ const { fetchMetadata: fetchCustomEventsMetadata } = useCustomEventsMetadataProxy()
+ const { fetchMetadata: fetchPropertyMetadata } = usePropertyMetadataProxy()
+ const { fetchKeywords: fetchGSCKeywords } = useGSCKeywordsProxy()
+ const { fetchRevenueStatus, fetchRevenueData } = useRevenueProxy()
+ const { trafficRefreshTrigger } = useRefreshTriggers()
const {
- trafficRefreshTrigger,
timezone,
period,
dateRange,
@@ -132,9 +222,7 @@ const TrafficView = ({
activePeriod,
// Comparison state from context
isActiveCompare,
- dateRangeCompare,
activePeriodCompare,
- compareDisable,
// Chart state from context
chartType,
setChartTypeOnClick,
@@ -156,7 +244,9 @@ const TrafficView = ({
const { theme } = useTheme()
const navigate = useNavigate()
const [searchParams, setSearchParams] = useSearchParams()
- const isEmbedded = searchParams.get('embedded') === 'true'
+
+ // Track if we've ever shown actual content to prevent NoEvents flash during exit animation
+ const hasShownContentRef = useRef(false)
// Annotations hook
const {
@@ -175,17 +265,73 @@ const TrafficView = ({
closeContextMenu,
} = useAnnotations()
- // Traffic-specific state
- const [dataLoading, setDataLoading] = useState(false)
- const [analyticsLoading, setAnalyticsLoading] = useState(true)
- const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)
- const [panelsData, setPanelsData] = useState<PanelsData>({ data: {} })
- const [chartData, setChartData] = useState<any>({})
- const [overall, setOverall] = useState<Partial<OverallObject>>({})
- const [overallCompare, setOverallCompare] = useState<Partial<OverallObject>>({})
- const [dataChartCompare, setDataChartCompare] = useState<any>({})
- const [customEventsChartData, setCustomEventsChartData] = useState<any>({})
+ const panelsData: PanelsData = useMemo(() => {
+ if (deferredData.trafficData) {
+ return {
+ types: _keys(deferredData.trafficData.params || {}),
+ data: deferredData.trafficData.params || {},
+ customs: deferredData.trafficData.customs,
+ properties: deferredData.trafficData.properties,
+ meta: deferredData.trafficData.meta,
+ }
+ }
+ return { data: {} }
+ }, [deferredData.trafficData])
+
+ const baseChartData = useMemo(() => deferredData.trafficData?.chart || {}, [deferredData.trafficData])
+
+ const overall: Partial<OverallObject> = useMemo(() => {
+ if (deferredData.overallStats && id) {
+ return deferredData.overallStats[id] || {}
+ }
+ return {}
+ }, [deferredData.overallStats, id])
+
+ const dataLoading = revalidator.state === 'loading'
+
+ // Derive compare data from loader
+ const overallCompare: Partial<OverallObject> = useMemo(() => {
+ if (deferredData.overallCompareStats && id) {
+ return deferredData.overallCompareStats[id] || {}
+ }
+ return {}
+ }, [deferredData.overallCompareStats, id])
+
+ const dataChartCompare = useMemo(
+ () => deferredData.trafficCompareData?.chart || {},
+ [deferredData.trafficCompareData],
+ )
+
+ // Derive custom events data from loader
+ const customEventsChartData = useMemo(
+ () => (deferredData.customEventsData?.chart?.events || {}) as Record<string, string[]>,
+ [deferredData.customEventsData],
+ )
+
+ // Revenue state (still fetched client-side for now)
const [isRevenueConnected, setIsRevenueConnected] = useState(false)
+ const [revenueOverlay, setRevenueOverlay] = useState<{ revenue: number[]; refundsAmount: number[] } | null>(null)
+
+ // Merge base chart with revenue data
+ const chartData = useMemo(() => {
+ if (revenueOverlay) {
+ return { ...baseChartData, ...revenueOverlay }
+ }
+ return baseChartData
+ }, [baseChartData, revenueOverlay])
+
+ const isPanelsDataEmptyRaw = useMemo(
+ () => _isEmpty(panelsData.data) && _isEmpty(panelsData.customs),
+ [panelsData.data, panelsData.customs],
+ )
+
+ // Track when we've shown content to prevent NoEvents flash during exit animation
+ if (!isPanelsDataEmptyRaw) {
+ hasShownContentRef.current = true
+ }
+
+ // Don't show NoEvents if we've previously shown content (prevents flash during tab switch)
+ const isPanelsDataEmpty = isPanelsDataEmptyRaw && !hasShownContentRef.current
// Chart metrics state
const [activeChartMetrics, setActiveChartMetrics] = useState({
@@ -199,7 +345,11 @@ const TrafficView = ({
[CHART_METRICS_MAPPING.customEvents]: false,
[CHART_METRICS_MAPPING.revenue]: false,
})
- const [activeChartMetricsCustomEvents, setActiveChartMetricsCustomEvents] = useState<string[]>([])
+ // Get custom events from URL params (SSR-friendly)
+ const activeChartMetricsCustomEvents = useMemo(() => {
+ const param = searchParams.get('customEvents')
+ return param ? param.split(',').filter(Boolean) : []
+ }, [searchParams])
// Panel active tabs
const [panelsActiveTabs, setPanelsActiveTabs] = useState<{
@@ -235,14 +385,14 @@ const TrafficView = ({
// Fetch revenue status
useEffect(() => {
- const fetchRevenueStatus = async () => {
+ const loadRevenueStatus = async () => {
if (!id || isSelfhosted) {
return
}
try {
- const status = await getRevenueStatus(id)
- if (isMountedRef.current) {
+ const status = await fetchRevenueStatus(id)
+ if (isMountedRef.current && status) {
setIsRevenueConnected(status.connected)
}
} catch (error) {
@@ -250,8 +400,8 @@ const TrafficView = ({
}
}
- fetchRevenueStatus()
- }, [id])
+ loadRevenueStatus()
+ }, [id, fetchRevenueStatus])
// Version data mapping for browser/OS versions
const createVersionDataMapping = useMemo(() => {
@@ -411,14 +561,27 @@ const TrafficView = ({
[isConflicted, t],
)
- const switchCustomEventChart = useCallback((id: string) => {
- setActiveChartMetricsCustomEvents((prev) => {
- if (_includes(prev, id)) {
- return _filter(prev, (item) => item !== id)
+ const switchCustomEventChart = useCallback(
+ (eventId: string) => {
+ const newParams = new URLSearchParams(searchParams.toString())
+ const currentEvents = newParams.get('customEvents')?.split(',').filter(Boolean) || []
+
+ let newEvents: string[]
+ if (currentEvents.includes(eventId)) {
+ newEvents = currentEvents.filter((e) => e !== eventId)
+ } else {
+ newEvents = [...currentEvents, eventId]
}
- return [...prev, id]
- })
- }, [])
+
+ if (newEvents.length > 0) {
+ newParams.set('customEvents', newEvents.join(','))
+ } else {
+ newParams.delete('customEvents')
+ }
+ setSearchParams(newParams)
+ },
+ [searchParams, setSearchParams],
+ )
const setPanelTab = (panel: keyof typeof panelsActiveTabs, tab: string) => {
setPanelsActiveTabs((prev) => ({
@@ -427,314 +590,111 @@ const TrafficView = ({
}))
}
- const loadAnalytics = async () => {
- if (!project) return
+ // Load revenue data (the only remaining client-side fetch)
+ const loadRevenueData = useCallback(async () => {
+ if (!project || !activeChartMetrics.revenue || isSelfhosted || !isRevenueConnected) {
+ setRevenueOverlay(null)
+ return
+ }
- setDataLoading(true)
+ // Early return if base chart x-axis is not yet available
+ const chart = baseChartData as { x?: string[] }
+ if (!Array.isArray(chart?.x) || chart.x.length === 0) {
+ setRevenueOverlay(null)
+ return
+ }
try {
- let data: TrafficLogResponse & { overall?: OverallObject }
- let dataCompare: (TrafficLogResponse & { overall?: OverallObject }) | null = null
- let from
- let fromCompare: string | undefined
- let to
- let toCompare: string | undefined
- let customEventsChart = customEventsChartData
- let rawOverall: any
-
- if (isActiveCompare) {
- if (dateRangeCompare && activePeriodCompare === PERIOD_PAIRS_COMPARE.CUSTOM) {
- let start
- let end
- let diff
- const startCompare = dayjs.utc(dateRangeCompare[0])
- const endCompare = dayjs.utc(dateRangeCompare[1])
- const diffCompare = endCompare.diff(startCompare, 'day')
-
- if (activePeriod?.period === 'custom' && dateRange) {
- start = dayjs.utc(dateRange[0])
- end = dayjs.utc(dateRange[1])
- diff = end.diff(start, 'day')
- }
-
- // @ts-expect-error
- if (activePeriod?.period === 'custom' ? diffCompare <= diff : diffCompare <= activePeriod?.countDays) {
- fromCompare = getFormatDate(dateRangeCompare[0])
- toCompare = getFormatDate(dateRangeCompare[1])
- } else {
- toast.error(t('project.compareDateRangeError'))
- compareDisable()
- }
- } else {
- let date
- if (dateRange) {
- date = _find(periodToCompareDate, (item) => item.period === period)?.formula(dateRange)
- } else {
- date = _find(periodToCompareDate, (item) => item.period === period)?.formula()
- }
-
- if (date) {
- fromCompare = date.from
- toCompare = date.to
- }
- }
-
- if (!_isEmpty(fromCompare) && !_isEmpty(toCompare)) {
- dataCompare =
- (await getTrafficCompareData(
- id,
- timeBucket,
- '',
- filters,
- fromCompare,
- toCompare,
- timezone,
- projectPassword,
- mode,
- )) || {}
- const compareOverall = await getOverallStats(
- [id],
- timeBucket,
- 'custom',
- fromCompare,
- toCompare,
- timezone,
- filters,
- projectPassword,
- )
-
- // @ts-expect-error
- dataCompare.overall = compareOverall[id]
- }
- }
+ let from: string | undefined
+ let to: string | undefined
if (dateRange) {
from = getFormatDate(dateRange[0])
to = getFormatDate(dateRange[1])
}
- if (period === 'custom' && dateRange) {
- data = await getProjectData(
- id,
- timeBucket,
- '',
- filters,
- customMetrics,
- from,
- to,
- timezone,
- projectPassword,
- mode,
- )
- if (activeChartMetricsCustomEvents.length > 0) {
- customEventsChart = await getProjectDataCustomEvents(
- id,
- timeBucket,
- '',
- filters,
- from,
- to,
- timezone,
- activeChartMetricsCustomEvents,
- projectPassword,
- )
- }
- rawOverall = await getOverallStats([id], timeBucket, period, from, to, timezone, filters, projectPassword)
- } else {
- data = await getProjectData(
- id,
- timeBucket,
- period,
- filters,
- customMetrics,
- '',
- '',
- timezone,
- projectPassword,
- mode,
- )
- if (activeChartMetricsCustomEvents.length > 0) {
- customEventsChart = await getProjectDataCustomEvents(
- id,
- timeBucket,
- period,
- filters,
- '',
- '',
- timezone,
- activeChartMetricsCustomEvents,
- projectPassword,
- )
- }
- rawOverall = await getOverallStats([id], timeBucket, period, '', '', timezone, filters, projectPassword)
- }
-
- customEventsChart = customEventsChart?.chart ? customEventsChart.chart.events : customEventsChartData
-
- if (isMountedRef.current) {
- setCustomEventsChartData(customEventsChart)
- data.overall = rawOverall[id]
- setOverall(rawOverall[id])
-
- if (_keys(data).length < 2) {
- setAnalyticsLoading(false)
- setDataLoading(false)
- setIsPanelsDataEmpty(true)
- return
- }
-
- const { chart, params, customs, properties, meta } = data
- let newTimebucket = timeBucket
-
- if (period === 'all' && !_isEmpty(data.timeBucket)) {
- newTimebucket = _includes(data.timeBucket, timeBucket) ? timeBucket : (data.timeBucket?.[0] as TimeBucket)
-
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.set('timeBucket', newTimebucket)
- setSearchParams(newSearchParams)
- }
-
- if (!_isEmpty(dataCompare)) {
- if (!_isEmpty(dataCompare?.chart)) {
- setDataChartCompare(dataCompare.chart)
- }
-
- if (!_isEmpty(dataCompare?.overall)) {
- setOverallCompare(dataCompare.overall)
- }
- }
-
- if (_isEmpty(params)) {
- setIsPanelsDataEmpty(true)
+ const revResult = await fetchRevenueData(id, {
+ period: period === 'custom' ? 'custom' : period,
+ from,
+ to,
+ timezone,
+ timeBucket,
+ })
+ const revChart = revResult?.chart
+ const revX = revChart?.x || []
+ const revY = revChart?.revenue || []
+ const revRefunds = revChart?.refundsAmount || []
+
+ // Align revenue series to the main traffic chart x-axis
+ let revenueData: number[] = []
+ let refundsData: number[] = []
+
+ if (Array.isArray(revX) && revX.length > 0) {
+ if (revX.length === chart.x.length && revX[0] === chart.x[0]) {
+ revenueData = revY.map((v: any) => Number(v ?? 0))
+ refundsData = revRefunds.map((v: any) => Number(v ?? 0))
} else {
- // Fetch revenue data if revenue metric is enabled and not selfhosted
- let revenueData: number[] = []
- let refundsData: number[] = []
- if (activeChartMetrics.revenue && !isSelfhosted && isRevenueConnected) {
- try {
- const revResult = await getRevenueData(
- id,
- period === 'custom' ? 'custom' : period,
- period === 'custom' && dateRange ? getFormatDate(dateRange[0]) : undefined,
- period === 'custom' && dateRange ? getFormatDate(dateRange[1]) : undefined,
- timezone,
- timeBucket,
- )
- const revChart = revResult?.chart
- const revX = revChart?.x || []
- const revY = revChart?.revenue || []
- const revRefunds = revChart?.refundsAmount || []
-
- // Align revenue series to the main traffic chart x-axis to avoid empty/invalid renders
- if (Array.isArray(chart?.x) && chart.x.length > 0) {
- if (
- Array.isArray(revX) &&
- revX.length === chart.x.length &&
- revX[0] === chart.x[0] &&
- revX[revX.length - 1] === chart.x[chart.x.length - 1]
- ) {
- revenueData = revY.map((v) => Number(v ?? 0))
- refundsData = revRefunds.map((v) => Number(v ?? 0))
- } else if (Array.isArray(revX) && revX.length > 0) {
- const byX = new Map<string, number>()
- const refundsByX = new Map<string, number>()
- for (let i = 0; i < revX.length; i += 1) {
- byX.set(revX[i], Number(revY[i] ?? 0))
- refundsByX.set(revX[i], Number(revRefunds[i] ?? 0))
- }
- revenueData = chart.x.map((x: string) => Number(byX.get(x) ?? 0))
- refundsData = chart.x.map((x: string) => Number(refundsByX.get(x) ?? 0))
-
- // Fallback: if mapping produced all zeros but arrays match length, use index-based mapping
- if (revenueData.every((v) => v === 0) && revY.length === chart.x.length) {
- console.warn(
- '[Revenue] Key-based mapping failed, falling back to index-based alignment. Data may be misaligned.',
- )
- revenueData = revY.map((v) => Number(v ?? 0))
- refundsData = revRefunds.map((v) => Number(v ?? 0))
- }
- } else {
- revenueData = revY.map((v) => Number(v ?? 0))
- refundsData = revRefunds.map((v) => Number(v ?? 0))
- }
- } else {
- revenueData = revY.map((v) => Number(v ?? 0))
- refundsData = revRefunds.map((v) => Number(v ?? 0))
- }
- } catch {
- // Revenue data not available, continue without it
- revenueData = []
- refundsData = []
- }
- }
-
- // Merge revenue data with chart
- const chartWithRevenue = {
- ...chart,
- revenue: revenueData,
- refundsAmount: refundsData,
+ const byX = new Map<string, number>()
+ const refundsByX = new Map<string, number>()
+ for (let i = 0; i < revX.length; i += 1) {
+ byX.set(revX[i], Number(revY[i] ?? 0))
+ refundsByX.set(revX[i], Number(revRefunds[i] ?? 0))
}
-
- setChartData(chartWithRevenue as any)
-
- setPanelsData({
- types: _keys(params),
- data: params,
- customs,
- properties,
- meta,
- })
-
- setIsPanelsDataEmpty(false)
+ revenueData = chart.x.map((x: string) => Number(byX.get(x) ?? 0))
+ refundsData = chart.x.map((x: string) => Number(refundsByX.get(x) ?? 0))
}
-
- setAnalyticsLoading(false)
- setDataLoading(false)
- }
- } catch (reason) {
- if (isMountedRef.current) {
- setAnalyticsLoading(false)
- setDataLoading(false)
- setIsPanelsDataEmpty(true)
- console.error('[ERROR](loadAnalytics) Loading analytics data failed')
- console.error(reason)
}
+
+ setRevenueOverlay({ revenue: revenueData, refundsAmount: refundsData })
+ } catch {
+ setRevenueOverlay(null)
}
- }
+ }, [
+ project,
+ activeChartMetrics.revenue,
+ isRevenueConnected,
+ dateRange,
+ period,
+ timezone,
+ timeBucket,
+ baseChartData,
+ id,
+ fetchRevenueData,
+ ])
const getCustomEventMetadata = async (event: string) => {
+ let result
if (period === 'custom' && dateRange) {
- return getCustomEventsMetadata(
- id,
- event,
+ result = await fetchCustomEventsMetadata(id, event, {
timeBucket,
- '',
- getFormatDate(dateRange[0]),
- getFormatDate(dateRange[1]),
+ period: '',
+ from: getFormatDate(dateRange[0]),
+ to: getFormatDate(dateRange[1]),
timezone,
- projectPassword,
- )
+ })
+ } else {
+ result = await fetchCustomEventsMetadata(id, event, { timeBucket, period, timezone })
}
- return getCustomEventsMetadata(id, event, timeBucket, period, '', '', timezone, projectPassword)
+ return result || { result: [] }
}
const _getPropertyMetadata = async (property: string) => {
+ let result
if (period === 'custom' && dateRange) {
- return getPropertyMetadata(
- id,
- property,
+ result = await fetchPropertyMetadata(id, property, {
timeBucket,
- '',
- getFormatDate(dateRange[0]),
- getFormatDate(dateRange[1]),
+ period: '',
+ from: getFormatDate(dateRange[0]),
+ to: getFormatDate(dateRange[1]),
filters,
timezone,
- projectPassword,
- )
+ })
+ } else {
+ result = await fetchPropertyMetadata(id, property, { timeBucket, period, filters, timezone })
}
- return getPropertyMetadata(id, property, timeBucket, period, '', '', filters, timezone, projectPassword)
+ return result || { result: [] }
}
// Load GSC Keywords when the traffic sources panel switches to 'keywords'
@@ -759,10 +719,10 @@ const TrafficView = ({
const data =
period === 'custom' && dateRange
- ? await getGSCKeywords(id, '', from, to, timezone, projectPassword)
- : await getGSCKeywords(id, period, '', '', timezone, projectPassword)
+ ? await fetchGSCKeywords(id, { period: '', from, to, timezone })
+ : await fetchGSCKeywords(id, { period, timezone })
- if (isMountedRef.current) {
+ if (isMountedRef.current && data) {
if (data.notConnected) {
setKeywordsNotConnected(true)
setKeywords([])
@@ -788,41 +748,15 @@ const TrafficView = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [panelsActiveTabs.source, period, dateRange, timezone, id, project])
- // Load analytics on mount and when dependencies change
+ // Load revenue data when revenue metric is enabled
useEffect(() => {
- if (!project) return
- loadAnalytics()
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [
- activeChartMetrics.revenue,
- isRevenueConnected,
- mode,
- customMetrics,
- filters,
- project,
- isActiveCompare,
- dateRange,
- period,
- timeBucket,
- dateRangeCompare,
- activePeriodCompare,
- ])
-
- // Handle custom events chart loading
- useEffect(() => {
- if (!project) return
- if (activeChartMetricsCustomEvents.length === 0) {
- setCustomEventsChartData({})
- return
- }
- loadAnalytics()
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [activeChartMetricsCustomEvents])
+ loadRevenueData()
+ }, [loadRevenueData, fetchRevenueData])
- // Handle refresh trigger
+ // Handle refresh trigger - use revalidator for URL-based data
useEffect(() => {
if (trafficRefreshTrigger > 0) {
- loadAnalytics()
+ revalidator.revalidate()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [trafficRefreshTrigger])
@@ -843,27 +777,11 @@ const TrafficView = ({
return <WaitingForAnEvent />
}
- // Show loader during initial load
- if (analyticsLoading) {
- return (
- <div
- className={cx('flex flex-col bg-gray-50 dark:bg-slate-900', {
- 'min-h-including-header': !isEmbedded,
- 'min-h-screen': isEmbedded,
- })}
- >
- <Loader />
- </div>
- )
- }
-
const headerRightContent = (
<TrafficHeaderActions
projectViews={projectViews}
projectViewsLoading={projectViewsLoading}
- projectViewDeleting={projectViewDeleting}
loadProjectViews={loadProjectViews}
- onProjectViewDelete={onProjectViewDelete}
setProjectViewToUpdate={setProjectViewToUpdate}
setIsAddAViewOpened={setIsAddAViewOpened}
onCustomMetric={onCustomMetric}
@@ -948,7 +866,7 @@ const TrafficView = ({
<>
<DashboardHeader rightContent={headerRightContent} />
{dataLoading && !isPanelsDataEmpty ? <LoadingBar /> : null}
- <div className={cx({ hidden: isPanelsDataEmpty || analyticsLoading })}>
+ <div className={cx({ hidden: isPanelsDataEmpty })}>
{!isPanelsDataEmpty ? <Filters className='mb-3' tnMapping={tnMapping} /> : null}
<div className='relative overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-800/25'>
<div className='mb-3 flex w-full items-center justify-end gap-2 lg:absolute lg:top-2 lg:right-2 lg:mb-0 lg:w-auto lg:justify-normal'>
@@ -989,7 +907,7 @@ const TrafficView = ({
return (
<Checkbox
classes={{
- label: cx('p-2', { hidden: analyticsLoading }),
+ label: 'p-2',
}}
label={label}
disabled={conflicted}
@@ -1053,7 +971,7 @@ const TrafficView = ({
</div>
) : null}
{!checkIfAllMetricsAreDisabled && !_isEmpty(chartData) ? (
- <div onContextMenu={(e) => handleChartContextMenu(e, chartData.x)} className='relative'>
+ <div onContextMenu={(e) => handleChartContextMenu(e, (chartData as any).x)} className='relative'>
<TrafficChart
chartData={chartData}
timeBucket={timeBucket}
@@ -1444,4 +1362,6 @@ const TrafficView = ({
)
}
+const TrafficView = TrafficViewWrapper
+
export default TrafficView
diff --git a/web/app/pages/Project/tabs/Traffic/UserFlow.tsx b/web/app/pages/Project/tabs/Traffic/UserFlow.tsx
index 99b7ea56d..b5ef771d2 100644
--- a/web/app/pages/Project/tabs/Traffic/UserFlow.tsx
+++ b/web/app/pages/Project/tabs/Traffic/UserFlow.tsx
@@ -4,11 +4,11 @@ import { useEffect, useState, memo, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
-import { getUserFlow } from '~/api'
+import { useUserFlowProxy } from '~/hooks/useAnalyticsProxy'
import { UserFlowType } from '~/lib/models/UserFlow'
import Loader from '~/ui/Loader'
-import { useCurrentProject, useProjectPassword } from '../../../../providers/CurrentProjectProvider'
+import { useCurrentProject } from '../../../../providers/CurrentProjectProvider'
import { useViewProjectContext } from '../../View/ViewProject'
import { getFormatDate } from '../../View/ViewProject.helpers'
@@ -20,13 +20,13 @@ interface UserFlowProps {
const UserFlow = ({ setReversed, isReversed }: UserFlowProps) => {
const { dateRange, period, timeBucket, timezone, filters } = useViewProjectContext()
const { id } = useCurrentProject()
- const projectPassword = useProjectPassword(id)
const { t } = useTranslation('common')
const [isLoading, setIsLoading] = useState<boolean | null>(null)
const [userFlow, setUserFlow] = useState<{
ascending: UserFlowType
descending: UserFlowType
} | null>(null)
+ const { fetchUserFlow: fetchUserFlowProxy } = useUserFlowProxy()
const [from, to] = useMemo(() => {
if (!dateRange) {
@@ -44,17 +44,20 @@ const UserFlow = ({ setReversed, isReversed }: UserFlowProps) => {
setIsLoading(true)
try {
- const { ascending, descending } = await getUserFlow(
- id,
+ const result = await fetchUserFlowProxy(id, {
timeBucket,
period,
filters,
from,
to,
timezone,
- projectPassword,
- )
- setUserFlow({ ascending, descending })
+ })
+ if (result) {
+ setUserFlow({
+ ascending: result as unknown as UserFlowType,
+ descending: result as unknown as UserFlowType,
+ })
+ }
} catch (error: any) {
toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))
} finally {
diff --git a/web/app/pages/Unsubscribe/index.tsx b/web/app/pages/Unsubscribe/index.tsx
deleted file mode 100644
index 42b715a26..000000000
--- a/web/app/pages/Unsubscribe/index.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import _isString from 'lodash/isString'
-import { useState, useEffect, memo } from 'react'
-import { useTranslation } from 'react-i18next'
-import { useParams } from 'react-router'
-
-import { unsubscribeFromEmailReports, unsubscribeFromEmailReports3rdParty } from '~/api'
-import { useAuth } from '~/providers/AuthProvider'
-import StatusPage from '~/ui/StatusPage'
-import routes from '~/utils/routes'
-
-interface UnsubscribeProps {
- type: 'user-reports' | '3rdparty'
-}
-
-const Unsubscribe = ({ type }: UnsubscribeProps) => {
- const { t } = useTranslation('common')
- const { token } = useParams()
- const { isAuthenticated } = useAuth()
-
- const isValidToken = _isString(token)
- const [loading, setLoading] = useState(isValidToken)
- const [error, setError] = useState(isValidToken ? '' : t('apiNotifications.invalidToken'))
-
- useEffect(() => {
- if (!isValidToken) {
- return
- }
-
- const apiCall = type === 'user-reports' ? unsubscribeFromEmailReports : unsubscribeFromEmailReports3rdParty
-
- apiCall(token)
- .catch((reason) => {
- setError(_isString(reason) ? reason : reason?.response?.data?.message || reason.message)
- })
- .finally(() => {
- setLoading(false)
- })
- }, [token, type, isValidToken])
-
- const primaryAction = isAuthenticated
- ? { label: t('common.dashboard'), to: routes.dashboard, primary: true }
- : { label: t('auth.signin.button'), to: routes.signin, primary: true }
-
- if (loading) {
- return <StatusPage loading />
- }
-
- if (error) {
- return (
- <StatusPage
- type='error'
- title={error}
- actions={[primaryAction, { label: t('notFoundPage.support'), to: routes.contact }]}
- />
- )
- }
-
- return <StatusPage type='success' title={t('unsubscribe.success')} actions={[primaryAction]} />
-}
-
-export default memo(Unsubscribe)
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index e4ef96a8e..c7b812249 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -10,30 +10,19 @@ import _keys from 'lodash/keys'
import _map from 'lodash/map'
import _size from 'lodash/size'
import { MessageSquareTextIcon, MonitorIcon, UserRoundIcon } from 'lucide-react'
-import React, { useState, useEffect, memo, useMemo } from 'react'
+import React, { useState, useEffect, memo, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { useNavigate } from 'react-router'
-import { ClientOnly } from 'remix-utils/client-only'
+import { useNavigate, useFetcher } from 'react-router'
import { toast } from 'sonner'
-import {
- confirmEmail,
- generateApiKey,
- deleteApiKey,
- receiveLoginNotification,
- setShowLiveVisitorsInTitle,
- changeUserDetails,
- deleteUser,
-} from '~/api'
-import { withAuthentication, auth } from '~/hoc/protected'
import { reportFrequencies, DEFAULT_TIMEZONE, CONFIRMATION_TIMEOUT, TimeFormat, isSelfhosted } from '~/lib/constants'
import { User } from '~/lib/models/User'
import PaidFeature from '~/modals/PaidFeature'
import { useAuth } from '~/providers/AuthProvider'
+import type { UserSettingsActionData } from '~/routes/user-settings'
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 Select from '~/ui/Select'
import { Text } from '~/ui/Text'
@@ -103,39 +92,93 @@ interface Form extends Partial<User> {
}
const UserSettings = () => {
- const { user, isLoading, logout, setUser, mergeUser } = useAuth()
+ const { user, logout, mergeUser } = useAuth()
const navigate = useNavigate()
const { t } = useTranslation('common')
+ const fetcher = useFetcher<UserSettingsActionData>()
+
const [activeTab, setActiveTab] = useState(TAB_MAPPING.ACCOUNT)
- const [form, setForm] = useState<Form>({
+ const [form, setForm] = useState<Form>(() => ({
email: user?.email || '',
password: '',
repeat: '',
timeFormat: user?.timeFormat || TimeFormat['12-hour'],
- })
+ }))
const [showPasswordFields, setShowPasswordFields] = useState(false)
- const [timezone, setTimezone] = useState(user?.timezone || DEFAULT_TIMEZONE)
+ const [timezone, setTimezone] = useState(() => user?.timezone || DEFAULT_TIMEZONE)
const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)
const [isPasswordChangeModalOpened, setIsPasswordChangeModalOpened] = useState(false)
- const [reportFrequency, setReportFrequency] = useState(user?.reportFrequency)
- const [formPreset, setFormPreset] = useState(false)
- const [validated, setValidated] = useState(false)
- const [errors, setErrors] = useState<Record<string, string>>({})
+ const [reportFrequency, setReportFrequency] = useState(() => user?.reportFrequency)
const [beenSubmitted, setBeenSubmitted] = useState(false)
const [showModal, setShowModal] = useState(false)
const [showAPIDeleteModal, setShowAPIDeleteModal] = useState(false)
- const [error, setError] = useState<null | string>(null)
- const translatedFrequencies = _map(reportFrequencies, (key) => t(`profileSettings.${key}`))
- const translatedTimeFormat = _map(TimeFormat, (key) => t(`profileSettings.${key}`))
- const [settingUpdating, setSettingUpdating] = useState(false)
+ const translatedFrequencies = useMemo(() => _map(reportFrequencies, (key) => t(`profileSettings.${key}`)), [t])
+ const translatedTimeFormat = useMemo(() => _map(TimeFormat, (key) => t(`profileSettings.${key}`)), [t])
const [deletionFeedback, setDeletionFeedback] = useState('')
+ const lastHandledData = useRef<UserSettingsActionData | null>(null)
+ const passwordChangedRef = useRef(false)
+ const pendingToggles = useRef<Map<string, boolean>>(new Map())
+
+ const isSubmitting = fetcher.state === 'submitting'
+
const tabs = getTabs(t)
const activeTabLabel = useMemo(() => _find(tabs, (tab) => tab.id === activeTab)?.label, [tabs, activeTab])
- const validate = () => {
- const allErrors = {} as Record<string, string>
+ useEffect(() => {
+ if (fetcher.state !== 'idle' || !fetcher.data) return
+ if (lastHandledData.current === fetcher.data) return
+ lastHandledData.current = fetcher.data
+
+ if (fetcher.data.success) {
+ const { intent, user: updatedUser, apiKey } = fetcher.data
+
+ if (intent === 'update-profile' && updatedUser) {
+ mergeUser(updatedUser)
+ toast.success(t('profileSettings.updated'))
+
+ // If password was changed, log out the user
+ if (passwordChangedRef.current) {
+ passwordChangedRef.current = false
+ logout()
+ }
+ } else if (intent === 'generate-api-key' && apiKey) {
+ mergeUser({ apiKey })
+ toast.success(t('profileSettings.updated'))
+ } else if (intent === 'delete-api-key') {
+ mergeUser({ apiKey: null })
+ toast.success(t('profileSettings.updated'))
+ } else if (intent === 'toggle-live-visitors' && updatedUser) {
+ pendingToggles.current.delete('live-visitors')
+ mergeUser(updatedUser)
+ toast.success(t('profileSettings.updated'))
+ } else if (intent === 'toggle-login-notifications') {
+ pendingToggles.current.delete('login-notifications')
+ toast.success(t('profileSettings.updated'))
+ } else if (intent === 'confirm-email') {
+ setCookie(CONFIRMATION_TIMEOUT, true, 600)
+ toast.success(t('profileSettings.confSent'))
+ } else if (intent === 'delete-account') {
+ logout()
+ toast.success(t('apiNotifications.accountDeleted'))
+ navigate(routes.main)
+ }
+ } else if (fetcher.data?.error) {
+ if (pendingToggles.current.has('live-visitors')) {
+ mergeUser({ showLiveVisitorsInTitle: pendingToggles.current.get('live-visitors') })
+ pendingToggles.current.delete('live-visitors')
+ }
+ if (pendingToggles.current.has('login-notifications')) {
+ mergeUser({ receiveLoginNotifications: pendingToggles.current.get('login-notifications') })
+ pendingToggles.current.delete('login-notifications')
+ }
+ toast.error(fetcher.data.error)
+ }
+ }, [fetcher.data, fetcher.state, mergeUser, t, logout, navigate])
+
+ const errors = useMemo(() => {
+ const allErrors: Record<string, string> = {}
if (!isValidEmail(form.email)) {
allErrors.email = t('auth.common.badEmailError')
@@ -151,50 +194,10 @@ const UserSettings = () => {
allErrors.repeat = t('auth.common.noMatchError')
}
- const valid = _isEmpty(_keys(allErrors))
-
- setErrors(allErrors)
- setValidated(valid)
- }
+ return allErrors
+ }, [form.email, form.password, form.repeat, t])
- const onSubmit = async (data: any, callback: (isSuccess: boolean) => void = () => {}) => {
- delete data.repeat
-
- for (const key in data) {
- if (data[key] === '') {
- delete data[key]
- }
- }
-
- try {
- const result = await changeUserDetails(data)
- setUser(result)
- toast.success(t('profileSettings.updated'))
- } catch (reason: any) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- } finally {
- callback(true)
- }
- }
-
- useEffect(() => {
- validate()
- }, [form]) // eslint-disable-line
-
- useEffect(() => {
- if (isLoading || !user || formPreset) {
- return
- }
-
- setForm((prev) => ({
- ...prev,
- email: user.email || '',
- timeFormat: user.timeFormat || TimeFormat['12-hour'],
- }))
- setTimezone(user.timezone || DEFAULT_TIMEZONE)
- setReportFrequency(user.reportFrequency)
- setFormPreset(true)
- }, [isLoading, user, formPreset])
+ const validated = _isEmpty(_keys(errors))
const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
const { target } = event
@@ -206,11 +209,27 @@ const UserSettings = () => {
}))
}
- const handleSubmit = (
- e: React.FormEvent<HTMLFormElement> | null,
- force?: boolean,
- callback: (isSuccess: boolean) => void = () => {},
- ) => {
+ const submitProfileUpdate = (additionalData?: Record<string, unknown>) => {
+ setBeenSubmitted(true)
+
+ if (!validated) return
+
+ const formData = new FormData()
+ formData.set('intent', 'update-profile')
+ if (form.email) formData.set('email', form.email)
+ if (form.password) formData.set('password', form.password)
+ if (form.repeat) formData.set('repeat', form.repeat)
+ if (additionalData?.timezone) formData.set('timezone', additionalData.timezone as string)
+ if (additionalData?.timeFormat || form.timeFormat) {
+ formData.set('timeFormat', (additionalData?.timeFormat || form.timeFormat) as string)
+ }
+ if (additionalData?.reportFrequency) formData.set('reportFrequency', additionalData.reportFrequency as string)
+
+ passwordChangedRef.current = !!form.password
+ fetcher.submit(formData, { method: 'post' })
+ }
+
+ const handleSubmit = (e: React.FormEvent<HTMLFormElement> | null, force?: boolean) => {
if (e) {
e.preventDefault()
e.stopPropagation()
@@ -224,139 +243,87 @@ const UserSettings = () => {
return
}
- onSubmit(form, callback)
+ submitProfileUpdate()
}
}
const handleTimezoneSave = () => {
- setBeenSubmitted(true)
-
- if (validated) {
- onSubmit({
- ...form,
- timezone,
- })
- }
+ submitProfileUpdate({ timezone })
}
- const handleShowLiveVisitorsSave = async (checked: boolean) => {
- if (settingUpdating) {
- return
- }
-
- setSettingUpdating(true)
+ const handleShowLiveVisitorsSave = (checked: boolean) => {
+ if (pendingToggles.current.has('live-visitors')) return
- try {
- await setShowLiveVisitorsInTitle(checked)
- mergeUser({ showLiveVisitorsInTitle: checked })
- toast.success(t('profileSettings.updated'))
- } catch (reason: any) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- } finally {
- setSettingUpdating(false)
- }
+ pendingToggles.current.set('live-visitors', user?.showLiveVisitorsInTitle ?? false)
+ const formData = new FormData()
+ formData.set('intent', 'toggle-live-visitors')
+ formData.set('show', checked.toString())
+ fetcher.submit(formData, { method: 'post' })
+ // Optimistic update
+ mergeUser({ showLiveVisitorsInTitle: checked })
}
- const handleReceiveLoginNotifications = async (checked: boolean) => {
- if (settingUpdating) {
- return
- }
-
- setSettingUpdating(true)
+ const handleReceiveLoginNotifications = (checked: boolean) => {
+ if (pendingToggles.current.has('login-notifications')) return
- try {
- await receiveLoginNotification(checked)
- mergeUser({ receiveLoginNotifications: checked })
- toast.success(t('profileSettings.updated'))
- } catch (reason: any) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- } finally {
- setSettingUpdating(false)
- }
+ pendingToggles.current.set('login-notifications', user?.receiveLoginNotifications ?? false)
+ const formData = new FormData()
+ formData.set('intent', 'toggle-login-notifications')
+ formData.set('receiveLoginNotifications', checked.toString())
+ fetcher.submit(formData, { method: 'post' })
+ // Optimistic update
+ mergeUser({ receiveLoginNotifications: checked })
}
- const handleIntegrationSave = (data: any, callback: (isSuccess: boolean) => void = () => {}) => {
+ const handleIntegrationSave = (data: Record<string, unknown>, callback: (isSuccess: boolean) => void = () => {}) => {
setBeenSubmitted(true)
if (validated) {
- onSubmit(
- {
- ...form,
- ...data,
- },
- callback,
- )
+ submitProfileUpdate(data)
+ callback(true)
}
}
const handleReportSave = () => {
- setBeenSubmitted(true)
-
- if (validated) {
- onSubmit({
- ...form,
- reportFrequency,
- })
- }
+ submitProfileUpdate({ reportFrequency })
}
- const onAccountDelete = async () => {
- try {
- await deleteUser(deletionFeedback)
- logout()
- toast.success(t('apiNotifications.accountDeleted'))
- navigate(routes.main)
- } catch (reason: any) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
- }
+ const onAccountDelete = () => {
+ const formData = new FormData()
+ formData.set('intent', 'delete-account')
+ formData.set('feedback', deletionFeedback)
+ fetcher.submit(formData, { method: 'post' })
}
- const onEmailConfirm = async (errorCallback: any) => {
+ const onEmailConfirm = () => {
if (getCookie(CONFIRMATION_TIMEOUT)) {
toast.error(t('profileSettings.confTimeout'))
return
}
- try {
- const res = await confirmEmail()
-
- if (res) {
- setCookie(CONFIRMATION_TIMEOUT, true, 600)
- toast.success(t('profileSettings.confSent'))
- } else {
- errorCallback(t('profileSettings.noConfLeft'))
- }
- } catch (reason: any) {
- toast.error(reason)
- }
+ const formData = new FormData()
+ formData.set('intent', 'confirm-email')
+ fetcher.submit(formData, { method: 'post' })
}
- const onApiKeyGenerate = async () => {
- try {
- const { apiKey } = await generateApiKey()
- mergeUser({ apiKey })
- } catch (reason: any) {
- toast.error(reason)
+ const onApiKeyGenerate = () => {
+ if (isSubmitting) {
+ return
}
- }
- const onApiKeyDelete = async () => {
- try {
- await deleteApiKey()
- mergeUser({ apiKey: null })
- } catch (reason: any) {
- toast.error(reason)
- }
+ const formData = new FormData()
+ formData.set('intent', 'generate-api-key')
+ fetcher.submit(formData, { method: 'post' })
}
- const setAsyncTimeFormat = async () => {
- setBeenSubmitted(true)
+ const onApiKeyDelete = () => {
+ const formData = new FormData()
+ formData.set('intent', 'delete-api-key')
+ fetcher.submit(formData, { method: 'post' })
+ }
- if (validated) {
- onSubmit({
- ...form,
- })
- }
+ const setAsyncTimeFormat = () => {
+ submitProfileUpdate({ timeFormat: form.timeFormat })
}
const toggleShowPasswordFields = () => {
@@ -368,7 +335,7 @@ const UserSettings = () => {
setShowPasswordFields((prev) => !prev)
}
- const SharedProjects = () => (
+ const sharedProjectsSection = (
<>
<hr className='mt-5 border-gray-200 dark:border-gray-600' />
<Text as='h3' size='lg' weight='bold' className='mt-2 flex items-center'>
@@ -478,333 +445,307 @@ const UserSettings = () => {
</aside>
<section className='flex-1'>
- <ClientOnly fallback={<Loader />}>
- {() => {
- if (isLoading) {
- return <Loader />
- }
-
- if (activeTab === TAB_MAPPING.ACCOUNT) {
- return (
- <>
+ {activeTab === TAB_MAPPING.ACCOUNT ? (
+ <>
+ <Input
+ name='email'
+ type='email'
+ label={t('auth.common.email')}
+ value={form.email}
+ placeholder='[email protected]'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.email : null}
+ />
+ <span
+ onClick={toggleShowPasswordFields}
+ className='mt-2 flex max-w-max cursor-pointer items-center text-sm text-gray-900 hover:underline dark:text-gray-50'
+ >
+ {t('auth.common.changePassword')}
+ <ChevronDownIcon
+ className={cx('ml-2 size-3', {
+ 'rotate-180': showPasswordFields,
+ })}
+ />
+ </span>
+ {showPasswordFields ? (
+ <div className='mt-4 grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-6'>
+ <Input
+ name='password'
+ type='password'
+ label={t('auth.common.password')}
+ hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}
+ value={form.password}
+ placeholder={t('auth.common.password')}
+ className='sm:col-span-3'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.password : null}
+ />
+ <Input
+ name='repeat'
+ type='password'
+ label={t('auth.common.repeat')}
+ value={form.repeat}
+ placeholder={t('auth.common.repeat')}
+ className='sm:col-span-3'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.repeat : null}
+ />
+ </div>
+ ) : null}
+ <Button className='mt-4' type='submit' primary large>
+ {t('profileSettings.update')}
+ </Button>
+
+ <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.apiKey')}
+ </h3>
+ {user?.apiKey ? (
+ <>
+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.apiKeyWarning')}
+ </p>
+ <div className='grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
<Input
- name='email'
- type='email'
- label={t('auth.common.email')}
- value={form.email}
- placeholder='[email protected]'
- onChange={handleInput}
- error={beenSubmitted ? errors.email : null}
+ label={t('profileSettings.apiKey')}
+ name='apiKey'
+ className='mt-4'
+ value={user.apiKey}
+ disabled
/>
- <span
- onClick={toggleShowPasswordFields}
- className='mt-2 flex max-w-max cursor-pointer items-center text-sm text-gray-900 hover:underline dark:text-gray-50'
- >
- {t('auth.common.changePassword')}
- <ChevronDownIcon
- className={cx('ml-2 size-3', {
- 'rotate-180': showPasswordFields,
- })}
- />
- </span>
- {showPasswordFields ? (
- <div className='mt-4 grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-6'>
- <Input
- name='password'
- type='password'
- label={t('auth.common.password')}
- hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}
- value={form.password}
- placeholder={t('auth.common.password')}
- className='sm:col-span-3'
- onChange={handleInput}
- error={beenSubmitted ? errors.password : null}
- />
- <Input
- name='repeat'
- type='password'
- label={t('auth.common.repeat')}
- value={form.repeat}
- placeholder={t('auth.common.repeat')}
- className='sm:col-span-3'
- onChange={handleInput}
- error={beenSubmitted ? errors.repeat : null}
- />
+ </div>
+ </>
+ ) : (
+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.noApiKey')}
+ </p>
+ )}
+ {user?.apiKey ? (
+ <Button className='mt-4' onClick={() => setShowAPIDeleteModal(true)} danger large>
+ {t('profileSettings.deleteApiKeyBtn')}
+ </Button>
+ ) : (
+ <Button className='mt-4' onClick={onApiKeyGenerate} primary large>
+ {t('profileSettings.addApiKeyBtn')}
+ </Button>
+ )}
+
+ {isSelfhosted ? (
+ <>
+ {/* Shared projects setting */}
+ {sharedProjectsSection}
+ </>
+ ) : (
+ <>
+ {/* 2FA setting */}
+ <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.2fa')}
+ </h3>
+ <TwoFA />
+
+ {/* Socialisations setup */}
+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />
+ <h3
+ id='socialisations'
+ className='mt-2 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'
+ >
+ {t('profileSettings.socialisations')}
+ </h3>
+ <Socialisations />
+
+ {/* Shared projects setting */}
+ {sharedProjectsSection}
+
+ {/* Organisations setting */}
+ <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.organisations')}
+ </h3>
+ <div>
+ {!_isEmpty(user?.organisationMemberships) ? (
+ <div className='mt-3 overflow-hidden rounded-lg border border-gray-200 dark:border-slate-700'>
+ <table className='min-w-full divide-y divide-gray-200 dark:divide-slate-700'>
+ <thead className='bg-gray-50 dark:bg-slate-800'>
+ <tr>
+ <th
+ scope='col'
+ className='px-4 py-3 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'
+ >
+ {t('profileSettings.organisationsTable.organisation')}
+ </th>
+ <th
+ scope='col'
+ className='px-4 py-3 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'
+ >
+ {t('profileSettings.organisationsTable.role')}
+ </th>
+ <th
+ scope='col'
+ className='px-4 py-3 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'
+ >
+ {t('profileSettings.organisationsTable.joinedOn')}
+ </th>
+ <th scope='col' />
+ </tr>
+ </thead>
+ <tbody className='divide-y divide-gray-200 bg-white dark:divide-slate-700 dark:bg-slate-900'>
+ {_map(user?.organisationMemberships, (membership) => (
+ <Organisations key={membership.id} membership={membership} />
+ ))}
+ </tbody>
+ </table>
</div>
- ) : null}
- <Button className='mt-4' type='submit' primary large>
- {t('profileSettings.update')}
- </Button>
-
- <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.apiKey')}
- </h3>
- {user?.apiKey ? (
- <>
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
- {t('profileSettings.apiKeyWarning')}
- </p>
- <div className='grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
- <Input
- label={t('profileSettings.apiKey')}
- name='apiKey'
- className='mt-4'
- value={user.apiKey}
- disabled
- />
- </div>
- </>
- ) : (
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
- {t('profileSettings.noApiKey')}
- </p>
- )}
- {user?.apiKey ? (
- <Button className='mt-4' onClick={() => setShowAPIDeleteModal(true)} danger large>
- {t('profileSettings.deleteApiKeyBtn')}
- </Button>
) : (
- <Button className='mt-4' onClick={onApiKeyGenerate} primary large>
- {t('profileSettings.addApiKeyBtn')}
- </Button>
+ <NoOrganisations />
)}
+ </div>
- {isSelfhosted ? (
- <>
- {/* Shared projects setting */}
- <SharedProjects />
- </>
- ) : (
- <>
- {/* 2FA setting */}
- <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.2fa')}
- </h3>
- <TwoFA />
-
- {/* Socialisations setup */}
- <hr className='mt-5 border-gray-200 dark:border-gray-600' />
- <h3
- id='socialisations'
- className='mt-2 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'
- >
- {t('profileSettings.socialisations')}
- </h3>
- <Socialisations />
-
- {/* Shared projects setting */}
- <SharedProjects />
-
- {/* Organisations setting */}
- <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.organisations')}
- </h3>
- <div>
- {!_isEmpty(user?.organisationMemberships) ? (
- <div className='mt-3 overflow-hidden rounded-lg border border-gray-200 dark:border-slate-700'>
- <table className='min-w-full divide-y divide-gray-200 dark:divide-slate-700'>
- <thead className='bg-gray-50 dark:bg-slate-800'>
- <tr>
- <th
- scope='col'
- className='px-4 py-3 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'
- >
- {t('profileSettings.organisationsTable.organisation')}
- </th>
- <th
- scope='col'
- className='px-4 py-3 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'
- >
- {t('profileSettings.organisationsTable.role')}
- </th>
- <th
- scope='col'
- className='px-4 py-3 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'
- >
- {t('profileSettings.organisationsTable.joinedOn')}
- </th>
- <th scope='col' />
- </tr>
- </thead>
- <tbody className='divide-y divide-gray-200 bg-white dark:divide-slate-700 dark:bg-slate-900'>
- {_map(user?.organisationMemberships, (membership) => (
- <Organisations key={membership.id} membership={membership} />
- ))}
- </tbody>
- </table>
- </div>
- ) : (
- <NoOrganisations />
- )}
- </div>
-
- <hr className='mt-5 border-gray-200 dark:border-gray-600' />
- {!user?.isActive ? (
- <div
- className='mt-4 flex max-w-max cursor-pointer pl-0 text-blue-600 underline hover:text-indigo-800 dark:hover:text-indigo-600'
- onClick={() => onEmailConfirm(setError)}
- >
- <EnvelopeIcon className='mt-0.5 mr-2 h-6 w-6 text-blue-500' />
- {t('profileSettings.noLink')}
- </div>
- ) : null}
- </>
- )}
- <div className='mt-4 flex flex-wrap justify-center gap-2 sm:justify-end'>
- <Button
- onClick={() => {
- logout(true)
- }}
- semiSmall
- semiDanger
- >
- <>
- {/* We need this div for the button to match the height of the button after it */}
- <div className='h-5' />
- {t('profileSettings.logoutAll')}
- </>
- </Button>
- <Button onClick={() => setShowModal(true)} semiSmall semiDanger>
- <>
- <ExclamationTriangleIcon className='mr-1 h-5 w-5' />
- {t('profileSettings.delete')}
- </>
- </Button>
+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />
+ {!user?.isActive ? (
+ <div
+ className='mt-4 flex max-w-max cursor-pointer pl-0 text-blue-600 underline hover:text-indigo-800 dark:hover:text-indigo-600'
+ onClick={onEmailConfirm}
+ >
+ <EnvelopeIcon className='mt-0.5 mr-2 h-6 w-6 text-blue-500' />
+ {t('profileSettings.noLink')}
</div>
- </>
- )
- }
-
- if (activeTab === TAB_MAPPING.INTERFACE) {
- return (
+ ) : null}
+ </>
+ )}
+ <div className='mt-4 flex flex-wrap justify-center gap-2 sm:justify-end'>
+ <Button
+ onClick={() => {
+ logout(true)
+ }}
+ semiSmall
+ semiDanger
+ >
<>
- <h3 className='flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
- {t('profileSettings.timezone')}
- </h3>
- <div className='mt-4 grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
- <div>
- <TimezonePicker value={timezone} onChange={setTimezone} />
- </div>
- </div>
- <Button className='mt-4' onClick={handleTimezoneSave} primary large>
- {t('common.save')}
- </Button>
- {/* Timeformat selector (12 / 24 hour format) */}
- <hr className='mt-5 border-gray-200 dark:border-gray-600' />
- <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
- {t('profileSettings.timeFormat')}
- </h3>
- <div className='mt-4 grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
- <div>
- <Select
- title={t(`profileSettings.${form.timeFormat}`)}
- label={t('profileSettings.selectTimeFormat')}
- className='w-full'
- items={translatedTimeFormat}
- onSelect={(f) =>
- setForm((prev) => ({
- ...prev,
- timeFormat: timeFormatArray[_findIndex(translatedTimeFormat, (freq) => freq === f)],
- }))
- }
- capitalise
- selectedItem={
- translatedTimeFormat[_findIndex(timeFormatArray, (freq) => freq === form.timeFormat)]
- }
- />
- </div>
- </div>
- <Button className='mt-4' onClick={setAsyncTimeFormat} primary large>
- {t('common.save')}
- </Button>
-
- {/* UI Settings */}
- <hr className='mt-5 border-gray-200 dark:border-gray-600' />
- <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
- {t('profileSettings.uiSettings')}
- </h3>
- <Checkbox
- checked={user?.showLiveVisitorsInTitle}
- onChange={handleShowLiveVisitorsSave}
- disabled={settingUpdating}
- name='active'
- classes={{
- label: 'mt-4',
- }}
- label={t('profileSettings.showVisitorsInTitle')}
- />
+ {/* We need this div for the button to match the height of the button after it */}
+ <div className='h-5' />
+ {t('profileSettings.logoutAll')}
</>
- )
- }
-
- if (activeTab === TAB_MAPPING.COMMUNICATIONS) {
- return (
+ </Button>
+ <Button onClick={() => setShowModal(true)} semiSmall semiDanger>
<>
- {!isSelfhosted ? (
- <>
- {/* Email reports frequency selector (e.g. monthly, weekly, etc.) */}
- <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>
- {t('profileSettings.email')}
- </h3>
- <div className='mt-4 grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
- <div>
- <Select
- title={t(`profileSettings.${reportFrequency}`)}
- label={t('profileSettings.frequency')}
- className='w-full'
- items={translatedFrequencies}
- onSelect={(f) =>
- setReportFrequency(
- reportFrequencies[_findIndex(translatedFrequencies, (freq) => freq === f)],
- )
- }
- capitalise
- selectedItem={
- translatedFrequencies[
- _findIndex(reportFrequencies, (freq) => freq === reportFrequency)
- ]
- }
- />
- </div>
- </div>
- <Button className='mt-4' onClick={handleReportSave} primary large>
- {t('common.save')}
- </Button>
-
- <hr className='mt-5 border-gray-200 dark:border-gray-600' />
- {/* Integrations setup */}
- <h3
- id='integrations'
- className='mt-2 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'
- >
- {t('profileSettings.integrations')}
- </h3>
- <Integrations handleIntegrationSave={handleIntegrationSave} />
- {user?.isTelegramChatIdConfirmed ? (
- <Checkbox
- checked={user?.receiveLoginNotifications}
- onChange={handleReceiveLoginNotifications}
- disabled={settingUpdating}
- name='receiveLoginNotifications'
- classes={{
- label: 'mt-4',
- }}
- label={t('profileSettings.receiveLoginNotifications')}
- />
- ) : null}
- </>
- ) : null}
+ <ExclamationTriangleIcon className='mr-1 h-5 w-5' />
+ {t('profileSettings.delete')}
</>
- )
- }
-
- return null
- }}
- </ClientOnly>
+ </Button>
+ </div>
+ </>
+ ) : null}
+
+ {activeTab === TAB_MAPPING.INTERFACE ? (
+ <>
+ <h3 className='flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.timezone')}
+ </h3>
+ <div className='mt-4 grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
+ <div>
+ <TimezonePicker value={timezone} onChange={setTimezone} />
+ </div>
+ </div>
+ <Button className='mt-4' onClick={handleTimezoneSave} primary large>
+ {t('common.save')}
+ </Button>
+ {/* Timeformat selector (12 / 24 hour format) */}
+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />
+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.timeFormat')}
+ </h3>
+ <div className='mt-4 grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
+ <div>
+ <Select
+ title={t(`profileSettings.${form.timeFormat}`)}
+ label={t('profileSettings.selectTimeFormat')}
+ className='w-full'
+ items={translatedTimeFormat}
+ onSelect={(f) =>
+ setForm((prev) => ({
+ ...prev,
+ timeFormat: timeFormatArray[_findIndex(translatedTimeFormat, (freq) => freq === f)],
+ }))
+ }
+ capitalise
+ selectedItem={
+ translatedTimeFormat[_findIndex(timeFormatArray, (freq) => freq === form.timeFormat)]
+ }
+ />
+ </div>
+ </div>
+ <Button className='mt-4' onClick={setAsyncTimeFormat} primary large>
+ {t('common.save')}
+ </Button>
+
+ {/* UI Settings */}
+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />
+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.uiSettings')}
+ </h3>
+ <Checkbox
+ checked={user?.showLiveVisitorsInTitle}
+ onChange={handleShowLiveVisitorsSave}
+ disabled={fetcher.formData?.get('intent') === 'toggle-live-visitors'}
+ name='active'
+ classes={{
+ label: 'mt-4',
+ }}
+ label={t('profileSettings.showVisitorsInTitle')}
+ />
+ </>
+ ) : null}
+
+ {activeTab === TAB_MAPPING.COMMUNICATIONS && !isSelfhosted ? (
+ <>
+ {/* Email reports frequency selector (e.g. monthly, weekly, etc.) */}
+ <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>{t('profileSettings.email')}</h3>
+ <div className='mt-4 grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
+ <div>
+ <Select
+ title={t(`profileSettings.${reportFrequency}`)}
+ label={t('profileSettings.frequency')}
+ className='w-full'
+ items={translatedFrequencies}
+ onSelect={(f) =>
+ setReportFrequency(reportFrequencies[_findIndex(translatedFrequencies, (freq) => freq === f)])
+ }
+ capitalise
+ selectedItem={
+ translatedFrequencies[_findIndex(reportFrequencies, (freq) => freq === reportFrequency)]
+ }
+ />
+ </div>
+ </div>
+ <Button className='mt-4' onClick={handleReportSave} primary large>
+ {t('common.save')}
+ </Button>
+
+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />
+ {/* Integrations setup */}
+ <h3
+ id='integrations'
+ className='mt-2 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'
+ >
+ {t('profileSettings.integrations')}
+ </h3>
+ <Integrations handleIntegrationSave={handleIntegrationSave} />
+ {user?.isTelegramChatIdConfirmed ? (
+ <Checkbox
+ checked={user?.receiveLoginNotifications}
+ onChange={handleReceiveLoginNotifications}
+ disabled={fetcher.formData?.get('intent') === 'toggle-login-notifications'}
+ name='receiveLoginNotifications'
+ classes={{
+ label: 'mt-4',
+ }}
+ label={t('profileSettings.receiveLoginNotifications')}
+ />
+ ) : null}
+ </>
+ ) : null}
</section>
</div>
</form>
@@ -856,28 +797,13 @@ const UserSettings = () => {
message={t('profileSettings.apiKeyDeleteConf')}
isOpened={showAPIDeleteModal}
/>
- <Modal
- onClose={() => {
- setError(null)
- }}
- closeText={t('common.gotIt')}
- type='error'
- title={t('common.error')}
- message={error}
- isOpened={Boolean(error)}
- />
<Modal
onClose={() => {
setIsPasswordChangeModalOpened(false)
}}
onSubmit={() => {
setIsPasswordChangeModalOpened(false)
- handleSubmit(null, true, (isSuccess: boolean) => {
- // password has been changed, let's log out the user as all the sessions are now invalid
- if (isSuccess) {
- logout()
- }
- })
+ handleSubmit(null, true)
}}
closeText={t('common.cancel')}
submitText={t('common.continue')}
@@ -890,4 +816,4 @@ const UserSettings = () => {
)
}
-export default memo(withAuthentication(UserSettings, auth.authenticated))
+export default memo(UserSettings)
diff --git a/web/app/pages/UserSettings/components/Integrations.tsx b/web/app/pages/UserSettings/components/Integrations.tsx
index 7a0186921..967b53401 100644
--- a/web/app/pages/UserSettings/components/Integrations.tsx
+++ b/web/app/pages/UserSettings/components/Integrations.tsx
@@ -1,13 +1,14 @@
import { CheckCircleIcon, XCircleIcon, ClockIcon } from '@heroicons/react/24/solid'
import type i18next from 'i18next'
import _map from 'lodash/map'
-import React, { useState, memo } from 'react'
+import React, { useState, memo, useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { removeTgIntegration } from '~/api'
import { User } from '~/lib/models/User'
import { useAuth } from '~/providers/AuthProvider'
+import type { UserSettingsActionData } from '~/routes/user-settings'
import Button from '~/ui/Button'
import Discord from '~/ui/icons/Discord'
import Slack from '~/ui/icons/Slack'
@@ -70,6 +71,23 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
const [isIntegrationLoading, setIsIntegrationLoading] = useState(false)
const [isRemovalLoading, setIsRemovalLoading] = useState(false)
+ const fetcher = useFetcher<UserSettingsActionData>()
+ const isTgRemovalLoading = fetcher.state !== 'idle'
+
+ useEffect(() => {
+ if (fetcher.data?.intent === 'remove-tg-integration') {
+ if (fetcher.data.success) {
+ mergeUser({
+ isTelegramChatIdConfirmed: false,
+ telegramChatId: null,
+ })
+ trackCustom('INTEGRATION_REMOVED', { integration: 'telegram' })
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ }
+ }, [fetcher.data, mergeUser])
+
const setupIntegration = (key: string) => () => {
setIntegrationConfigurating(key)
}
@@ -166,31 +184,22 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
}
const removeIntegration = async (key: string) => {
- if (isRemovalLoading || !user) {
+ if (isRemovalLoading || isTgRemovalLoading || !user) {
return
}
- setIsRemovalLoading(true)
-
if (key === 'telegram') {
- try {
- if (user.telegramChatId) {
- await removeTgIntegration(user.telegramChatId)
- } else {
- throw new Error('No chat ID')
- }
- mergeUser({
- isTelegramChatIdConfirmed: false,
- telegramChatId: null,
- })
- } catch (reason: any) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.integrationRemovalError'))
- console.error(`[ERROR] Failed to remove TG integration: ${reason}`)
+ if (!user.telegramChatId) {
+ toast.error(t('apiNotifications.integrationRemovalError'))
+ return
}
- setIsRemovalLoading(false)
+ fetcher.submit({ intent: 'remove-tg-integration', tgID: user.telegramChatId }, { method: 'POST' })
+ return
}
+ setIsRemovalLoading(true)
+
if (key === 'slack') {
handleIntegrationSave(
{
@@ -199,6 +208,8 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
(isSuccess: boolean) => {
if (!isSuccess) {
toast.error(t('apiNotifications.integrationRemovalError'))
+ } else {
+ trackCustom('INTEGRATION_REMOVED', { integration: key })
}
mergeUser({
@@ -217,6 +228,8 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
(isSuccess: boolean) => {
if (!isSuccess) {
toast.error(t('apiNotifications.integrationRemovalError'))
+ } else {
+ trackCustom('INTEGRATION_REMOVED', { integration: key })
}
mergeUser({
@@ -226,10 +239,6 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
},
)
}
-
- trackCustom('INTEGRATION_REMOVED', {
- integration: key,
- })
}
if (integrationConfigurating) {
diff --git a/web/app/pages/UserSettings/components/Organisations.tsx b/web/app/pages/UserSettings/components/Organisations.tsx
index fcca74048..4f2ef0b47 100644
--- a/web/app/pages/UserSettings/components/Organisations.tsx
+++ b/web/app/pages/UserSettings/components/Organisations.tsx
@@ -2,13 +2,14 @@ import cx from 'clsx'
import dayjs from 'dayjs'
import _filter from 'lodash/filter'
import _map from 'lodash/map'
-import { memo, useState } from 'react'
+import { memo, useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { rejectOrganisationInvitation, acceptOrganisationInvitation } from '~/api'
import { OrganisationMembership } from '~/lib/models/Organisation'
import { useAuth } from '~/providers/AuthProvider'
+import type { UserSettingsActionData } from '~/routes/user-settings'
import Button from '~/ui/Button'
import Modal from '~/ui/Modal'
@@ -26,42 +27,47 @@ const Organisations = ({ membership }: OrganisationsProps) => {
const [showDeleteModal, setShowDeleteModal] = useState(false)
const { organisation, confirmed, role, created } = membership
- const onQuit = async () => {
- try {
- await rejectOrganisationInvitation(membership.id)
+ const fetcher = useFetcher<UserSettingsActionData>()
+ const isLoading = fetcher.state !== 'idle'
- mergeUser({
- organisationMemberships: _filter(
- user?.organisationMemberships,
- (userMembership) => userMembership.id !== membership.id,
- ),
- })
-
- toast.success(t('apiNotifications.quitOrganisation'))
- } catch (reason) {
- console.error(`[ERROR] Error while quitting project: ${reason}`)
- toast.error(t('apiNotifications.quitOrganisationError'))
+ useEffect(() => {
+ if (fetcher.data?.intent === 'reject-organisation-invitation') {
+ if (fetcher.data.success) {
+ mergeUser({
+ organisationMemberships: _filter(
+ user?.organisationMemberships,
+ (userMembership) => userMembership.id !== membership.id,
+ ),
+ })
+ toast.success(t('apiNotifications.quitOrganisation'))
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
}
- }
- const onAccept = async () => {
- try {
- await acceptOrganisationInvitation(membership.id)
+ if (fetcher.data?.intent === 'accept-organisation-invitation') {
+ if (fetcher.data.success) {
+ mergeUser({
+ organisationMemberships: _map(user?.organisationMemberships, (item) => {
+ if (item.id === membership.id) {
+ return { ...item, confirmed: true }
+ }
+ return item
+ }),
+ })
+ toast.success(t('apiNotifications.acceptInvitation'))
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ }
+ }, [fetcher.data, mergeUser, membership.id, t, user?.organisationMemberships])
- mergeUser({
- organisationMemberships: _map(user?.organisationMemberships, (item) => {
- if (item.id === membership.id) {
- return { ...item, confirmed: true }
- }
- return item
- }),
- })
+ const onQuit = () => {
+ fetcher.submit({ intent: 'reject-organisation-invitation', membershipId: membership.id }, { method: 'POST' })
+ }
- toast.success(t('apiNotifications.acceptInvitation'))
- } catch (reason) {
- console.error(`[ERROR] Error while accepting project invitation: ${reason}`)
- toast.error(t('apiNotifications.acceptInvitationError'))
- }
+ const onAccept = () => {
+ fetcher.submit({ intent: 'accept-organisation-invitation', membershipId: membership.id }, { method: 'POST' })
}
return (
@@ -89,7 +95,7 @@ const Organisations = ({ membership }: OrganisationsProps) => {
<Button className='mr-2' onClick={() => setShowDeleteModal(true)} primary small>
{t('common.reject')}
</Button>
- <Button onClick={onAccept} primary small>
+ <Button onClick={onAccept} loading={isLoading} primary small>
{t('common.accept')}
</Button>
</>
diff --git a/web/app/pages/UserSettings/components/ProjectList.tsx b/web/app/pages/UserSettings/components/ProjectList.tsx
index 3d43c724f..784165033 100644
--- a/web/app/pages/UserSettings/components/ProjectList.tsx
+++ b/web/app/pages/UserSettings/components/ProjectList.tsx
@@ -1,13 +1,14 @@
import dayjs from 'dayjs'
import _filter from 'lodash/filter'
import _map from 'lodash/map'
-import { memo, useState } from 'react'
+import { memo, useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { rejectProjectShare, acceptProjectShare } from '~/api'
import { SharedProject } from '~/lib/models/SharedProject'
import { useAuth } from '~/providers/AuthProvider'
+import { UserSettingsActionData } from '~/routes/user-settings'
import Button from '~/ui/Button'
import Modal from '~/ui/Modal'
@@ -21,41 +22,48 @@ const ProjectList = ({ item }: ProjectListProps) => {
i18n: { language },
} = useTranslation('common')
const { user, mergeUser } = useAuth()
+ const fetcher = useFetcher<UserSettingsActionData>()
const [showDeleteModal, setShowDeleteModal] = useState(false)
const { created, confirmed, id, role, project } = item
- const onQuit = async () => {
- try {
- await rejectProjectShare(item.id)
- mergeUser({
- sharedProjects: _filter(user?.sharedProjects, (share) => share.id !== item.id),
- })
- toast.success(t('apiNotifications.quitProject'))
- } catch (reason) {
- console.error(`[ERROR] Error while quitting project: ${reason}`)
- toast.error(t('apiNotifications.quitProjectError'))
+ const isPending = fetcher.state !== 'idle'
+
+ useEffect(() => {
+ if (fetcher.data?.intent === 'reject-project-share') {
+ if (fetcher.data.success) {
+ mergeUser({
+ sharedProjects: _filter(user?.sharedProjects, (share) => share.id !== item.id),
+ })
+ toast.success(t('apiNotifications.quitProject'))
+ } else if (fetcher.data.error) {
+ toast.error(t('apiNotifications.quitProjectError'))
+ }
}
- }
- const onAccept = async () => {
- try {
- await acceptProjectShare(id)
+ if (fetcher.data?.intent === 'accept-project-share') {
+ if (fetcher.data.success) {
+ mergeUser({
+ sharedProjects: _map(user?.sharedProjects, (share) => {
+ if (share.id === id) {
+ return { ...share, confirmed: true }
+ }
+ return share
+ }),
+ })
+ toast.success(t('apiNotifications.acceptInvitation'))
+ } else if (fetcher.data.error) {
+ toast.error(t('apiNotifications.acceptInvitationError'))
+ }
+ }
+ }, [fetcher.data, id, item.id, mergeUser, t, user?.sharedProjects])
- mergeUser({
- sharedProjects: _map(user?.sharedProjects, (item) => {
- if (item.id === id) {
- return { ...item, confirmed: true }
- }
- return item
- }),
- })
+ const onQuit = () => {
+ fetcher.submit({ intent: 'reject-project-share', shareId: item.id }, { method: 'post', action: '/user-settings' })
+ }
- toast.success(t('apiNotifications.acceptInvitation'))
- } catch (reason) {
- console.error(`[ERROR] Error while accepting project invitation: ${reason}`)
- toast.error(t('apiNotifications.acceptInvitationError'))
- }
+ const onAccept = () => {
+ fetcher.submit({ intent: 'accept-project-share', shareId: id }, { method: 'post', action: '/user-settings' })
}
return (
@@ -71,15 +79,15 @@ const ProjectList = ({ item }: ProjectListProps) => {
</td>
<td className='px-4 py-3 text-right text-sm whitespace-nowrap'>
{confirmed ? (
- <Button onClick={() => setShowDeleteModal(true)} danger small>
+ <Button onClick={() => setShowDeleteModal(true)} danger small loading={isPending}>
{t('common.quit')}
</Button>
) : (
<>
- <Button className='mr-2' onClick={() => setShowDeleteModal(true)} primary small>
+ <Button className='mr-2' onClick={() => setShowDeleteModal(true)} primary small loading={isPending}>
{t('common.reject')}
</Button>
- <Button onClick={onAccept} primary small>
+ <Button onClick={onAccept} primary small loading={isPending}>
{t('common.accept')}
</Button>
</>
diff --git a/web/app/pages/UserSettings/components/Socialisations.tsx b/web/app/pages/UserSettings/components/Socialisations.tsx
index 7cbd90c68..a6070668d 100644
--- a/web/app/pages/UserSettings/components/Socialisations.tsx
+++ b/web/app/pages/UserSettings/components/Socialisations.tsx
@@ -1,15 +1,17 @@
import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'
import _map from 'lodash/map'
-import { useState } from 'react'
+import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { generateSSOAuthURL, linkBySSOHash, unlinkSSO } from '~/api'
+import { useAuthProxy } from '~/hooks/useAuthProxy'
import { SSO_PROVIDERS } from '~/lib/constants'
import { SSOProvider } from '~/lib/models/Auth'
import { User } from '~/lib/models/User'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
+import type { UserSettingsActionData } from '~/routes/user-settings'
import Button from '~/ui/Button'
import GithubDark from '~/ui/icons/GithubDark'
import GithubLight from '~/ui/icons/GithubLight'
@@ -63,6 +65,20 @@ const Socialisations = () => {
const { theme } = useTheme()
const { t } = useTranslation('common')
const [isLoading, setIsLoading] = useState(false)
+ const fetcher = useFetcher<UserSettingsActionData>()
+ const isUnlinking = fetcher.state !== 'idle'
+ const { generateSSOAuthURL, linkBySSOHash } = useAuthProxy()
+
+ useEffect(() => {
+ if (fetcher.data?.intent === 'unlink-sso') {
+ if (fetcher.data.success) {
+ loadUser()
+ toast.success(t('apiNotifications.socialAccountUninked'))
+ } else if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ }
+ }
+ }, [fetcher.data, loadUser, t])
const linkSSO = async (provider: SSOProvider) => {
setIsLoading(true)
@@ -135,19 +151,8 @@ const Socialisations = () => {
}
}
- const onUnlinkSSO = async (provider: SSOProvider) => {
- setIsLoading(true)
-
- try {
- await unlinkSSO(provider)
- await loadUser()
-
- toast.success(t('apiNotifications.socialAccountUninked'))
- } catch (reason) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.socialisationUnlinkGenericError'))
- } finally {
- setIsLoading(false)
- }
+ const onUnlinkSSO = (provider: SSOProvider) => {
+ fetcher.submit({ intent: 'unlink-sso', provider }, { method: 'POST' })
}
return (
@@ -212,7 +217,7 @@ const Socialisations = () => {
) : null}
{connected && unlinkable ? (
- <Button onClick={() => onUnlinkSSO(key)} loading={isLoading} small danger>
+ <Button onClick={() => onUnlinkSSO(key)} loading={isUnlinking} small danger>
{t('common.unlink')}
</Button>
) : null}
diff --git a/web/app/pages/UserSettings/components/TwoFA.tsx b/web/app/pages/UserSettings/components/TwoFA.tsx
index d6a8f8f0a..b91e05f22 100644
--- a/web/app/pages/UserSettings/components/TwoFA.tsx
+++ b/web/app/pages/UserSettings/components/TwoFA.tsx
@@ -1,20 +1,19 @@
import cx from 'clsx'
import _isNull from 'lodash/isNull'
-import _isString from 'lodash/isString'
-import React, { useState } from 'react'
+import React, { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import QRCode from 'react-qr-code'
+import { useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { generate2FA, enable2FA, disable2FA } from '~/api'
import { useAuth } from '~/providers/AuthProvider'
+import type { UserSettingsActionData } from '~/routes/user-settings'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
-import { setAccessToken } from '~/utils/accessToken'
-import { setRefreshToken } from '~/utils/refreshToken'
const TwoFA = () => {
const { user, mergeUser } = useAuth()
+ const fetcher = useFetcher<UserSettingsActionData>()
const { t } = useTranslation('common')
const [twoFAConfigurating, setTwoFAConfigurating] = useState(false)
@@ -22,13 +21,57 @@ const TwoFA = () => {
const [twoFAConfigData, setTwoFAConfigData] = useState<{
secret?: string
otpauthUrl?: string
- }>({}) // { secret, otpauthUrl }
- const [isTwoFaLoading, setIsTwoFaLoading] = useState(false)
+ }>({})
const [twoFACode, setTwoFACode] = useState('')
const [twoFACodeError, setTwoFACodeError] = useState<string | null>(null)
const [twoFARecovery, setTwoFARecovery] = useState<string | null>(null)
const { isTwoFactorAuthenticationEnabled } = user || {}
+ const isLoading = fetcher.state === 'submitting' || fetcher.state === 'loading'
+
+ // Handle fetcher responses
+ useEffect(() => {
+ if (fetcher.data?.success) {
+ const { intent, twoFAData } = fetcher.data
+
+ if (intent === 'generate-2fa' && twoFAData) {
+ setTimeout(() => {
+ setTwoFAConfigurating(true)
+ setTwoFAConfigData({ secret: twoFAData.secret, otpauthUrl: twoFAData.otpauthUrl })
+ }, 0)
+ } else if (intent === 'enable-2fa' && twoFAData?.twoFactorRecoveryCode) {
+ mergeUser({ isTwoFactorAuthenticationEnabled: true })
+ setTimeout(() => {
+ setTwoFARecovery(twoFAData.twoFactorRecoveryCode ?? null)
+ setTwoFACode('')
+ }, 0)
+ } else if (intent === 'disable-2fa') {
+ mergeUser({ isTwoFactorAuthenticationEnabled: false })
+ setTimeout(() => {
+ setTwoFADisabling(false)
+ setTwoFACode('')
+ }, 0)
+ }
+ } else if (fetcher.data?.error) {
+ const { intent, error } = fetcher.data
+
+ if (intent === 'enable-2fa' || intent === 'disable-2fa') {
+ setTimeout(() => {
+ setTwoFACodeError(t('profileSettings.invalid2fa'))
+ setTwoFACode('')
+ }, 0)
+ } else {
+ toast.error(error)
+ if (intent === 'generate-2fa') {
+ setTimeout(() => {
+ setTwoFAConfigurating(false)
+ setTwoFAConfigData({})
+ }, 0)
+ }
+ }
+ }
+ }, [fetcher.data, mergeUser, t])
+
const handle2FAInput = (event: React.ChangeEvent<HTMLInputElement>) => {
const {
target: { value },
@@ -37,74 +80,29 @@ const TwoFA = () => {
setTwoFACodeError(null)
}
- const _generate2FA = async () => {
- if (!isTwoFaLoading) {
- setIsTwoFaLoading(true)
-
- try {
- const result = await generate2FA()
- setTwoFAConfigurating(true)
- setTwoFAConfigData(result)
- } catch (reason) {
- if (_isString(reason)) {
- toast.error(reason)
- } else {
- toast.error(t('apiNotifications.generate2FAError'))
- }
- console.error(`[ERROR] Failed to generate 2FA: ${reason}`)
- setTwoFAConfigurating(false)
- setTwoFAConfigData({})
- }
-
- setIsTwoFaLoading(false)
- }
+ const _generate2FA = () => {
+ const formData = new FormData()
+ formData.set('intent', 'generate-2fa')
+ fetcher.submit(formData, { method: 'post' })
}
- const _enable2FA = async () => {
- if (!isTwoFaLoading) {
- setIsTwoFaLoading(true)
-
- try {
- const { twoFactorRecoveryCode, accessToken, refreshToken } = await enable2FA(twoFACode)
- setRefreshToken(refreshToken)
- // TODO: Should probably pass dontRemember here if user session is temporary
- setAccessToken(accessToken)
- mergeUser({ isTwoFactorAuthenticationEnabled: true })
- setTwoFARecovery(twoFactorRecoveryCode)
- } catch (reason) {
- if (_isString(reason)) {
- toast.error(reason)
- }
- setTwoFACodeError(t('profileSettings.invalid2fa'))
- }
-
- setTwoFACode('')
- setIsTwoFaLoading(false)
- }
+ const _enable2FA = () => {
+ const formData = new FormData()
+ formData.set('intent', 'enable-2fa')
+ formData.set('code', twoFACode)
+ fetcher.submit(formData, { method: 'post' })
}
- const _disable2FA = async () => {
- if (!isTwoFaLoading) {
- setIsTwoFaLoading(true)
-
- try {
- await disable2FA(twoFACode)
- mergeUser({ isTwoFactorAuthenticationEnabled: false })
- } catch (reason) {
- if (_isString(reason)) {
- toast.error(reason)
- }
- setTwoFACodeError(t('profileSettings.invalid2fa'))
- }
-
- setTwoFACode('')
- setIsTwoFaLoading(false)
- }
+ const _disable2FA = () => {
+ const formData = new FormData()
+ formData.set('intent', 'disable-2fa')
+ formData.set('code', twoFACode)
+ fetcher.submit(formData, { method: 'post' })
}
const callFnOnKeyPress =
- (fn: (e: any) => void, key = 'Enter') =>
- (e: any) => {
+ (fn: (e: React.KeyboardEvent) => void, key = 'Enter') =>
+ (e: React.KeyboardEvent) => {
e.stopPropagation()
if (e.key === key) {
fn(e)
@@ -142,7 +140,7 @@ const TwoFA = () => {
onChange={handle2FAInput}
onKeyDown={callFnOnKeyPress(_disable2FA)}
error={twoFACodeError}
- disabled={isTwoFaLoading}
+ disabled={isLoading}
/>
<Button
className={cx('ml-2', {
@@ -150,7 +148,7 @@ const TwoFA = () => {
'mb-1': !_isNull(twoFACodeError),
})}
onClick={_disable2FA}
- loading={isTwoFaLoading}
+ loading={isLoading}
danger
large
>
@@ -190,7 +188,7 @@ const TwoFA = () => {
onChange={handle2FAInput}
onKeyDown={callFnOnKeyPress(_enable2FA)}
error={twoFACodeError}
- disabled={isTwoFaLoading}
+ disabled={isLoading}
/>
<Button
className={cx('ml-2', {
@@ -198,7 +196,7 @@ const TwoFA = () => {
'mb-1': !_isNull(twoFACodeError),
})}
onClick={_enable2FA}
- loading={isTwoFaLoading}
+ loading={isLoading}
primary
large
>
@@ -212,7 +210,7 @@ const TwoFA = () => {
return (
<>
<p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>{t('profileSettings.2faEnable')}</p>
- <Button className='mt-4' onClick={_generate2FA} loading={isTwoFaLoading} primary large>
+ <Button className='mt-4' onClick={_generate2FA} loading={isLoading} primary large>
{t('profileSettings.2faEnableBtn')}
</Button>
</>
diff --git a/web/app/providers/AuthProvider.tsx b/web/app/providers/AuthProvider.tsx
index eba6ac927..c82e5c4ff 100644
--- a/web/app/providers/AuthProvider.tsx
+++ b/web/app/providers/AuthProvider.tsx
@@ -1,11 +1,8 @@
-import { isCancel } from 'axios'
-import { createContext, useCallback, useContext, useEffect, useState } from 'react'
+import { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'
-import { authMe } from '~/api'
+import { useAuthProxy } from '~/hooks/useAuthProxy'
import { User } from '~/lib/models/User'
-import { getAccessToken } from '~/utils/accessToken'
-import { logout as logoutCookies } from '~/utils/auth'
-import { getRefreshToken } from '~/utils/refreshToken'
+import { clearLocalStorageOnLogout } from '~/utils/auth'
interface AuthContextType {
isAuthenticated: boolean
@@ -16,8 +13,8 @@ interface AuthContextType {
setUser: (user: User) => void
mergeUser: (newUser: Partial<User>) => void
setTotalMonthlyEvents: (totalMonthlyEvents: number) => void
- loadUser: (signal?: AbortSignal) => Promise<void>
setIsAuthenticated: (isAuthenticated: boolean) => void
+ loadUser: (signal?: AbortSignal) => Promise<void>
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
@@ -25,25 +22,67 @@ const AuthContext = createContext<AuthContextType | undefined>(undefined)
interface AuthProviderProps {
children: React.ReactNode
initialIsAuthenticated: boolean
+ initialUser?: User | null
+ initialTotalMonthlyEvents?: number
}
-export const AuthProvider = ({ children, initialIsAuthenticated }: AuthProviderProps) => {
- const [isAuthenticated, setIsAuthenticated] = useState(initialIsAuthenticated)
- const [isLoading, setIsLoading] = useState(true)
- const [user, setUser] = useState<User | null>(null)
+export const AuthProvider = ({
+ children,
+ initialIsAuthenticated,
+ initialUser,
+ initialTotalMonthlyEvents,
+}: AuthProviderProps) => {
+ const { authMe } = useAuthProxy()
+ const [isAuthenticated, setIsAuthenticated] = useState(initialIsAuthenticated || !!initialUser)
+ const [user, setUserState] = useState<User | null>(initialUser || null)
// TODO: @deprecated
- const [totalMonthlyEvents, setTotalMonthlyEvents] = useState(0)
+ const [totalMonthlyEvents, setTotalMonthlyEvents] = useState(initialTotalMonthlyEvents || 0)
+
+ // Track whether this is the initial mount
+ const isInitialMount = useRef(true)
+
+ // Sync state with loader data when it changes (e.g., after login redirect)
+ useEffect(() => {
+ // Skip the initial mount since state is already initialized from props
+ if (isInitialMount.current) {
+ isInitialMount.current = false
+ return
+ }
+
+ if (initialUser) {
+ setUserState(initialUser)
+ setIsAuthenticated(true)
+ setTotalMonthlyEvents(initialTotalMonthlyEvents || 0)
+ } else {
+ setUserState(null)
+ setIsAuthenticated(false)
+ setTotalMonthlyEvents(0)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [initialUser?.id, initialTotalMonthlyEvents])
+
+ const setUser = useCallback((newUser: User) => {
+ setUserState(newUser)
+ }, [])
const logout = useCallback((invalidateAllSessions?: boolean) => {
setIsAuthenticated(false)
- setUser(null)
- logoutCookies(invalidateAllSessions)
+ setUserState(null)
+ clearLocalStorageOnLogout()
+
+ // Navigate to server-side logout route which handles cookie cleanup
+ const logoutUrl = invalidateAllSessions ? '/logout?logoutAll=true' : '/logout'
+ window.location.href = logoutUrl
}, [])
const mergeUser = useCallback((newUser: Partial<User>) => {
- setUser((prev) => {
+ setUserState((prev) => {
if (!prev) {
+ // If no previous user, set the new user as full user (if it has required fields)
+ if ('id' in newUser && 'email' in newUser) {
+ return newUser as User
+ }
return null
}
@@ -54,72 +93,34 @@ export const AuthProvider = ({ children, initialIsAuthenticated }: AuthProviderP
const loadUser = useCallback(
async (signal?: AbortSignal) => {
try {
- const { user, totalMonthlyEvents } = await authMe({ signal })
- setUser(user)
+ const { user, totalMonthlyEvents } = await authMe(signal)
+ setUserState(user)
setTotalMonthlyEvents(totalMonthlyEvents)
setIsAuthenticated(true)
} catch (error) {
- if (isCancel(error)) {
+ if (error instanceof Error && error.name === 'AbortError') {
return
}
-
logout()
setIsAuthenticated(false)
- } finally {
- setIsLoading(false)
}
},
- [logout],
+ [logout, authMe],
)
- useEffect(() => {
- if (!initialIsAuthenticated) {
- setIsLoading(false)
- return
- }
-
- const abortController = new AbortController()
-
- loadUser(abortController.signal)
-
- return () => abortController.abort()
- }, [initialIsAuthenticated, loadUser])
-
- useEffect(() => {
- const abortController = new AbortController()
-
- if (initialIsAuthenticated) {
- loadUser(abortController.signal)
- return () => abortController.abort()
- }
-
- // Client-side rehydration: if tokens exist but SSR did not receive cookies
- const hasClientToken = Boolean(getAccessToken() || getRefreshToken())
-
- if (hasClientToken) {
- setIsLoading(true)
- loadUser(abortController.signal)
- return () => abortController.abort()
- }
-
- setIsLoading(false)
- return () => abortController.abort()
- }, [initialIsAuthenticated, loadUser])
-
return (
<AuthContext.Provider
value={{
- //
isAuthenticated,
+ isLoading: false,
user,
- isLoading,
logout,
totalMonthlyEvents,
setTotalMonthlyEvents,
setUser,
mergeUser,
- loadUser,
setIsAuthenticated,
+ loadUser,
}}
>
{children}
diff --git a/web/app/providers/CurrentProjectProvider.tsx b/web/app/providers/CurrentProjectProvider.tsx
index 09d8ad1b3..10d9a28ad 100644
--- a/web/app/providers/CurrentProjectProvider.tsx
+++ b/web/app/providers/CurrentProjectProvider.tsx
@@ -1,20 +1,18 @@
-import _replace from 'lodash/replace'
-import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useNavigate, useSearchParams } from 'react-router'
+import { useNavigate, useSearchParams, useFetcher, useLoaderData } from 'react-router'
import { toast } from 'sonner'
-import { checkPassword, getLiveVisitors, getProject } from '~/api'
+import { useLiveVisitorsProxy } from '~/hooks/useAnalyticsProxy'
import { LIVE_VISITORS_UPDATE_INTERVAL, LS_PROJECTS_PROTECTED_KEY, Period, TimeBucket } from '~/lib/constants'
import { type Project } from '~/lib/models/Project'
-import { getItemJSON, removeItem } from '~/utils/localstorage'
+import type { ProjectLoaderData, ProjectViewActionData } from '~/routes/projects.$id'
+import { getItemJSON } from '~/utils/localstorage'
import routes from '~/utils/routes'
import { getProjectPreferences, setProjectPassword, setProjectPreferences } from '../pages/Project/View/utils/cache'
import { CHART_METRICS_MAPPING } from '../pages/Project/View/ViewProject.helpers'
-import { useAuth } from './AuthProvider'
-
interface CurrentProjectContextType {
id: string
project: Project | null
@@ -49,110 +47,95 @@ export const useProjectPassword = (id?: string) => {
const useProject = (id: string) => {
const { t } = useTranslation('common')
const navigate = useNavigate()
- const { isLoading: authLoading } = useAuth()
- const projectPassword = useProjectPassword(id)
- const [project, setProject] = useState<Project | null>(null)
- const [isPasswordRequired, setIsPasswordRequired] = useState(false)
- const [passwordForRetry, setPasswordForRetry] = useState<string | null>(null)
+ const loaderData = useLoaderData<ProjectLoaderData>()
+ const storedPassword = useProjectPassword(id)
- const [searchParams] = useSearchParams()
+ // Use loader data only for initial state (SSR hydration)
+ const [project, setProject] = useState<Project | null>(() => loaderData?.project || null)
+ const [isPasswordRequired, setIsPasswordRequired] = useState(() => loaderData?.isPasswordRequired || false)
- const params = useMemo(() => {
- const searchParamsObj = new URLSearchParams()
+ const passwordFetcher = useFetcher<ProjectViewActionData>()
+ const lastHandledFetcherData = useRef<ProjectViewActionData | null>(null)
+ const hasTriedStoredPassword = useRef(false)
+ const passwordResolverRef = useRef<((value: { success: boolean; error?: string }) => void) | null>(null)
+ const lastSubmittedPasswordRef = useRef<string | null>(null)
- if (searchParams.has('theme')) {
- searchParamsObj.set('theme', searchParams.get('theme')!)
+ useEffect(() => {
+ if (loaderData?.error && !loaderData.project && !loaderData.isPasswordRequired) {
+ console.error('[ERROR] (getProject)', loaderData.error)
+ toast.error(t('project.noExist'))
+ navigate(routes.dashboard)
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
- if (searchParams.has('embedded')) {
- searchParamsObj.set('embedded', searchParams.get('embedded')!)
+ // Auto-submit stored password if loader says password is required but we have it in localStorage
+ useEffect(() => {
+ if (
+ loaderData?.isPasswordRequired &&
+ storedPassword &&
+ !hasTriedStoredPassword.current &&
+ passwordFetcher.state === 'idle'
+ ) {
+ hasTriedStoredPassword.current = true
+ passwordFetcher.submit(
+ { intent: 'get-project', password: storedPassword },
+ { method: 'POST', action: `/projects/${id}` },
+ )
}
+ }, [loaderData?.isPasswordRequired, storedPassword, id, passwordFetcher])
- const searchString = searchParamsObj.toString()
- return searchString ? `?${searchString}` : undefined
- }, [searchParams])
-
- const onErrorLoading = useCallback(() => {
- if (projectPassword) {
- checkPassword(id, projectPassword).then((res) => {
- if (res) {
- navigate({
- pathname: _replace(routes.project, ':id', id),
- search: params,
- })
- return
- }
-
- toast.error(t('apiNotifications.incorrectPassword'))
- setIsPasswordRequired(true)
- removeItem(LS_PROJECTS_PROTECTED_KEY)
- })
- return
- }
+ // Handle password fetcher response
+ useEffect(() => {
+ if (passwordFetcher.state !== 'idle' || !passwordFetcher.data) return
- toast.error(t('project.noExist'))
- navigate(routes.dashboard)
- }, [id, projectPassword, navigate, t, params])
+ // Prevent handling the same response twice
+ if (lastHandledFetcherData.current === passwordFetcher.data) return
+ lastHandledFetcherData.current = passwordFetcher.data
- // Function to submit password and retry loading project
- const submitPassword = useCallback(
- async (password: string): Promise<{ success: boolean; error?: string }> => {
- try {
- const isValid = await checkPassword(id, password)
-
- if (!isValid) {
- return { success: false, error: t('apiNotifications.incorrectPassword') }
- }
-
- // Password is correct, store it for future use and trigger project reload
- setProjectPassword(id, password)
- setPasswordForRetry(password)
- setIsPasswordRequired(false)
- return { success: true }
- } catch (error) {
- console.error('[ERROR] (submitPassword)', error)
- return { success: false, error: t('apiNotifications.somethingWentWrong') }
- }
- },
- [id, t],
- )
+ if (passwordFetcher.data.success && passwordFetcher.data.data) {
+ const result = passwordFetcher.data.data as Project
+ setProject(result)
+ setIsPasswordRequired(false)
- useEffect(() => {
- if (authLoading || project) {
- return
- }
-
- // Use passwordForRetry if available, otherwise use stored password
- const effectivePassword = passwordForRetry || projectPassword
+ if (lastSubmittedPasswordRef.current) {
+ setProjectPassword(id, lastSubmittedPasswordRef.current)
+ lastSubmittedPasswordRef.current = null
+ }
- getProject(id, effectivePassword)
- .then((result) => {
- if (!result) {
- onErrorLoading()
- return
- }
+ if (passwordResolverRef.current) {
+ passwordResolverRef.current({ success: true })
+ passwordResolverRef.current = null
+ }
+ } else if (passwordFetcher.data.error) {
+ toast.error(t('apiNotifications.incorrectPassword'))
- if (result.isPasswordProtected && !result.role && !effectivePassword) {
- // Show password modal instead of redirecting
- setIsPasswordRequired(true)
- return
- }
+ lastSubmittedPasswordRef.current = null
+ if (passwordResolverRef.current) {
+ passwordResolverRef.current({ success: false, error: passwordFetcher.data.error })
+ passwordResolverRef.current = null
+ }
+ }
+ }, [passwordFetcher.state, passwordFetcher.data, t, id])
- setProject(result)
- })
- .catch((reason) => {
- console.error('[ERROR] (getProject)', reason)
- onErrorLoading()
+ const submitPassword = useCallback(
+ async (password: string): Promise<{ success: boolean; error?: string }> => {
+ return new Promise((resolve) => {
+ passwordResolverRef.current = resolve
+ lastSubmittedPasswordRef.current = password
+ passwordFetcher.submit({ intent: 'get-project', password }, { method: 'POST', action: `/projects/${id}` })
})
- }, [authLoading, project, id, projectPassword, passwordForRetry, navigate, onErrorLoading, params])
+ },
+ [id, passwordFetcher],
+ )
- const mergeProject = useCallback((project: Partial<Project>) => {
+ const mergeProject = useCallback((updates: Partial<Project>) => {
setProject((prev) => {
if (!prev) {
return null
}
- return { ...prev, ...project }
+ return { ...prev, ...updates }
})
}, [])
@@ -185,33 +168,41 @@ const useProjectPreferences = (id: string) => {
}
const useLiveVisitors = (project: Project | null) => {
- const projectPassword = useProjectPassword(project?.id)
+ const projectId = project?.id
+ const isLocked = project?.isLocked
const [liveVisitors, setLiveVisitors] = useState(0)
+ const { fetchLiveVisitors } = useLiveVisitorsProxy()
const updateLiveVisitors = useCallback(async () => {
- if (!project || project.isLocked) {
+ if (!projectId || isLocked) {
return
}
- const { id: pid } = project
- const result = await getLiveVisitors([pid], projectPassword)
- setLiveVisitors(result[pid] || 0)
- }, [project, projectPassword])
+ try {
+ const result = await fetchLiveVisitors([projectId])
+ if (result) {
+ setLiveVisitors(result[projectId] || 0)
+ }
+ } catch (reason) {
+ console.error('Failed to update live visitors:', reason)
+ }
+ }, [projectId, isLocked, fetchLiveVisitors])
useEffect(() => {
- if (!project || project.isLocked) {
+ if (!projectId || isLocked) {
return
}
- // eslint-disable-next-line react-hooks/set-state-in-effect -- Initial fetch and interval subscription
+ // Initial fetch on mount - eslint-disable needed as this is intentional
+ // eslint-disable-next-line react-hooks/set-state-in-effect
updateLiveVisitors()
- const interval = setInterval(async () => {
- await updateLiveVisitors()
+ const interval = setInterval(() => {
+ updateLiveVisitors()
}, LIVE_VISITORS_UPDATE_INTERVAL)
return () => clearInterval(interval)
- }, [project, updateLiveVisitors])
+ }, [projectId, isLocked, updateLiveVisitors])
return { liveVisitors, updateLiveVisitors }
}
diff --git a/web/app/root.tsx b/web/app/root.tsx
index 89a0334c5..64253b9bf 100644
--- a/web/app/root.tsx
+++ b/web/app/root.tsx
@@ -20,15 +20,17 @@ import {
import { useChangeLanguage } from 'remix-i18next/react'
import { ExternalScripts } from 'remix-utils/external-scripts'
+import { getAuthenticatedUser } from '~/api/api.server'
import { LocaleLinks } from '~/components/LocaleLinks'
import SelfhostedApiUrlBanner from '~/components/SelfhostedApiUrlBanner'
import { SEO } from '~/components/SEO'
-import { CONTACT_EMAIL, LS_THEME_SETTING, isSelfhosted, I18N_CACHE_BREAKER } from '~/lib/constants'
+import { CONTACT_EMAIL, LS_THEME_SETTING, isSelfhosted, I18N_CACHE_BREAKER, isDevelopment } from '~/lib/constants'
import mainCss from '~/styles/index.css?url'
import tailwindCss from '~/styles/tailwind.css?url'
import { trackViews, trackErrors, trackError } from '~/utils/analytics'
import { getCookie } from '~/utils/cookie'
-import { detectTheme, isAuthenticated, isWWW } from '~/utils/server'
+import { detectTheme, isWWW } from '~/utils/server'
+import { createHeadersWithCookies, hasAuthTokens } from '~/utils/session.server'
import AppWrapper from './App'
import { detectLanguage } from './i18n'
@@ -198,7 +200,20 @@ export async function loader({ request }: LoaderFunctionArgs) {
const locale = detectLanguage(request)
const theme = detectTheme(request)
- const isAuthed = isAuthenticated(request)
+ const hasTokens = hasAuthTokens(request)
+
+ let user = null
+ let totalMonthlyEvents = 0
+ let cookies: string[] = []
+
+ if (hasTokens) {
+ const authResult = await getAuthenticatedUser(request)
+ if (authResult) {
+ user = authResult.user.user
+ totalMonthlyEvents = authResult.user.totalMonthlyEvents
+ cookies = authResult.cookies
+ }
+ }
const REMIX_ENV = {
NODE_ENV: process.env.NODE_ENV,
@@ -212,19 +227,36 @@ export async function loader({ request }: LoaderFunctionArgs) {
COOKIE_DOMAIN: process.env.COOKIE_DOMAIN,
}
- return { locale, url, theme, REMIX_ENV, isAuthed, pathname: urlObject.pathname }
+ const loaderData = {
+ locale,
+ url,
+ theme,
+ REMIX_ENV,
+ isAuthed: !!user,
+ user,
+ totalMonthlyEvents,
+ pathname: urlObject.pathname,
+ }
+
+ if (cookies.length > 0) {
+ return data(loaderData, {
+ headers: createHeadersWithCookies(cookies),
+ })
+ }
+
+ return loaderData
}
export const handle = { i18n: 'common' }
const Body = () => {
- const { isAuthed } = useLoaderData<typeof loader>()
+ const { isAuthed, user, totalMonthlyEvents } = useLoaderData<typeof loader>()
const { theme } = useTheme()
return (
<body className={cx(theme, { 'bg-gray-50': theme === 'light', 'bg-slate-900': theme === 'dark' })}>
<SelfhostedApiUrlBanner />
- <AuthProvider initialIsAuthenticated={isAuthed}>
+ <AuthProvider initialIsAuthenticated={isAuthed} initialUser={user} initialTotalMonthlyEvents={totalMonthlyEvents}>
<AppWrapper />
</AuthProvider>
<ScrollRestoration />
@@ -253,6 +285,7 @@ export default function App() {
<SEO />
<meta name='google' content='notranslate' />
<link rel='icon' type='image/x-icon' href={isSelfhosted ? '/favicon-ce.ico' : '/favicon.ico'} />
+ {isDevelopment ? <script src='https://unpkg.com/[email protected]/dist/auto.global.js' /> : null}
<Meta />
<meta name='viewport' content='width=device-width,initial-scale=1' />
<Links />
diff --git a/web/app/routes/$.tsx b/web/app/routes/$.tsx
index 8799825cf..d2096681f 100644
--- a/web/app/routes/$.tsx
+++ b/web/app/routes/$.tsx
@@ -1,11 +1,11 @@
-import type { LoaderFunction, MetaFunction } from 'react-router'
+import type { LoaderFunctionArgs, MetaFunction } from 'react-router'
import { data, useLoaderData } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { getOgImageUrl } from '~/lib/constants'
import Post from '~/pages/Blog/Post'
import NotFound from '~/pages/NotFound'
-import { getPost } from '~/utils/getPosts'
+import { getPost } from '~/utils/getPosts.server'
import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
export const meta: MetaFunction = (loaderData: any) => {
@@ -26,14 +26,14 @@ export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export const loader: LoaderFunction = async ({ params }) => {
+export async function loader({ request, params }: LoaderFunctionArgs) {
const catchAllPath = params['*']
if (!catchAllPath) {
return data(null, { status: 404 })
}
- const post = await getPost(catchAllPath, undefined, true)
+ const post = await getPost(request, catchAllPath, undefined, true)
if (post) {
return post
diff --git a/web/app/routes/3rd-party-unsubscribe.$token.tsx b/web/app/routes/3rd-party-unsubscribe.$token.tsx
index 4847321dc..cd98e7f6a 100644
--- a/web/app/routes/3rd-party-unsubscribe.$token.tsx
+++ b/web/app/routes/3rd-party-unsubscribe.$token.tsx
@@ -1,21 +1,65 @@
-import { redirect } from 'react-router'
+import type { LoaderFunctionArgs } from 'react-router'
+import { redirect, useLoaderData } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { serverFetch } from '~/api/api.server'
import { isSelfhosted } from '~/lib/constants'
-import Unsubscribe from '~/pages/Unsubscribe'
+import StatusPage from '~/ui/StatusPage'
+import routes from '~/utils/routes'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export async function loader() {
+export interface UnsubscribeLoaderData {
+ success: boolean
+ error?: string
+}
+
+export async function loader({ request, params }: LoaderFunctionArgs): Promise<UnsubscribeLoaderData | Response> {
if (isSelfhosted) {
return redirect('/login', 302)
}
- return null
+ const { token } = params
+
+ if (!token) {
+ return { success: false, error: 'Invalid token' }
+ }
+
+ const result = await serverFetch(request, `project/unsubscribe/${token}`, {
+ skipAuth: true,
+ })
+
+ if (result.error) {
+ const errorMessage = typeof result.error === 'string' ? result.error : 'Failed to unsubscribe'
+ return { success: false, error: errorMessage }
+ }
+
+ return { success: true }
}
-export default function Index() {
- return <Unsubscribe type='3rdparty' />
+export default function ThirdPartyUnsubscribeRoute() {
+ const data = useLoaderData<UnsubscribeLoaderData>()
+
+ if (data.error) {
+ return (
+ <StatusPage
+ type='error'
+ title={data.error}
+ actions={[
+ { label: 'Sign In', to: routes.signin, primary: true },
+ { label: 'Support', to: routes.contact },
+ ]}
+ />
+ )
+ }
+
+ return (
+ <StatusPage
+ type='success'
+ title='Successfully unsubscribed from email reports'
+ actions={[{ label: 'Sign In', to: routes.signin, primary: true }]}
+ />
+ )
}
diff --git a/web/app/routes/_index.tsx b/web/app/routes/_index.tsx
index bdb349eff..ec52a49c9 100644
--- a/web/app/routes/_index.tsx
+++ b/web/app/routes/_index.tsx
@@ -29,7 +29,7 @@ import { Link, redirect, useLoaderData } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { ClientOnly } from 'remix-utils/client-only'
-import { getGeneralStats, getPaymentMetainfo } from '~/api'
+import { getGeneralStats, serverFetch } from '~/api/api.server'
import Header from '~/components/Header'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
import FAQ from '~/components/marketing/FAQ'
@@ -82,7 +82,16 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
}
- return { deviceInfo }
+ const [metainfoResult, stats] = await Promise.all([
+ serverFetch<Metainfo>(request, 'user/metainfo', { skipAuth: true }),
+ getGeneralStats(request),
+ ])
+
+ return {
+ deviceInfo,
+ metainfo: metainfoResult.data ?? DEFAULT_METAINFO,
+ stats,
+ }
}
interface FeedbackHighlightProps {
@@ -186,15 +195,8 @@ const REVIEWERS = [
},
]
-const Testimonials = ({ className }: { className?: string }) => {
+const Testimonials = ({ className, stats }: { className?: string; stats: Stats | null }) => {
const { t } = useTranslation('common')
- const [stats, setStats] = useState<Stats>({} as Stats)
-
- useEffect(() => {
- getGeneralStats()
- .then((stats) => setStats(stats))
- .catch(console.error)
- }, [])
return (
<div className={cn('flex flex-col items-center justify-center gap-3 md:flex-row', className)}>
@@ -217,31 +219,15 @@ const Testimonials = ({ className }: { className?: string }) => {
<StarIcon className='size-5 text-yellow-500' />
</div>
<div className='text-base text-gray-900/70 dark:text-gray-200'>
- <ClientOnly
- fallback={
- <Trans
- values={{
- amount: '> 1000',
- }}
- t={t}
- i18nKey='main.understandTheirUsers'
- >
- <span className='font-semibold text-gray-900 dark:text-gray-50' />
- </Trans>
- }
+ <Trans
+ values={{
+ amount: stats?.users || '> 1000',
+ }}
+ t={t}
+ i18nKey='main.understandTheirUsers'
>
- {() => (
- <Trans
- values={{
- amount: stats.users || '> 1000',
- }}
- t={t}
- i18nKey='main.understandTheirUsers'
- >
- <span className='font-semibold text-gray-900 dark:text-gray-50' />
- </Trans>
- )}
- </ClientOnly>
+ <span className='font-semibold text-gray-900 dark:text-gray-50' />
+ </Trans>
</div>
</div>
</div>
@@ -312,6 +298,7 @@ const LiveDemoPreview = () => {
const Hero = () => {
const { t } = useTranslation('common')
+ const { stats } = useLoaderData<typeof loader>()
return (
<div className='relative isolate bg-gray-100/80 pt-2 dark:bg-slate-800/50'>
@@ -366,7 +353,7 @@ const Hero = () => {
<span>{t('main.heroBenefits.selfHostable')}</span>
</div>
</div>
- <Testimonials className='mt-8 hidden lg:block' />
+ <Testimonials className='mt-8 hidden lg:block' stats={stats} />
</div>
<div className='col-span-6 mt-10 overflow-visible lg:mt-0 lg:mr-0 lg:ml-4'>
<ClientOnly
@@ -377,7 +364,7 @@ const Hero = () => {
{() => <LiveDemoPreview />}
</ClientOnly>
</div>
- <Testimonials className='mt-8 lg:hidden' />
+ <Testimonials className='mt-8 lg:hidden' stats={stats} />
</section>
</div>
</div>
@@ -1365,18 +1352,7 @@ const FeaturesShowcase = () => {
t,
i18n: { language },
} = useTranslation('common')
- const [metainfo, setMetainfo] = useState<Metainfo>(DEFAULT_METAINFO)
- const { deviceInfo } = useLoaderData<typeof loader>()
-
- useEffect(() => {
- const abortController = new AbortController()
-
- getPaymentMetainfo({ signal: abortController.signal })
- .then(setMetainfo)
- .catch(() => {})
-
- return () => abortController.abort()
- }, [])
+ const { deviceInfo, metainfo } = useLoaderData<typeof loader>()
const geoOptions = [
{
@@ -1701,6 +1677,8 @@ const FeaturesShowcase = () => {
}
export default function Index() {
+ const { metainfo } = useLoaderData<typeof loader>()
+
return (
<div className='overflow-hidden'>
<main className='bg-gray-50 dark:bg-slate-900'>
@@ -1710,7 +1688,7 @@ export default function Index() {
<FeaturesShowcase />
- <MarketingPricing />
+ <MarketingPricing metainfo={metainfo} />
<FAQ />
diff --git a/web/app/routes/api.ai.ts b/web/app/routes/api.ai.ts
new file mode 100644
index 000000000..bb7413ec2
--- /dev/null
+++ b/web/app/routes/api.ai.ts
@@ -0,0 +1,40 @@
+import { type ActionFunctionArgs, type LoaderFunctionArgs, data } from 'react-router'
+
+import { streamingServerFetch } from '~/api/api.server'
+
+export async function action({ request }: ActionFunctionArgs) {
+ const body = await request.json()
+ const { pid, messages, timezone } = body
+
+ if (!pid || !messages) {
+ return data({ error: 'pid and messages are required' }, { status: 400 })
+ }
+
+ try {
+ const response = await streamingServerFetch(request, `ai/${pid}/chat`, {
+ method: 'POST',
+ body: { messages, timezone },
+ })
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}))
+ return data({ error: errorData.message || `HTTP error! status: ${response.status}` }, { status: response.status })
+ }
+
+ // Stream the response back to the client
+ return new Response(response.body, {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ Connection: 'keep-alive',
+ },
+ })
+ } catch (error) {
+ console.error('[api.ai] Proxy request failed:', error)
+ return data({ error: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 })
+ }
+}
+
+export async function loader({ request: _request }: LoaderFunctionArgs) {
+ return data({ error: 'Use POST method' }, { status: 405 })
+}
diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.ts
new file mode 100644
index 000000000..68838aae9
--- /dev/null
+++ b/web/app/routes/api.analytics.ts
@@ -0,0 +1,621 @@
+import { type ActionFunctionArgs, type LoaderFunctionArgs, data } from 'react-router'
+
+import {
+ getSessionsServer,
+ getErrorsServer,
+ getFeatureFlagStatsServer,
+ getFeatureFlagProfilesServer,
+ getGoalStatsServer,
+ getGoalChartServer,
+ getCaptchaDataServer,
+ getExperimentResultsServer,
+ getExperimentServer,
+ getGoalServer,
+ getProjectGoalsServer,
+ getProjectFeatureFlagsServer,
+ getProfilesServer,
+ getProfileServer,
+ getProfileSessionsServer,
+ getProjectServer,
+ getFiltersServer,
+ getErrorsFiltersServer,
+ getVersionFiltersServer,
+ getCustomEventsMetadataServer,
+ getPropertyMetadataServer,
+ getErrorSessionsServer,
+ getLiveVisitorsServer,
+ getLiveVisitorsInfoServer,
+ getProjectDataCustomEventsServer,
+ getUserFlowServer,
+ getGSCKeywordsServer,
+ getRevenueStatusServer,
+ getRevenueDataServer,
+ getOverallStatsServer,
+ type AnalyticsParams,
+ type AnalyticsFilter,
+ type SessionsResponse,
+ type ErrorsResponse,
+ type FeatureFlagStats,
+ type FeatureFlagProfilesResponse,
+ type GoalStats,
+ type GoalChartData,
+ type CaptchaDataResponse,
+ type ExperimentResults,
+ type Experiment,
+ type Goal,
+ type GoalsResponse,
+ type FeatureFlagsResponse,
+ type ProfilesResponse,
+ type ProfileDetailsResponse,
+ type ProfileSessionsResponse,
+ type Project,
+ type VersionFilter,
+ type CustomEventsMetadataResponse,
+ type PropertyMetadataResponse,
+ type ErrorSessionsResponse,
+ type LiveStats,
+ type LiveVisitorInfo,
+ type ProjectDataCustomEventsResponse,
+ type UserFlowResponse,
+ type GSCKeywordsResponse,
+ type RevenueStatus,
+ type RevenueDataResponse,
+ type OverallObject,
+} from '~/api/api.server'
+import { getProjectPasswordCookie } from '~/utils/session.server'
+
+interface ProxyRequest {
+ action:
+ | 'getSessions'
+ | 'getErrors'
+ | 'getFeatureFlagStats'
+ | 'getFeatureFlagProfiles'
+ | 'getGoalStats'
+ | 'getGoalChart'
+ | 'getCaptchaData'
+ | 'getExperimentResults'
+ | 'getExperiment'
+ | 'getGoal'
+ | 'getProjectGoals'
+ | 'getProjectFeatureFlags'
+ | 'getProfiles'
+ | 'getProfile'
+ | 'getProfileSessions'
+ | 'getProject'
+ | 'getFilters'
+ | 'getErrorsFilters'
+ | 'getVersionFilters'
+ | 'getCustomEventsMetadata'
+ | 'getPropertyMetadata'
+ | 'getErrorSessions'
+ | 'getLiveVisitors'
+ | 'getLiveVisitorsInfo'
+ | 'getProjectDataCustomEvents'
+ | 'getUserFlow'
+ | 'getGSCKeywords'
+ | 'getRevenueStatus'
+ | 'getRevenueData'
+ | 'getOverallStats'
+ projectId: string
+ pids?: string[]
+ flagId?: string
+ goalId?: string
+ experimentId?: string
+ profileId?: string
+ errorId?: string
+ filterType?: string
+ filterColumn?: 'br' | 'os'
+ dataType?: 'traffic' | 'errors'
+ event?: string
+ property?: string
+ customEvents?: string[]
+ params: {
+ timeBucket?: string
+ period?: string
+ from?: string
+ to?: string
+ timezone?: string
+ filters?: AnalyticsFilter[]
+ take?: number
+ skip?: number
+ options?: Record<string, unknown>
+ resultFilter?: string
+ search?: string
+ profileType?: 'all' | 'anonymous' | 'identified'
+ }
+}
+
+interface ProxyResponse<T> {
+ data: T | null
+ error: string | null
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const body = (await request.json()) as ProxyRequest
+
+ const { action, projectId, pids, params } = body
+
+ const password = getProjectPasswordCookie(request, projectId)
+
+ const analyticsParams: AnalyticsParams & { take?: number; skip?: number; options?: Record<string, unknown> } = {
+ timeBucket: params.timeBucket || 'day',
+ period: params.period || '7d',
+ from: params.from,
+ to: params.to,
+ timezone: params.timezone || 'UTC',
+ filters: params.filters || [],
+ password: password || undefined,
+ take: params.take,
+ skip: params.skip,
+ }
+
+ try {
+ switch (action) {
+ case 'getSessions': {
+ const result = await getSessionsServer(request, projectId, analyticsParams)
+ return data<ProxyResponse<SessionsResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getErrors': {
+ const errorsParams = { ...analyticsParams, options: params.options }
+ const result = await getErrorsServer(request, projectId, errorsParams)
+ return data<ProxyResponse<ErrorsResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getFeatureFlagStats': {
+ if (!body.flagId) {
+ return data<ProxyResponse<null>>({ data: null, error: 'flagId is required' }, { status: 400 })
+ }
+ const result = await getFeatureFlagStatsServer(
+ request,
+ body.flagId,
+ params.period || '7d',
+ params.from || '',
+ params.to || '',
+ params.timezone,
+ )
+ return data<ProxyResponse<FeatureFlagStats>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getFeatureFlagProfiles': {
+ if (!body.flagId) {
+ return data<ProxyResponse<null>>({ data: null, error: 'flagId is required' }, { status: 400 })
+ }
+ const result = await getFeatureFlagProfilesServer(
+ request,
+ body.flagId,
+ params.period || '7d',
+ params.from || '',
+ params.to || '',
+ params.timezone,
+ params.take || 15,
+ params.skip || 0,
+ params.resultFilter,
+ )
+ return data<ProxyResponse<FeatureFlagProfilesResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getGoalStats': {
+ if (!body.goalId) {
+ return data<ProxyResponse<null>>({ data: null, error: 'goalId is required' }, { status: 400 })
+ }
+ const result = await getGoalStatsServer(
+ request,
+ body.goalId,
+ params.period || '7d',
+ params.from || '',
+ params.to || '',
+ params.timezone,
+ )
+ return data<ProxyResponse<GoalStats>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getGoalChart': {
+ if (!body.goalId) {
+ return data<ProxyResponse<null>>({ data: null, error: 'goalId is required' }, { status: 400 })
+ }
+ const result = await getGoalChartServer(
+ request,
+ body.goalId,
+ params.period || '7d',
+ params.from || '',
+ params.to || '',
+ params.timeBucket || 'day',
+ params.timezone,
+ )
+ return data<ProxyResponse<{ chart: GoalChartData }>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getCaptchaData': {
+ const result = await getCaptchaDataServer(
+ request,
+ projectId,
+ params.timeBucket || 'hour',
+ params.period || '3d',
+ params.filters || [],
+ params.from || '',
+ params.to || '',
+ password || undefined,
+ )
+ return data<ProxyResponse<CaptchaDataResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getExperimentResults': {
+ if (!body.experimentId) {
+ return data<ProxyResponse<null>>({ data: null, error: 'experimentId is required' }, { status: 400 })
+ }
+ const result = await getExperimentResultsServer(
+ request,
+ body.experimentId,
+ params.period || '7d',
+ params.timeBucket || 'day',
+ params.from || '',
+ params.to || '',
+ params.timezone,
+ )
+ return data<ProxyResponse<ExperimentResults>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getExperiment': {
+ if (!body.experimentId) {
+ return data<ProxyResponse<null>>({ data: null, error: 'experimentId is required' }, { status: 400 })
+ }
+ const result = await getExperimentServer(request, body.experimentId)
+ return data<ProxyResponse<Experiment>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getGoal': {
+ if (!body.goalId) {
+ return data<ProxyResponse<null>>({ data: null, error: 'goalId is required' }, { status: 400 })
+ }
+ const result = await getGoalServer(request, body.goalId)
+ return data<ProxyResponse<Goal>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getProjectGoals': {
+ const result = await getProjectGoalsServer(
+ request,
+ projectId,
+ params.take || 100,
+ params.skip || 0,
+ params.search,
+ )
+ return data<ProxyResponse<GoalsResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getProjectFeatureFlags': {
+ const result = await getProjectFeatureFlagsServer(
+ request,
+ projectId,
+ params.take || 100,
+ params.skip || 0,
+ params.search,
+ )
+ return data<ProxyResponse<FeatureFlagsResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getProfiles': {
+ const result = await getProfilesServer(
+ request,
+ projectId,
+ params.period || '3d',
+ params.filters || [],
+ params.from || '',
+ params.to || '',
+ params.take || 30,
+ params.skip || 0,
+ params.timezone || '',
+ params.profileType || 'all',
+ password || undefined,
+ )
+ return data<ProxyResponse<ProfilesResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getProfile': {
+ if (!body.profileId) {
+ return data<ProxyResponse<null>>({ data: null, error: 'profileId is required' }, { status: 400 })
+ }
+ const result = await getProfileServer(
+ request,
+ projectId,
+ body.profileId,
+ params.period || '7d',
+ params.from || '',
+ params.to || '',
+ params.timezone || '',
+ password || undefined,
+ )
+ return data<ProxyResponse<ProfileDetailsResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getProfileSessions': {
+ if (!body.profileId) {
+ return data<ProxyResponse<null>>({ data: null, error: 'profileId is required' }, { status: 400 })
+ }
+ const result = await getProfileSessionsServer(
+ request,
+ projectId,
+ body.profileId,
+ params.period || '3d',
+ params.filters || [],
+ params.from || '',
+ params.to || '',
+ params.take || 30,
+ params.skip || 0,
+ params.timezone || '',
+ password || undefined,
+ )
+ return data<ProxyResponse<ProfileSessionsResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getProject': {
+ const result = await getProjectServer(request, projectId, password || undefined)
+ return data<ProxyResponse<Project>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getFilters': {
+ if (!body.filterType) {
+ return data<ProxyResponse<null>>({ data: null, error: 'filterType is required' }, { status: 400 })
+ }
+ const result = await getFiltersServer(request, projectId, body.filterType, password || undefined)
+ return data<ProxyResponse<string[]>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getErrorsFilters': {
+ if (!body.filterType) {
+ return data<ProxyResponse<null>>({ data: null, error: 'filterType is required' }, { status: 400 })
+ }
+ const result = await getErrorsFiltersServer(request, projectId, body.filterType, password || undefined)
+ return data<ProxyResponse<string[]>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getVersionFilters': {
+ if (!body.filterColumn || !body.dataType) {
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'filterColumn and dataType are required' },
+ { status: 400 },
+ )
+ }
+ const result = await getVersionFiltersServer(
+ request,
+ projectId,
+ body.dataType,
+ body.filterColumn,
+ password || undefined,
+ )
+ return data<ProxyResponse<VersionFilter[]>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getCustomEventsMetadata': {
+ if (!body.event) {
+ return data<ProxyResponse<null>>({ data: null, error: 'event is required' }, { status: 400 })
+ }
+ const result = await getCustomEventsMetadataServer(request, projectId, body.event, {
+ timeBucket: params.timeBucket,
+ period: params.period,
+ from: params.from,
+ to: params.to,
+ timezone: params.timezone,
+ password: password || undefined,
+ })
+ return data<ProxyResponse<CustomEventsMetadataResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getPropertyMetadata': {
+ if (!body.property) {
+ return data<ProxyResponse<null>>({ data: null, error: 'property is required' }, { status: 400 })
+ }
+ const result = await getPropertyMetadataServer(request, projectId, body.property, {
+ timeBucket: params.timeBucket,
+ period: params.period,
+ from: params.from,
+ to: params.to,
+ filters: params.filters,
+ timezone: params.timezone,
+ password: password || undefined,
+ })
+ return data<ProxyResponse<PropertyMetadataResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getErrorSessions': {
+ if (!body.errorId) {
+ return data<ProxyResponse<null>>({ data: null, error: 'errorId is required' }, { status: 400 })
+ }
+ const result = await getErrorSessionsServer(request, projectId, body.errorId, {
+ timeBucket: params.timeBucket,
+ period: params.period,
+ from: params.from,
+ to: params.to,
+ take: params.take,
+ skip: params.skip,
+ password: password || undefined,
+ })
+ return data<ProxyResponse<ErrorSessionsResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getLiveVisitors': {
+ const pids = body.pids || [projectId]
+ const result = await getLiveVisitorsServer(request, pids, password || undefined)
+ return data<ProxyResponse<LiveStats>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getLiveVisitorsInfo': {
+ const result = await getLiveVisitorsInfoServer(request, projectId, password || undefined)
+ return data<ProxyResponse<LiveVisitorInfo[]>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getProjectDataCustomEvents': {
+ const result = await getProjectDataCustomEventsServer(request, projectId, {
+ timeBucket: params.timeBucket,
+ period: params.period,
+ filters: params.filters,
+ from: params.from,
+ to: params.to,
+ timezone: params.timezone,
+ customEvents: body.customEvents,
+ password: password || undefined,
+ })
+ return data<ProxyResponse<ProjectDataCustomEventsResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getUserFlow': {
+ const result = await getUserFlowServer(request, projectId, {
+ timeBucket: params.timeBucket,
+ period: params.period,
+ filters: params.filters,
+ from: params.from,
+ to: params.to,
+ timezone: params.timezone,
+ password: password || undefined,
+ })
+ return data<ProxyResponse<UserFlowResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getGSCKeywords': {
+ const result = await getGSCKeywordsServer(request, projectId, {
+ period: params.period,
+ from: params.from,
+ to: params.to,
+ timezone: params.timezone,
+ password: password || undefined,
+ })
+ return data<ProxyResponse<GSCKeywordsResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getRevenueStatus': {
+ const result = await getRevenueStatusServer(request, projectId)
+ return data<ProxyResponse<RevenueStatus>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getRevenueData': {
+ const result = await getRevenueDataServer(request, projectId, {
+ period: params.period || '7d',
+ from: params.from,
+ to: params.to,
+ timezone: params.timezone,
+ timeBucket: params.timeBucket,
+ })
+ return data<ProxyResponse<RevenueDataResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getOverallStats': {
+ if (!pids || pids.length === 0) {
+ return data<ProxyResponse<null>>({ data: null, error: 'pids is required' }, { status: 400 })
+ }
+ const result = await getOverallStatsServer(request, pids, {
+ timeBucket: params.timeBucket || 'day',
+ period: params.period || '7d',
+ from: params.from,
+ to: params.to,
+ timezone: params.timezone || 'UTC',
+ filters: params.filters || [],
+ includeChart: true,
+ })
+ return data<ProxyResponse<Record<string, OverallObject>>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ default:
+ return data<ProxyResponse<null>>({ data: null, error: `Unknown action: ${action}` }, { status: 400 })
+ }
+ } catch (error) {
+ console.error('[api.analytics] Proxy request failed:', error)
+ return data<ProxyResponse<null>>(
+ { data: null, error: error instanceof Error ? error.message : 'Unknown error' },
+ { status: 500 },
+ )
+ }
+}
+
+export async function loader({ request: _request }: LoaderFunctionArgs) {
+ return data({ error: 'Use POST method' }, { status: 405 })
+}
diff --git a/web/app/routes/api.auth.ts b/web/app/routes/api.auth.ts
new file mode 100644
index 000000000..fffd0e44c
--- /dev/null
+++ b/web/app/routes/api.auth.ts
@@ -0,0 +1,154 @@
+import { type ActionFunctionArgs, type LoaderFunctionArgs, data } from 'react-router'
+
+import {
+ generateSSOAuthURLServer,
+ getJWTBySSOHashServer,
+ processSSOTokenCommunityEditionServer,
+ linkBySSOHashServer,
+ processSSOTokenServer,
+ processGSCTokenServer,
+ authMeServer,
+ type SSOProvider,
+ type SSOAuthURLResponse,
+ type SSOHashResponse,
+ type AuthMeResponse,
+} from '~/api/api.server'
+import { createAuthCookies } from '~/utils/session.server'
+
+interface ProxyRequest {
+ action:
+ | 'generateSSOAuthURL'
+ | 'getJWTBySSOHash'
+ | 'processSSOTokenCommunityEdition'
+ | 'linkBySSOHash'
+ | 'processSSOToken'
+ | 'processGSCToken'
+ | 'authMe'
+ provider?: SSOProvider
+ redirectUrl?: string
+ hash?: string
+ token?: string
+ code?: string
+ state?: string
+ remember?: boolean
+}
+
+interface ProxyResponse<T> {
+ data: T | null
+ error: string | null
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const body = (await request.json()) as ProxyRequest
+ const { action } = body
+
+ try {
+ switch (action) {
+ case 'generateSSOAuthURL': {
+ if (!body.provider) {
+ return data<ProxyResponse<null>>({ data: null, error: 'provider is required' }, { status: 400 })
+ }
+ const result = await generateSSOAuthURLServer(request, body.provider, body.redirectUrl)
+ return data<ProxyResponse<SSOAuthURLResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'getJWTBySSOHash': {
+ if (!body.hash || !body.provider) {
+ return data<ProxyResponse<null>>({ data: null, error: 'hash and provider are required' }, { status: 400 })
+ }
+ const result = await getJWTBySSOHashServer(request, body.hash, body.provider)
+
+ if (result.data) {
+ const { accessToken, refreshToken } = result.data
+ const cookies = createAuthCookies({ accessToken, refreshToken }, body.remember ?? false)
+
+ return data<ProxyResponse<SSOHashResponse>>(
+ {
+ data: result.data,
+ error: null,
+ },
+ {
+ headers: cookies.map((cookie) => ['Set-Cookie', cookie]) as [string, string][],
+ },
+ )
+ }
+
+ return data<ProxyResponse<SSOHashResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'processSSOTokenCommunityEdition': {
+ if (!body.code || !body.hash || !body.redirectUrl) {
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'code, hash, and redirectUrl are required' },
+ { status: 400 },
+ )
+ }
+ const result = await processSSOTokenCommunityEditionServer(request, body.code, body.hash, body.redirectUrl)
+ return data<ProxyResponse<unknown>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'linkBySSOHash': {
+ if (!body.hash || !body.provider) {
+ return data<ProxyResponse<null>>({ data: null, error: 'hash and provider are required' }, { status: 400 })
+ }
+ const result = await linkBySSOHashServer(request, body.hash, body.provider)
+ return data<ProxyResponse<unknown>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'processSSOToken': {
+ if (!body.token || !body.hash) {
+ return data<ProxyResponse<null>>({ data: null, error: 'token and hash are required' }, { status: 400 })
+ }
+ const result = await processSSOTokenServer(request, body.token, body.hash)
+ return data<ProxyResponse<unknown>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'processGSCToken': {
+ if (!body.code || !body.state) {
+ return data<ProxyResponse<null>>({ data: null, error: 'code and state are required' }, { status: 400 })
+ }
+ const result = await processGSCTokenServer(request, body.code, body.state)
+ return data<ProxyResponse<{ pid: string }>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ case 'authMe': {
+ const result = await authMeServer(request)
+ return data<ProxyResponse<AuthMeResponse>>({
+ data: result.data,
+ error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ })
+ }
+
+ default:
+ return data<ProxyResponse<null>>({ data: null, error: `Unknown action: ${action}` }, { status: 400 })
+ }
+ } catch (error) {
+ console.error('[api.auth] Proxy request failed:', error)
+ return data<ProxyResponse<null>>(
+ { data: null, error: error instanceof Error ? error.message : 'Unknown error' },
+ { status: 500 },
+ )
+ }
+}
+
+export async function loader({ request: _request }: LoaderFunctionArgs) {
+ return data({ error: 'Use POST method' }, { status: 405 })
+}
diff --git a/web/app/routes/billing.tsx b/web/app/routes/billing.tsx
index ecc5ed8d5..d4dc1b75a 100644
--- a/web/app/routes/billing.tsx
+++ b/web/app/routes/billing.tsx
@@ -1,19 +1,111 @@
-import { redirect } from 'react-router'
+import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, data } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { serverFetch } from '~/api/api.server'
import { isSelfhosted } from '~/lib/constants'
+import { Metainfo } from '~/lib/models/Metainfo'
+import { UsageInfo } from '~/lib/models/Usageinfo'
import Billing from '~/pages/Billing'
+import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export async function loader() {
+export interface BillingLoaderData {
+ metainfo: Metainfo | null
+ usageInfo: UsageInfo | null
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
if (isSelfhosted) {
return redirect('/login', 302)
}
- return null
+ redirectIfNotAuthenticated(request)
+
+ const [metainfoResult, usageInfoResult] = await Promise.all([
+ serverFetch<Metainfo>(request, 'user/metainfo'),
+ serverFetch<UsageInfo>(request, 'user/usageinfo'),
+ ])
+
+ const cookies = [...metainfoResult.cookies, ...usageInfoResult.cookies]
+
+ return data<BillingLoaderData>(
+ {
+ metainfo: metainfoResult.data,
+ usageInfo: usageInfoResult.data,
+ },
+ { headers: createHeadersWithCookies(cookies) },
+ )
+}
+
+export interface BillingActionData {
+ success?: boolean
+ intent?: string
+ error?: string
+ data?: unknown
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ redirectIfNotAuthenticated(request)
+
+ const formData = await request.formData()
+ const intent = formData.get('intent')?.toString()
+
+ switch (intent) {
+ case 'preview-subscription-update': {
+ const planId = Number(formData.get('planId'))
+
+ const result = await serverFetch(request, 'user/preview-plan', {
+ method: 'POST',
+ body: { planId },
+ })
+
+ if (result.error) {
+ return data<BillingActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<BillingActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'change-subscription-plan': {
+ const planId = Number(formData.get('planId'))
+
+ const result = await serverFetch(request, 'user/change-plan', {
+ method: 'POST',
+ body: { planId },
+ })
+
+ if (result.error) {
+ return data<BillingActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<BillingActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-metainfo': {
+ const result = await serverFetch<Metainfo>(request, 'user/metainfo')
+
+ if (result.error) {
+ return data<BillingActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<BillingActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ default:
+ return data<BillingActionData>({ error: 'Unknown action' }, { status: 400 })
+ }
}
export default function BillingRoute() {
diff --git a/web/app/routes/blog.$category.$slug.tsx b/web/app/routes/blog.$category.$slug.tsx
index 54384fcdc..024061dcf 100644
--- a/web/app/routes/blog.$category.$slug.tsx
+++ b/web/app/routes/blog.$category.$slug.tsx
@@ -1,9 +1,9 @@
-import type { LoaderFunction, MetaFunction } from 'react-router'
+import type { LoaderFunctionArgs, MetaFunction } from 'react-router'
import { redirect, data } from 'react-router'
import { isSelfhosted, getOgImageUrl, isDisableMarketingPages } from '~/lib/constants'
import Post from '~/pages/Blog/Post'
-import { getPost } from '~/utils/getPosts'
+import { getPost } from '~/utils/getPosts.server'
import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
export const meta: MetaFunction = (loaderData: any) => {
@@ -16,7 +16,7 @@ export const meta: MetaFunction = (loaderData: any) => {
]
}
-export const loader: LoaderFunction = async ({ params }) => {
+export async function loader({ request, params }: LoaderFunctionArgs) {
if (isSelfhosted || isDisableMarketingPages) {
return redirect('/dashboard', 302)
}
@@ -29,7 +29,7 @@ export const loader: LoaderFunction = async ({ params }) => {
})
}
- const post = await getPost(slug, category)
+ const post = await getPost(request, slug, category)
if (!post) {
return data(null, {
diff --git a/web/app/routes/blog.$slug.tsx b/web/app/routes/blog.$slug.tsx
index 5e2c51f1b..e30b9204e 100644
--- a/web/app/routes/blog.$slug.tsx
+++ b/web/app/routes/blog.$slug.tsx
@@ -2,13 +2,13 @@ import _isString from 'lodash/isString'
import _last from 'lodash/last'
import _map from 'lodash/map'
import { redirect, data } from 'react-router'
-import type { LoaderFunction, MetaFunction } from 'react-router'
+import type { LoaderFunctionArgs, MetaFunction } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
-import { getSitemap } from '~/api'
-import { isSelfhosted, getOgImageUrl, isDisableMarketingPages } from '~/lib/constants'
+import { isSelfhosted, getOgImageUrl, isDisableMarketingPages, API_URL } from '~/lib/constants'
import Post from '~/pages/Blog/Post'
-import { getPost, getSlugFromFilename, getDateFromFilename } from '~/utils/getPosts'
+import { getSlugFromFilename, getDateFromFilename } from '~/utils/blog'
+import { getPost } from '~/utils/getPosts.server'
import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
export const meta: MetaFunction = (loaderData: any) => {
@@ -21,9 +21,10 @@ export const meta: MetaFunction = (loaderData: any) => {
]
}
-// @ts-expect-error SitemapFunction does not support async, investigate it later
+// @ts-expect-error
export const sitemap: SitemapFunction = async () => {
- const files = await getSitemap()
+ const response = await fetch(`${API_URL}v1/blog/sitemap`)
+ const files = await response.json()
if (isSelfhosted || isDisableMarketingPages) {
return {
@@ -36,7 +37,6 @@ export const sitemap: SitemapFunction = async () => {
let date: string
if (_isString(file)) {
- // Standalone post in root - just the filename (e.g., "2025-05-31-data-policy")
handle = getSlugFromFilename(file)
date = getDateFromFilename(file)
} else {
@@ -44,18 +44,13 @@ export const sitemap: SitemapFunction = async () => {
const firstElement = file[0]
if (firstElement === 'blog') {
- // Blog posts: ["blog", "filename"] or ["blog", "category", "filename"]
if (file.length === 2) {
- // ["blog", "filename"] - blog post in root
handle = `blog/${getSlugFromFilename(_file)}`
} else {
- // ["blog", "category", "filename"] - blog post in subdirectory
const category = file[1]
handle = `blog/${category}/${getSlugFromFilename(_file)}`
}
} else {
- // Standalone post in category folder: ["category", "filename"]
- // e.g., ["comparison", "2025-11-26-plausible"] -> /comparison/plausible
handle = `${firstElement}/${getSlugFromFilename(_file)}`
}
@@ -70,7 +65,7 @@ export const sitemap: SitemapFunction = async () => {
})
}
-export const loader: LoaderFunction = async ({ params }) => {
+export async function loader({ request, params }: LoaderFunctionArgs) {
if (isSelfhosted || isDisableMarketingPages) {
return redirect('/dashboard', 302)
}
@@ -81,7 +76,7 @@ export const loader: LoaderFunction = async ({ params }) => {
})
}
- const post = await getPost(params.slug)
+ const post = await getPost(request, params.slug)
if (!post) {
return data(null, {
diff --git a/web/app/routes/blog._index.tsx b/web/app/routes/blog._index.tsx
index 1b74702f6..5393e7834 100644
--- a/web/app/routes/blog._index.tsx
+++ b/web/app/routes/blog._index.tsx
@@ -2,25 +2,19 @@ import _filter from 'lodash/filter'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import { ChevronRightIcon } from 'lucide-react'
-import type { LoaderFunction, MetaFunction } from 'react-router'
+import type { LoaderFunctionArgs, MetaFunction } from 'react-router'
import { redirect, Link, useLoaderData } from 'react-router'
-import { getBlogPosts } from '~/api'
+import { getBlogPosts } from '~/api/api.server'
import { isDisableMarketingPages, isSelfhosted } from '~/lib/constants'
import { getTitle } from '~/utils/seo'
-export const loader: LoaderFunction = async () => {
+export async function loader({ request }: LoaderFunctionArgs) {
if (isSelfhosted || isDisableMarketingPages) {
return redirect('/dashboard', 302)
}
- const data = await getBlogPosts()
- .then((data) => {
- return data
- })
- .catch((error) => {
- console.error(error)
- })
+ const data = await getBlogPosts(request)
if (!data || _isEmpty(data)) {
return null
diff --git a/web/app/routes/change-email.$id.tsx b/web/app/routes/change-email.$id.tsx
index f586a2336..ff4c12181 100644
--- a/web/app/routes/change-email.$id.tsx
+++ b/web/app/routes/change-email.$id.tsx
@@ -1,27 +1,70 @@
-import type { HeadersFunction } from 'react-router'
-import { redirect } from 'react-router'
+import type { HeadersFunction, LoaderFunctionArgs } from 'react-router'
+import { redirect, useLoaderData } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { serverFetch } from '~/api/api.server'
import { isSelfhosted } from '~/lib/constants'
-import ChangeEmail from '~/pages/Auth/ChangeEmail'
+import StatusPage from '~/ui/StatusPage'
+import routes from '~/utils/routes'
export const headers: HeadersFunction = ({ parentHeaders }) => {
parentHeaders.set('X-Frame-Options', 'DENY')
return parentHeaders
}
-export async function loader() {
+export const sitemap: SitemapFunction = () => ({
+ exclude: true,
+})
+
+export interface ChangeEmailLoaderData {
+ success: boolean
+ error?: string
+}
+
+export async function loader({ request, params }: LoaderFunctionArgs): Promise<ChangeEmailLoaderData | Response> {
if (isSelfhosted) {
return redirect('/login', 302)
}
- return null
+ const { id } = params
+
+ if (!id) {
+ return { success: false, error: 'Invalid verification link' }
+ }
+
+ const result = await serverFetch(request, `v1/auth/change-email/confirm/${id}`, {
+ skipAuth: true,
+ })
+
+ if (result.error) {
+ const errorMessage = typeof result.error === 'string' ? result.error : 'Verification failed'
+ return { success: false, error: errorMessage }
+ }
+
+ return { success: true }
}
-export const sitemap: SitemapFunction = () => ({
- exclude: true,
-})
+export default function ChangeEmailRoute() {
+ const data = useLoaderData<ChangeEmailLoaderData>()
+
+ if (data.error) {
+ return (
+ <StatusPage
+ type='error'
+ title={data.error}
+ actions={[
+ { label: 'Dashboard', to: routes.dashboard, primary: true },
+ { label: 'Support', to: routes.contact },
+ ]}
+ />
+ )
+ }
-export default function Index() {
- return <ChangeEmail />
+ return (
+ <StatusPage
+ type='success'
+ title='Email changed successfully'
+ actions={[{ label: 'Dashboard', to: routes.dashboard, primary: true }]}
+ />
+ )
}
diff --git a/web/app/routes/dashboard.tsx b/web/app/routes/dashboard.tsx
index f099a7a41..dcc727e54 100644
--- a/web/app/routes/dashboard.tsx
+++ b/web/app/routes/dashboard.tsx
@@ -1,17 +1,174 @@
-import type { LoaderFunction } from 'react-router'
+import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router'
+import { data } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { serverFetch } from '~/api/api.server'
+import { Project } from '~/lib/models/Project'
import Dashboard from '~/pages/Dashboard'
+import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export const loader: LoaderFunction = async ({ request }) => {
+export interface DashboardLoaderData {
+ viewMode: 'grid' | 'list'
+ projects: {
+ results: Project[]
+ total: number
+ page_total: number
+ } | null
+}
+
+export interface DashboardActionData {
+ success?: boolean
+ intent?: string
+ error?: string
+ fieldErrors?: {
+ name?: string
+ }
+ project?: Project
+ isPinned?: boolean
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ redirectIfNotAuthenticated(request)
+
+ const formData = await request.formData()
+ const intent = formData.get('intent')?.toString()
+
+ switch (intent) {
+ case 'create-project': {
+ const name = formData.get('name')?.toString() || ''
+ const organisationId = formData.get('organisationId')?.toString()
+
+ if (!name.trim()) {
+ return data<DashboardActionData>({ intent, fieldErrors: { name: 'Project name is required' } }, { status: 400 })
+ }
+
+ if (name.length > 50) {
+ return data<DashboardActionData>(
+ { intent, fieldErrors: { name: 'Project name must be 50 characters or less' } },
+ { status: 400 },
+ )
+ }
+
+ const body: { name: string; organisationId?: string } = { name: name.trim() }
+ if (organisationId) body.organisationId = organisationId
+
+ const result = await serverFetch<Project>(request, 'project', {
+ method: 'POST',
+ body,
+ })
+
+ if (result.error) {
+ return data<DashboardActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<DashboardActionData>(
+ { intent, success: true, project: result.data as Project },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'pin-project': {
+ const projectId = formData.get('projectId')?.toString()
+
+ if (!projectId) {
+ return data<DashboardActionData>({ intent, error: 'Project ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `project/${projectId}/pin`, {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<DashboardActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<DashboardActionData>(
+ { intent, success: true, isPinned: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'unpin-project': {
+ const projectId = formData.get('projectId')?.toString()
+
+ if (!projectId) {
+ return data<DashboardActionData>({ intent, error: 'Project ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `project/${projectId}/pin`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<DashboardActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<DashboardActionData>(
+ { intent, success: true, isPinned: false },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'accept-project-share': {
+ const shareId = formData.get('shareId')?.toString()
+
+ if (!shareId) {
+ return data<DashboardActionData>({ intent, error: 'Share ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `user/share/${shareId}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<DashboardActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<DashboardActionData>({ intent, success: true }, { headers: createHeadersWithCookies(result.cookies) })
+ }
+
+ default:
+ return data<DashboardActionData>({ error: 'Unknown action' }, { status: 400 })
+ }
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ redirectIfNotAuthenticated(request)
+
+ const url = new URL(request.url)
+ const page = parseInt(url.searchParams.get('page') || '1', 10)
+ const pageSize = parseInt(url.searchParams.get('pageSize') || '12', 10)
+ const search = url.searchParams.get('search') || ''
+ const period = url.searchParams.get('period') || '7d'
+ const sort = url.searchParams.get('sort') || 'alpha_asc'
+
+ const skip = (page - 1) * pageSize
+
const cookieHeader = request.headers.get('Cookie')
const viewMode = (cookieHeader?.match(/(?<=dashboard_view=)[^;]*/)?.[0] as 'grid' | 'list') || 'grid'
- return { viewMode }
+ const projectsResult = await serverFetch<{
+ results: Project[]
+ total: number
+ page_total: number
+ }>(request, `/project?take=${pageSize}&skip=${skip}&search=${search}&period=${period}&sort=${sort}`)
+
+ const loaderData: DashboardLoaderData = {
+ viewMode,
+ projects: projectsResult.data,
+ }
+
+ if (projectsResult.cookies.length > 0) {
+ return data(loaderData, {
+ headers: createHeadersWithCookies(projectsResult.cookies),
+ })
+ }
+
+ return loaderData
}
export default function DashboardPage() {
diff --git a/web/app/routes/gsc-connected.tsx b/web/app/routes/gsc-connected.tsx
index 65ebd3074..04d79c0fb 100644
--- a/web/app/routes/gsc-connected.tsx
+++ b/web/app/routes/gsc-connected.tsx
@@ -1,86 +1,142 @@
import _replace from 'lodash/replace'
import { useEffect, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { redirect, useNavigate } from 'react-router'
+import type { LoaderFunctionArgs } from 'react-router'
+import { redirect, useLoaderData, useNavigate } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
-import { processGSCToken } from '~/api'
+import { serverFetch } from '~/api/api.server'
+import { useAuthProxy } from '~/hooks/useAuthProxy'
import { isSelfhosted } from '~/lib/constants'
import StatusPage from '~/ui/StatusPage'
import routes from '~/utils/routes'
-export async function loader() {
+export const sitemap: SitemapFunction = () => ({
+ exclude: true,
+})
+
+export interface GscConnectedLoaderData {
+ error?: string
+ useClientFallback?: boolean
+}
+
+export async function loader({ request }: LoaderFunctionArgs): Promise<GscConnectedLoaderData | Response> {
if (isSelfhosted) {
return redirect('/login', 302)
}
- return null
+ const url = new URL(request.url)
+
+ // Google sometimes redirects with hash instead of query params
+ // The hash won't be available server-side, so we need client-side fallback
+ const state = url.searchParams.get('state')
+ const code = url.searchParams.get('code')
+
+ if (!state || !code) {
+ // If params are missing, it might be in the hash - need client-side handling
+ return { useClientFallback: true }
+ }
+
+ const result = await serverFetch<{ pid: string }>(request, 'v1/project/gsc/process-token', {
+ method: 'POST',
+ body: { code, state },
+ })
+
+ // If auth fails (401/403), fall back to client-side which has localStorage tokens
+ if (result.status === 401 || result.status === 403) {
+ return { useClientFallback: true }
+ }
+
+ if (result.error || !result.data) {
+ // For other errors, also try client-side as a fallback
+ // This handles cases where server-side cookies aren't synced with localStorage
+ return { useClientFallback: true }
+ }
+
+ const { pid } = result.data
+ const redirectUrl = _replace(routes.project_settings, ':id', pid)
+
+ return redirect(`${redirectUrl}?tab=integrations`)
}
-export const sitemap: SitemapFunction = () => ({
- exclude: true,
-})
+export default function GscConnectedRoute() {
+ const data = useLoaderData<GscConnectedLoaderData>()
-export default function GscConnected() {
- const { t } = useTranslation('common')
+ // Always use client-side handler when loader indicates fallback
+ if (data.useClientFallback) {
+ return <GscHashHandler />
+ }
+
+ // This shouldn't be reached normally, but handle edge cases
+ return (
+ <StatusPage
+ type='error'
+ title='Failed to connect Google Search Console'
+ description={data.error || 'Unknown error'}
+ actions={[{ label: 'Support', to: routes.contact }]}
+ />
+ )
+}
+
+function GscHashHandler() {
const navigate = useNavigate()
- const [loading, setLoading] = useState(true)
- const [isError, setIsError] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const { processGSCToken } = useAuthProxy()
+ const [{ state, code }] = useState(() => {
+ if (typeof window === 'undefined') return { state: null, code: null }
+ // Fix Google's hash URL redirect (sometimes Google uses # instead of ?)
+ const _location = _replace(window.location.href, `${routes.gsc_connected}#`, `${routes.gsc_connected}?`)
+ const { searchParams } = new URL(_location)
+ return {
+ state: searchParams.get('state'),
+ code: searchParams.get('code'),
+ }
+ })
useEffect(() => {
- // For some reason, Google redirects to a hash URL, let's fix it
- const _location = _replace(window.location.href, `${routes.gsc_connected}#`, `${routes.gsc_connected}?`)
+ if (!state || !code) return
- const { searchParams } = new URL(_location)
- const state = searchParams.get('state')
- const code = searchParams.get('code')
-
- // Prevent duplicate callback processing in React 18 StrictMode (dev) or other double-invocation scenarios
- const processedKey = state ? `gsc_processed:${state}` : null
- if (processedKey && sessionStorage.getItem(processedKey) === '1') {
- // eslint-disable-next-line react-hooks/set-state-in-effect -- Checking sessionStorage for duplicate processing
- setLoading(false)
+ // Prevent duplicate processing in React StrictMode or on refresh
+ const processedKey = `gsc_processed:${state}`
+ if (sessionStorage.getItem(processedKey) === '1') {
return
}
+ sessionStorage.setItem(processedKey, '1')
- const processCode = async () => {
- if (!state || !code) {
- setIsError(true)
- return
- }
-
- try {
- const { pid } = await processGSCToken(code, state)
+ processGSCToken(code, state)
+ .then(({ pid }) => {
navigate({
pathname: _replace(routes.project_settings, ':id', pid),
search: new URLSearchParams({ tab: 'integrations' }).toString(),
})
- } catch (reason) {
- setIsError(true)
- setLoading(false)
+ })
+ .catch((reason) => {
+ sessionStorage.removeItem(processedKey)
+ setError(String(reason))
console.error(`[ERROR] Error while processing GSC integration: ${reason}`)
- }
- }
-
- setLoading(true)
+ })
+ }, [navigate, state, code, processGSCToken])
- processCode()
- }, [navigate])
-
- if (loading) {
- return <StatusPage loading />
+ if (!state || !code) {
+ return (
+ <StatusPage
+ type='error'
+ title='Failed to connect Google Search Console'
+ description='Invalid callback parameters'
+ actions={[{ label: 'Support', to: routes.contact }]}
+ />
+ )
}
- if (isError) {
+ if (error) {
return (
<StatusPage
type='error'
- title={t('gsc.failed')}
- description={t('gsc.failedDesc')}
- actions={[{ label: t('notFoundPage.support'), to: routes.contact }]}
+ title='Failed to connect Google Search Console'
+ description={error}
+ actions={[{ label: 'Support', to: routes.contact }]}
/>
)
}
- return null
+ return <StatusPage loading />
}
diff --git a/web/app/routes/login.tsx b/web/app/routes/login.tsx
index b8d6dfb72..dc53a4e2d 100644
--- a/web/app/routes/login.tsx
+++ b/web/app/routes/login.tsx
@@ -1,12 +1,124 @@
-import type { HeadersFunction } from 'react-router'
+import type { ActionFunctionArgs, HeadersFunction, LoaderFunctionArgs } from 'react-router'
+import { redirect, data } from 'react-router'
+import { getAuthenticatedUser, loginUser, serverFetch } from '~/api/api.server'
import Signin from '~/pages/Auth/Signin'
+import { createHeadersWithCookies, createAuthCookies } from '~/utils/session.server'
export const headers: HeadersFunction = ({ parentHeaders }) => {
parentHeaders.set('X-Frame-Options', 'DENY')
return parentHeaders
}
+export async function loader({ request }: LoaderFunctionArgs) {
+ const authResult = await getAuthenticatedUser(request)
+
+ if (authResult) {
+ if (!authResult.user.user.hasCompletedOnboarding) {
+ return redirect('/onboarding')
+ }
+ return redirect('/dashboard')
+ }
+
+ return null
+}
+
+export interface LoginActionData {
+ error?: string | string[]
+ requires2FA?: boolean
+ twoFASuccess?: boolean
+ fieldErrors?: {
+ email?: string
+ password?: string
+ twoFACode?: string
+ }
+ timestamp?: number
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const formData = await request.formData()
+ const intent = formData.get('intent')?.toString()
+
+ // Handle 2FA submission
+ if (intent === 'submit-2fa') {
+ const twoFactorAuthenticationCode = formData.get('twoFACode')?.toString() || ''
+ const dontRemember = formData.get('dontRemember') === 'true'
+
+ if (!twoFactorAuthenticationCode || twoFactorAuthenticationCode.length !== 6) {
+ return data<LoginActionData>(
+ { fieldErrors: { twoFACode: 'Please enter a valid 6-digit code' }, timestamp: Date.now() },
+ { status: 400 },
+ )
+ }
+
+ const result = await serverFetch<{
+ accessToken: string
+ refreshToken: string
+ user: { hasCompletedOnboarding: boolean }
+ }>(request, '2fa/authenticate', {
+ method: 'POST',
+ body: { twoFactorAuthenticationCode },
+ })
+
+ if (result.error) {
+ return data<LoginActionData>(
+ { fieldErrors: { twoFACode: 'Invalid 2FA code' }, timestamp: Date.now() },
+ { status: 400 },
+ )
+ }
+
+ const { accessToken, refreshToken, user } = result.data!
+ const cookies = createAuthCookies({ accessToken, refreshToken }, !dontRemember)
+
+ const redirectTo = user.hasCompletedOnboarding ? '/dashboard' : '/onboarding'
+
+ return redirect(redirectTo, {
+ headers: createHeadersWithCookies(cookies),
+ })
+ }
+
+ // Handle regular login
+ const email = formData.get('email')?.toString() || ''
+ const password = formData.get('password')?.toString() || ''
+ const dontRemember = formData.get('dontRemember') === 'true'
+
+ const fieldErrors: LoginActionData['fieldErrors'] = {}
+
+ if (!email || !email.includes('@')) {
+ fieldErrors.email = 'Please enter a valid email address'
+ }
+
+ if (!password || password.length < 8) {
+ fieldErrors.password = 'Password must be at least 8 characters'
+ }
+
+ if (fieldErrors.email || fieldErrors.password) {
+ return data({ fieldErrors, timestamp: Date.now() }, { status: 400 })
+ }
+
+ const result = await loginUser(request, { email, password }, !dontRemember)
+
+ if (!result.success) {
+ return data({ error: result.error, timestamp: Date.now() }, { status: 400 })
+ }
+
+ if (result.requires2FA) {
+ return data(
+ { requires2FA: true },
+ {
+ status: 200,
+ headers: createHeadersWithCookies(result.cookies),
+ },
+ )
+ }
+
+ const redirectTo = result.data?.user.hasCompletedOnboarding ? '/dashboard' : '/onboarding'
+
+ return redirect(redirectTo, {
+ headers: createHeadersWithCookies(result.cookies),
+ })
+}
+
export default function SigninRoute() {
return <Signin />
}
diff --git a/web/app/routes/logout.tsx b/web/app/routes/logout.tsx
new file mode 100644
index 000000000..d3e3a96d5
--- /dev/null
+++ b/web/app/routes/logout.tsx
@@ -0,0 +1,32 @@
+import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router'
+import { redirect } from 'react-router'
+
+import { logoutUser } from '~/api/api.server'
+import { createHeadersWithCookies } from '~/utils/session.server'
+
+function getLogoutAllParam(request: Request): boolean {
+ const url = new URL(request.url)
+ return url.searchParams.get('logoutAll') === 'true'
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const logoutAll = getLogoutAllParam(request)
+ const { cookies } = await logoutUser(request, { logoutAll })
+
+ return redirect('/login', {
+ headers: createHeadersWithCookies(cookies),
+ })
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const logoutAll = getLogoutAllParam(request)
+ const { cookies } = await logoutUser(request, { logoutAll })
+
+ return redirect('/login', {
+ headers: createHeadersWithCookies(cookies),
+ })
+}
+
+export default function LogoutRoute() {
+ return null
+}
diff --git a/web/app/routes/onboarding.tsx b/web/app/routes/onboarding.tsx
index 1ebcb2989..878b39fd5 100644
--- a/web/app/routes/onboarding.tsx
+++ b/web/app/routes/onboarding.tsx
@@ -1,7 +1,12 @@
-import type { MetaFunction } from 'react-router'
+import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from 'react-router'
+import { data } from 'react-router'
import { SitemapFunction } from 'remix-sitemap'
+import { getAuthenticatedUser, serverFetch } from '~/api/api.server'
+import { Project } from '~/lib/models/Project'
+import { User } from '~/lib/models/User'
import Onboarding from '~/pages/Onboarding'
+import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
@@ -14,6 +19,149 @@ export const meta: MetaFunction = () => {
]
}
+export interface OnboardingLoaderData {
+ project: Project | null
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ redirectIfNotAuthenticated(request)
+
+ const authResult = await getAuthenticatedUser(request)
+ const user = authResult?.user
+ const cookies: string[] = authResult?.cookies || []
+
+ if (user?.user?.onboardingStep === 'setup_tracking' || user?.user?.onboardingStep === 'waiting_for_events') {
+ const projectsResult = await serverFetch<{
+ results: Project[]
+ total: number
+ }>(request, '/project?take=1&skip=0')
+
+ const project = projectsResult.data?.results?.[0] || null
+ const allCookies = [...cookies, ...projectsResult.cookies]
+
+ const loaderData: OnboardingLoaderData = { project }
+
+ if (allCookies.length > 0) {
+ return data(loaderData, {
+ headers: createHeadersWithCookies(allCookies),
+ })
+ }
+
+ return loaderData
+ }
+
+ if (cookies.length > 0) {
+ return data({ project: null } as OnboardingLoaderData, {
+ headers: createHeadersWithCookies(cookies),
+ })
+ }
+
+ return { project: null } as OnboardingLoaderData
+}
+
+export interface OnboardingActionData {
+ success?: boolean
+ intent?: string
+ error?: string
+ fieldErrors?: {
+ name?: string
+ }
+ project?: Project
+ user?: User
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ redirectIfNotAuthenticated(request)
+
+ const formData = await request.formData()
+ const intent = formData.get('intent')?.toString()
+
+ switch (intent) {
+ case 'create-project': {
+ const name = formData.get('name')?.toString() || ''
+
+ if (!name.trim()) {
+ return data<OnboardingActionData>(
+ { intent, fieldErrors: { name: 'Project name is required' } },
+ { status: 400 },
+ )
+ }
+
+ if (name.length > 50) {
+ return data<OnboardingActionData>(
+ { intent, fieldErrors: { name: 'Project name must be 50 characters or less' } },
+ { status: 400 },
+ )
+ }
+
+ const result = await serverFetch<Project>(request, 'project', {
+ method: 'POST',
+ body: { name },
+ })
+
+ if (result.error) {
+ return data<OnboardingActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OnboardingActionData>(
+ { intent, success: true, project: result.data as Project },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-step': {
+ const step = formData.get('step')?.toString() || ''
+
+ const result = await serverFetch<User>(request, 'user/onboarding/step', {
+ method: 'POST',
+ body: { step },
+ })
+
+ if (result.error) {
+ return data<OnboardingActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OnboardingActionData>(
+ { intent, success: true, user: result.data as User },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'complete-onboarding': {
+ const result = await serverFetch<User>(request, 'user/onboarding/complete', {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<OnboardingActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OnboardingActionData>(
+ { intent, success: true, user: result.data as User },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-account': {
+ const result = await serverFetch(request, 'user', {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<OnboardingActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OnboardingActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ default:
+ return data<OnboardingActionData>({ error: 'Unknown action' }, { status: 400 })
+ }
+}
+
export default function OnboardingRoute() {
return <Onboarding />
}
diff --git a/web/app/routes/open.tsx b/web/app/routes/open.tsx
index 587fee438..84fd91d28 100644
--- a/web/app/routes/open.tsx
+++ b/web/app/routes/open.tsx
@@ -1,7 +1,7 @@
-import { redirect } from 'react-router'
-import type { LinksFunction } from 'react-router'
+import { redirect, type LoaderFunctionArgs, useLoaderData, LinksFunction } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { getGeneralStats } from '~/api/api.server'
import { isDisableMarketingPages, isSelfhosted } from '~/lib/constants'
import OpenStartup from '~/pages/OpenStartup'
import Style from '~/styles/ProjectViewStyle.css?url'
@@ -15,14 +15,18 @@ export const sitemap: SitemapFunction = () => ({
exclude: isSelfhosted || isDisableMarketingPages,
})
-export async function loader() {
+export async function loader({ request }: LoaderFunctionArgs) {
if (isSelfhosted || isDisableMarketingPages) {
return redirect('/login', 302)
}
- return null
+ const stats = await getGeneralStats(request)
+
+ return { stats }
}
export default function Index() {
- return <OpenStartup />
+ const { stats } = useLoaderData<typeof loader>()
+
+ return <OpenStartup stats={stats} />
}
diff --git a/web/app/routes/organisation.invite.$id.tsx b/web/app/routes/organisation.invite.$id.tsx
index 0dff39cbb..677792879 100644
--- a/web/app/routes/organisation.invite.$id.tsx
+++ b/web/app/routes/organisation.invite.$id.tsx
@@ -1,51 +1,50 @@
-import { useEffect, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { useParams } from 'react-router'
+import type { LoaderFunctionArgs } from 'react-router'
+import { useLoaderData } from 'react-router'
+import type { SitemapFunction } from 'remix-sitemap'
-import { acceptOrganisationInvitation } from '~/api'
+import { serverFetch } from '~/api/api.server'
import StatusPage from '~/ui/StatusPage'
import routes from '~/utils/routes'
-export default function ConfirmOrganisationInvitation() {
- const { t } = useTranslation('common')
- const { id } = useParams()
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState<string | null>(null)
-
- useEffect(() => {
- setLoading(true)
-
- if (!id) {
- setError(t('common.error'))
- setLoading(false)
- return
- }
-
- const acceptInvitation = async () => {
- try {
- await acceptOrganisationInvitation(id)
- } catch (reason) {
- setError(typeof reason === 'string' ? reason : t('apiNotifications.acceptOrganisationInvitationError'))
- } finally {
- setLoading(false)
- }
- }
-
- acceptInvitation()
- }, [id]) // eslint-disable-line
-
- if (loading) {
- return <StatusPage loading />
+export const sitemap: SitemapFunction = () => ({
+ exclude: true,
+})
+
+export interface OrganisationInviteLoaderData {
+ success: boolean
+ error?: string
+}
+
+export async function loader({ request, params }: LoaderFunctionArgs): Promise<OrganisationInviteLoaderData> {
+ const { id } = params
+
+ if (!id) {
+ return { success: false, error: 'Invalid invitation link' }
+ }
+
+ const result = await serverFetch(request, `/user/organisation/${id}`, {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ const errorMessage = typeof result.error === 'string' ? result.error : 'Failed to accept invitation'
+ return { success: false, error: errorMessage }
}
- if (error) {
+ return { success: true }
+}
+
+export default function OrganisationInviteRoute() {
+ const data = useLoaderData<OrganisationInviteLoaderData>()
+
+ if (data.error) {
return (
<StatusPage
type='error'
- title={error}
+ title={data.error}
actions={[
- { label: t('common.dashboard'), to: routes.dashboard, primary: true },
- { label: t('notFoundPage.support'), to: routes.contact },
+ { label: 'Dashboard', to: routes.dashboard, primary: true },
+ { label: 'Support', to: routes.contact },
]}
/>
)
@@ -54,8 +53,8 @@ export default function ConfirmOrganisationInvitation() {
return (
<StatusPage
type='success'
- title={t('apiNotifications.acceptOrganisationInvitation')}
- actions={[{ label: t('common.dashboard'), to: routes.dashboard, primary: true }]}
+ title='Organisation invitation accepted'
+ actions={[{ label: 'Dashboard', to: routes.dashboard, primary: true }]}
/>
)
}
diff --git a/web/app/routes/organisations.$id.tsx b/web/app/routes/organisations.$id.tsx
index fac9422d6..f0fc455e7 100644
--- a/web/app/routes/organisations.$id.tsx
+++ b/web/app/routes/organisations.$id.tsx
@@ -1,19 +1,256 @@
-import { redirect } from 'react-router'
+import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router'
+import { data, redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { serverFetch } from '~/api/api.server'
import { isSelfhosted } from '~/lib/constants'
+import { DetailedOrganisation } from '~/lib/models/Organisation'
import OrganisationSettings from '~/pages/Organisations/Settings'
+import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export async function loader() {
+export interface OrganisationLoaderData {
+ organisation: DetailedOrganisation | null
+ error?: string
+}
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ if (isSelfhosted) {
+ return redirect('/login', 302)
+ }
+
+ redirectIfNotAuthenticated(request)
+
+ const { id } = params
+
+ const result = await serverFetch<DetailedOrganisation>(request, `organisation/${id}`)
+
+ if (result.error) {
+ return data<OrganisationLoaderData>(
+ { organisation: null, error: result.error as string },
+ { status: result.status, headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ return data<OrganisationLoaderData>(
+ { organisation: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+}
+
+interface AvailableProject {
+ id: string
+ name: string
+ uiHidden?: boolean
+}
+
+interface AvailableProjectsResponse {
+ results: AvailableProject[]
+ total: number
+}
+
+export interface OrganisationSettingsActionData {
+ success?: boolean
+ intent?: string
+ error?: string
+ fieldErrors?: {
+ name?: string
+ email?: string
+ }
+ organisation?: DetailedOrganisation
+ availableProjects?: AvailableProjectsResponse
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
if (isSelfhosted) {
return redirect('/login', 302)
}
- return null
+ redirectIfNotAuthenticated(request)
+
+ const { id } = params
+ const formData = await request.formData()
+ const intent = formData.get('intent')?.toString()
+
+ switch (intent) {
+ case 'update-organisation': {
+ const name = formData.get('name')?.toString() || ''
+
+ if (!name.trim()) {
+ return data<OrganisationSettingsActionData>(
+ { intent, fieldErrors: { name: 'Organisation name is required' } },
+ { status: 400 },
+ )
+ }
+
+ if (name.length > 50) {
+ return data<OrganisationSettingsActionData>(
+ { intent, fieldErrors: { name: 'Organisation name must be 50 characters or less' } },
+ { status: 400 },
+ )
+ }
+
+ const result = await serverFetch<DetailedOrganisation>(request, `organisation/${id}`, {
+ method: 'PATCH',
+ body: { name: name.trim() },
+ })
+
+ if (result.error) {
+ return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OrganisationSettingsActionData>(
+ { intent, success: true, organisation: result.data as DetailedOrganisation },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-organisation': {
+ const result = await serverFetch(request, `organisation/${id}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OrganisationSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'invite-member': {
+ const email = formData.get('email')?.toString() || ''
+ const role = formData.get('role')?.toString() || 'viewer'
+
+ if (!email || !email.includes('@')) {
+ return data<OrganisationSettingsActionData>(
+ { intent, fieldErrors: { email: 'Please enter a valid email address' } },
+ { status: 400 },
+ )
+ }
+
+ const result = await serverFetch(request, `organisation/${id}/invite`, {
+ method: 'POST',
+ body: { email, role },
+ })
+
+ if (result.error) {
+ return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OrganisationSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'remove-member': {
+ const memberId = formData.get('memberId')?.toString()
+
+ const result = await serverFetch(request, `organisation/member/${memberId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OrganisationSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-member-role': {
+ const memberId = formData.get('memberId')?.toString()
+ const role = formData.get('role')?.toString()
+
+ const result = await serverFetch(request, `organisation/member/${memberId}`, {
+ method: 'PATCH',
+ body: { role },
+ })
+
+ if (result.error) {
+ return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OrganisationSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'add-project': {
+ const projectId = formData.get('projectId')?.toString()
+
+ if (!projectId) {
+ return data<OrganisationSettingsActionData>({ intent, error: 'Project ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `project/organisation/${id}`, {
+ method: 'POST',
+ body: { projectId },
+ })
+
+ if (result.error) {
+ return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OrganisationSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'remove-project': {
+ const projectId = formData.get('projectId')?.toString()
+
+ if (!projectId) {
+ return data<OrganisationSettingsActionData>({ intent, error: 'Project ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `project/organisation/${id}/${projectId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OrganisationSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-available-projects': {
+ const take = parseInt(formData.get('take')?.toString() || '5', 10)
+ const skip = parseInt(formData.get('skip')?.toString() || '0', 10)
+ const search = formData.get('search')?.toString() || ''
+
+ const result = await serverFetch<AvailableProjectsResponse>(
+ request,
+ `project/available-for-organisation?take=${take}&skip=${skip}&search=${encodeURIComponent(search)}`,
+ )
+
+ if (result.error) {
+ return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OrganisationSettingsActionData>(
+ { intent, success: true, availableProjects: result.data as AvailableProjectsResponse },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ default:
+ return data<OrganisationSettingsActionData>({ error: 'Unknown action' }, { status: 400 })
+ }
}
export default function Index() {
diff --git a/web/app/routes/organisations._index.tsx b/web/app/routes/organisations._index.tsx
index 1b3fbee36..808d08df3 100644
--- a/web/app/routes/organisations._index.tsx
+++ b/web/app/routes/organisations._index.tsx
@@ -1,19 +1,163 @@
-import { redirect } from 'react-router'
+import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router'
+import { redirect, data } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
-import { isSelfhosted } from '~/lib/constants'
+import { serverFetch } from '~/api/api.server'
+import { ENTRIES_PER_PAGE_DASHBOARD, isSelfhosted } from '~/lib/constants'
+import { DetailedOrganisation } from '~/lib/models/Organisation'
import Organisations from '~/pages/Organisations'
+import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export async function loader() {
+interface OrganisationsResponse {
+ results: DetailedOrganisation[]
+ total: number
+}
+
+export interface OrganisationsLoaderData {
+ organisations: DetailedOrganisation[]
+ total: number
+ page: number
+ search: string
+ error?: string
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
if (isSelfhosted) {
return redirect('/login', 302)
}
- return null
+ redirectIfNotAuthenticated(request)
+
+ const url = new URL(request.url)
+ const page = parseInt(url.searchParams.get('page') || '1', 10)
+ const search = url.searchParams.get('search') || ''
+ const skip = (page - 1) * ENTRIES_PER_PAGE_DASHBOARD
+
+ const result = await serverFetch<OrganisationsResponse>(
+ request,
+ `organisation?take=${ENTRIES_PER_PAGE_DASHBOARD}&skip=${skip}&search=${encodeURIComponent(search)}`,
+ )
+
+ if (result.error) {
+ return data<OrganisationsLoaderData>(
+ { organisations: [], total: 0, page, search, error: result.error as string },
+ { status: 400, headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ return data<OrganisationsLoaderData>(
+ {
+ organisations: result.data?.results || [],
+ total: result.data?.total || 0,
+ page,
+ search,
+ },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+}
+
+export interface OrganisationsActionData {
+ success?: boolean
+ intent?: string
+ error?: string
+ fieldErrors?: {
+ name?: string
+ }
+ organisation?: DetailedOrganisation
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ if (isSelfhosted) {
+ return redirect('/login', 302)
+ }
+
+ redirectIfNotAuthenticated(request)
+
+ const formData = await request.formData()
+ const intent = formData.get('intent')?.toString()
+
+ switch (intent) {
+ case 'create-organisation': {
+ const name = formData.get('name')?.toString() || ''
+
+ if (!name.trim()) {
+ return data<OrganisationsActionData>(
+ { intent, fieldErrors: { name: 'Organisation name is required' } },
+ { status: 400 },
+ )
+ }
+
+ if (name.length > 50) {
+ return data<OrganisationsActionData>(
+ { intent, fieldErrors: { name: 'Organisation name must be 50 characters or less' } },
+ { status: 400 },
+ )
+ }
+
+ const result = await serverFetch<DetailedOrganisation>(request, 'organisation', {
+ method: 'POST',
+ body: { name: name.trim() },
+ })
+
+ if (result.error) {
+ return data<OrganisationsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OrganisationsActionData>(
+ { intent, success: true, organisation: result.data as DetailedOrganisation },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'accept-invitation': {
+ const membershipId = formData.get('membershipId')?.toString()
+
+ if (!membershipId) {
+ return data<OrganisationsActionData>({ intent, error: 'Membership ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `user/organisation/${membershipId}`, {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<OrganisationsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OrganisationsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'reject-invitation': {
+ const membershipId = formData.get('membershipId')?.toString()
+
+ if (!membershipId) {
+ return data<OrganisationsActionData>({ intent, error: 'Membership ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `user/organisation/${membershipId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<OrganisationsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<OrganisationsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ default:
+ return data<OrganisationsActionData>({ error: 'Unknown action' }, { status: 400 })
+ }
}
export default function Index() {
diff --git a/web/app/routes/password-reset.$id.tsx b/web/app/routes/password-reset.$id.tsx
index 7b4b3e1ac..76fdab618 100644
--- a/web/app/routes/password-reset.$id.tsx
+++ b/web/app/routes/password-reset.$id.tsx
@@ -1,7 +1,10 @@
-import type { HeadersFunction } from 'react-router'
+import type { ActionFunctionArgs, HeadersFunction } from 'react-router'
+import { data, redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { serverFetch } from '~/api/api.server'
import CreateNewPassword from '~/pages/Auth/CreateNewPassword'
+import { isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS } from '~/utils/validator'
export const headers: HeadersFunction = ({ parentHeaders }) => {
parentHeaders.set('X-Frame-Options', 'DENY')
@@ -12,6 +15,53 @@ export const sitemap: SitemapFunction = () => ({
exclude: true,
})
+export interface CreateNewPasswordActionData {
+ success?: boolean
+ error?: string
+ fieldErrors?: {
+ password?: string
+ repeat?: string
+ }
+ timestamp?: number
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { id } = params
+ const formData = await request.formData()
+ const password = formData.get('password')?.toString() || ''
+ const repeat = formData.get('repeat')?.toString() || ''
+
+ const fieldErrors: CreateNewPasswordActionData['fieldErrors'] = {}
+
+ if (!isValidPassword(password)) {
+ fieldErrors.password = `Password must be at least ${MIN_PASSWORD_CHARS} characters`
+ }
+
+ if (password.length > MAX_PASSWORD_CHARS) {
+ fieldErrors.password = `Password must be at most ${MAX_PASSWORD_CHARS} characters`
+ }
+
+ if (password !== repeat) {
+ fieldErrors.repeat = 'Passwords do not match'
+ }
+
+ if (fieldErrors.password || fieldErrors.repeat) {
+ return data<CreateNewPasswordActionData>({ fieldErrors, timestamp: Date.now() }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `v1/auth/reset-password/confirm/${id}`, {
+ method: 'POST',
+ body: { newPassword: password },
+ skipAuth: true,
+ })
+
+ if (result.error) {
+ return data<CreateNewPasswordActionData>({ error: result.error as string, timestamp: Date.now() }, { status: 400 })
+ }
+
+ return redirect('/login?password_updated=true')
+}
+
export default function Index() {
return <CreateNewPassword />
}
diff --git a/web/app/routes/project.transfer.cancel.tsx b/web/app/routes/project.transfer.cancel.tsx
index 5ee3cae60..4f8f93d2b 100644
--- a/web/app/routes/project.transfer.cancel.tsx
+++ b/web/app/routes/project.transfer.cancel.tsx
@@ -1,11 +1,61 @@
+import type { LoaderFunctionArgs } from 'react-router'
+import { useLoaderData } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
-import TransferProjectReject from '~/pages/Project/Settings/TransferProject/TransferProjectReject'
+import { serverFetch } from '~/api/api.server'
+import StatusPage from '~/ui/StatusPage'
+import routes from '~/utils/routes'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export default function Index() {
- return <TransferProjectReject />
+export interface TransferCancelLoaderData {
+ success: boolean
+ error?: string
+}
+
+export async function loader({ request }: LoaderFunctionArgs): Promise<TransferCancelLoaderData> {
+ const url = new URL(request.url)
+ const token = url.searchParams.get('token')
+
+ if (!token) {
+ return { success: false, error: 'Invalid or expired token' }
+ }
+
+ const result = await serverFetch(request, `project/transfer?token=${token}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ const errorMessage = typeof result.error === 'string' ? result.error : 'Invalid or expired token'
+ return { success: false, error: errorMessage }
+ }
+
+ return { success: true }
+}
+
+export default function TransferCancelRoute() {
+ const data = useLoaderData<TransferCancelLoaderData>()
+
+ if (data.error) {
+ return (
+ <StatusPage
+ type='error'
+ title={data.error}
+ actions={[
+ { label: 'Dashboard', to: routes.dashboard, primary: true },
+ { label: 'Support', to: routes.contact },
+ ]}
+ />
+ )
+ }
+
+ return (
+ <StatusPage
+ type='info'
+ title='Project transfer rejected'
+ actions={[{ label: 'Dashboard', to: routes.dashboard, primary: true }]}
+ />
+ )
}
diff --git a/web/app/routes/project.transfer.confirm.tsx b/web/app/routes/project.transfer.confirm.tsx
index 04c7083e1..727a29ba3 100644
--- a/web/app/routes/project.transfer.confirm.tsx
+++ b/web/app/routes/project.transfer.confirm.tsx
@@ -1,11 +1,59 @@
+import type { LoaderFunctionArgs } from 'react-router'
+import { useLoaderData } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
-import TransferProjectConfirm from '~/pages/Project/Settings/TransferProject/TransferProjectConfirm'
+import { serverFetch } from '~/api/api.server'
+import StatusPage from '~/ui/StatusPage'
+import routes from '~/utils/routes'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export default function Index() {
- return <TransferProjectConfirm />
+export interface TransferConfirmLoaderData {
+ success: boolean
+ error?: string
+}
+
+export async function loader({ request }: LoaderFunctionArgs): Promise<TransferConfirmLoaderData> {
+ const url = new URL(request.url)
+ const token = url.searchParams.get('token')
+
+ if (!token) {
+ return { success: false, error: 'Invalid or expired token' }
+ }
+
+ const result = await serverFetch(request, `project/transfer?token=${token}`)
+
+ if (result.error) {
+ const errorMessage = typeof result.error === 'string' ? result.error : 'Invalid or expired token'
+ return { success: false, error: errorMessage }
+ }
+
+ return { success: true }
+}
+
+export default function TransferConfirmRoute() {
+ const data = useLoaderData<TransferConfirmLoaderData>()
+
+ if (data.error) {
+ return (
+ <StatusPage
+ type='error'
+ title={data.error}
+ actions={[
+ { label: 'Dashboard', to: routes.dashboard, primary: true },
+ { label: 'Support', to: routes.contact },
+ ]}
+ />
+ )
+ }
+
+ return (
+ <StatusPage
+ type='success'
+ title='Project transfer accepted'
+ actions={[{ label: 'Dashboard', to: routes.dashboard, primary: true }]}
+ />
+ )
}
diff --git a/web/app/routes/projects.$id.subscribers.invite.tsx b/web/app/routes/projects.$id.subscribers.invite.tsx
index 54f60285c..608c88dec 100644
--- a/web/app/routes/projects.$id.subscribers.invite.tsx
+++ b/web/app/routes/projects.$id.subscribers.invite.tsx
@@ -1,5 +1,62 @@
-import ConfirmReportsShare from '~/pages/Project/Settings/Emails/ConfirmReportsShare'
+import type { LoaderFunctionArgs } from 'react-router'
+import { useLoaderData } from 'react-router'
+import type { SitemapFunction } from 'remix-sitemap'
-export default function Index() {
- return <ConfirmReportsShare />
+import { serverFetch } from '~/api/api.server'
+import StatusPage from '~/ui/StatusPage'
+import routes from '~/utils/routes'
+
+export const sitemap: SitemapFunction = () => ({
+ exclude: true,
+})
+
+export interface SubscriberInviteLoaderData {
+ success: boolean
+ error?: string
+}
+
+export async function loader({ request, params }: LoaderFunctionArgs): Promise<SubscriberInviteLoaderData> {
+ const { id } = params
+ const url = new URL(request.url)
+ const token = url.searchParams.get('token')
+
+ if (!id || !token) {
+ return { success: false, error: 'Invalid invitation link' }
+ }
+
+ const result = await serverFetch(request, `project/${id}/subscribers/invite?token=${token}`, {
+ skipAuth: true,
+ })
+
+ if (result.error) {
+ const errorMessage = typeof result.error === 'string' ? result.error : 'Invalid or expired token'
+ return { success: false, error: errorMessage }
+ }
+
+ return { success: true }
+}
+
+export default function SubscriberInviteRoute() {
+ const data = useLoaderData<SubscriberInviteLoaderData>()
+
+ if (data.error) {
+ return (
+ <StatusPage
+ type='error'
+ title={data.error}
+ actions={[
+ { label: 'Dashboard', to: routes.dashboard, primary: true },
+ { label: 'Support', to: routes.contact },
+ ]}
+ />
+ )
+ }
+
+ return (
+ <StatusPage
+ type='success'
+ title='Invitation accepted'
+ actions={[{ label: 'Dashboard', to: routes.dashboard, primary: true }]}
+ />
+ )
}
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index b838c9079..7c2d7a230 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -1,11 +1,53 @@
+import _includes from 'lodash/includes'
+import _some from 'lodash/some'
import _split from 'lodash/split'
-import { type LinksFunction, type MetaFunction } from 'react-router'
+import _startsWith from 'lodash/startsWith'
+import { type ActionFunctionArgs, type LinksFunction, type LoaderFunctionArgs, type MetaFunction } from 'react-router'
+import { data, redirect } from 'react-router'
+import {
+ serverFetch,
+ getProjectDataServer,
+ getOverallStatsServer,
+ getCustomEventsDataServer,
+ getPerfDataServer,
+ getPerformanceOverallStatsServer,
+ getSessionsServer,
+ getSessionServer,
+ getErrorsServer,
+ getErrorServer,
+ getErrorOverviewServer,
+ getProjectFeatureFlagsServer,
+ getProjectGoalsServer,
+ getProjectAlertsServer,
+ getFunnelDataServer,
+ type TrafficLogResponse,
+ type OverallObject,
+ type PerformanceDataResponse,
+ type PerformanceOverallObject,
+ type SessionsResponse,
+ type SessionDetailsResponse,
+ type ErrorsResponse,
+ type ErrorDetailsResponse,
+ type ErrorOverviewResponse,
+ type FeatureFlagsResponse,
+ type GoalsResponse,
+ type AlertsResponse,
+ type FunnelDataResponse,
+ type AnalyticsFilter,
+} from '~/api/api.server'
import { useRequiredParams } from '~/hooks/useRequiredParams'
-import { API_URL, MAIN_URL } from '~/lib/constants'
+import { API_URL, MAIN_URL, DEFAULT_TIMEZONE, PROJECT_TABS } from '~/lib/constants'
+import { Project } from '~/lib/models/Project'
import ViewProject from '~/pages/Project/View'
import { CurrentProjectProvider } from '~/providers/CurrentProjectProvider'
import ProjectViewStyle from '~/styles/ProjectViewStyle.css?url'
+import {
+ redirectIfNotAuthenticated,
+ createHeadersWithCookies,
+ getProjectPasswordCookie,
+ createProjectPasswordCookie,
+} from '~/utils/session.server'
export const links: LinksFunction = () => [{ rel: 'stylesheet', href: ProjectViewStyle }]
@@ -22,6 +64,1505 @@ export const meta: MetaFunction = ({ location }) => {
]
}
+const validFilters = [
+ 'host',
+ 'cc',
+ 'rg',
+ 'ct',
+ 'pg',
+ 'entryPage',
+ 'exitPage',
+ 'lc',
+ 'ref',
+ 'refn',
+ 'dv',
+ 'br',
+ 'brv',
+ 'os',
+ 'osv',
+ 'so',
+ 'me',
+ 'ca',
+ 'te',
+ 'co',
+ 'ev',
+ 'tag:key',
+ 'tag:value',
+ 'ev:key',
+ 'ev:value',
+]
+const validDynamicFilters = ['ev:key:', 'tag:key:']
+
+function isFilterValid(filter: string, checkDynamicFilters = false) {
+ let normalised = filter
+ if (_startsWith(normalised, '!') || _startsWith(normalised, '~') || _startsWith(normalised, '^')) {
+ normalised = normalised.substring(1)
+ }
+
+ if (_includes(validFilters, normalised)) {
+ return true
+ }
+
+ if (checkDynamicFilters && _some(validDynamicFilters, (prefix) => _startsWith(normalised, prefix))) {
+ return true
+ }
+
+ return false
+}
+
+function parseFiltersFromUrl(searchParams: URLSearchParams): AnalyticsFilter[] {
+ const filters: AnalyticsFilter[] = []
+
+ const entries = Array.from(searchParams.entries())
+
+ for (const [key, value] of entries) {
+ let actualColumn = key
+
+ let isExclusive = false
+ let isContains = false
+
+ if (key.startsWith('!')) {
+ isExclusive = true
+ actualColumn = key.substring(1)
+ } else if (key.startsWith('~')) {
+ isContains = true
+ actualColumn = key.substring(1)
+ } else if (key.startsWith('^')) {
+ isExclusive = true
+ isContains = true
+ actualColumn = key.substring(1)
+ }
+
+ if (!isFilterValid(actualColumn, true)) {
+ continue
+ }
+
+ filters.push({
+ column: actualColumn,
+ filter: value,
+ isExclusive: isExclusive,
+ isContains,
+ })
+ }
+
+ return filters
+}
+
+export interface ProjectLoaderData {
+ project: Project | null
+ isPasswordRequired: boolean
+ error?: string
+ // Traffic data
+ trafficData?: Promise<TrafficLogResponse | null>
+ overallStats?: Promise<Record<string, OverallObject> | null>
+ trafficCompareData?: Promise<TrafficLogResponse | null>
+ overallCompareStats?: Promise<Record<string, OverallObject> | null>
+ customEventsData?: Promise<{ chart?: { events?: Record<string, unknown> } } | null>
+ // Performance data
+ perfData?: Promise<PerformanceDataResponse | null>
+ perfOverallStats?: Promise<Record<string, PerformanceOverallObject> | null>
+ // Sessions data
+ sessionsData?: Promise<SessionsResponse | null>
+ sessionDetails?: Promise<SessionDetailsResponse | null>
+ // Errors data
+ errorsData?: Promise<ErrorsResponse | null>
+ errorDetails?: Promise<ErrorDetailsResponse | null>
+ errorOverview?: Promise<ErrorOverviewResponse | null>
+ // Feature Flags data
+ featureFlagsData?: Promise<FeatureFlagsResponse | null>
+ // Goals data
+ goalsData?: Promise<GoalsResponse | null>
+ // Alerts data
+ alertsData?: Promise<AlertsResponse | null>
+ // Funnels data
+ funnelData?: Promise<FunnelDataResponse | null>
+}
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { id: projectId } = params
+ const url = new URL(request.url)
+
+ const passwordFromQuery = url.searchParams.get('password') || ''
+ const passwordFromCookie = getProjectPasswordCookie(request, projectId || '')
+ const password = passwordFromQuery || passwordFromCookie
+
+ const result = await serverFetch<Project>(request, `project/${projectId}`, {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ })
+
+ if (result.error || !result.data) {
+ if (result.status === 404 || result.status === 403) {
+ return redirect('/dashboard')
+ }
+
+ return data<ProjectLoaderData>(
+ { project: null, isPasswordRequired: false, error: result.error as string },
+ { status: result.status, headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ const project = result.data
+
+ if (project.isPasswordProtected && !project.role && !password) {
+ return data<ProjectLoaderData>(
+ { project: null, isPasswordRequired: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ const cookies = [...result.cookies]
+ if (password && passwordFromQuery && password !== passwordFromCookie) {
+ cookies.push(createProjectPasswordCookie(projectId || '', password))
+ }
+
+ // Parse URL params for analytics data
+ const tab = (url.searchParams.get('tab') as keyof typeof PROJECT_TABS) || PROJECT_TABS.traffic
+ const period = url.searchParams.get('period') || '7d'
+ const timeBucket = url.searchParams.get('timeBucket') || 'day'
+ const from = url.searchParams.get('from') || ''
+ const to = url.searchParams.get('to') || ''
+ const timezone = url.searchParams.get('timezone') || DEFAULT_TIMEZONE
+ const filters = parseFiltersFromUrl(url.searchParams)
+
+ // Performance-specific params
+ const measure = url.searchParams.get('measure') || 'median'
+ const perfMetric = url.searchParams.get('perfMetric') || 'timing' // 'timing' or 'quantiles'
+
+ // Traffic compare params
+ const compareEnabled = url.searchParams.get('compare') === 'true'
+ const compareFrom = url.searchParams.get('compareFrom') || ''
+ const compareTo = url.searchParams.get('compareTo') || ''
+
+ // Traffic custom events params
+ const customEventsParam = url.searchParams.get('customEvents') || ''
+ const customEvents = customEventsParam ? customEventsParam.split(',').filter(Boolean) : []
+
+ const analyticsParams = {
+ timeBucket,
+ period,
+ filters,
+ from: from || undefined,
+ to: to || undefined,
+ timezone,
+ password: password || undefined,
+ }
+
+ // Initialize deferred data promises
+ let trafficData: Promise<TrafficLogResponse | null> | undefined
+ let overallStats: Promise<Record<string, OverallObject> | null> | undefined
+ let trafficCompareData: Promise<TrafficLogResponse | null> | undefined
+ let overallCompareStats: Promise<Record<string, OverallObject> | null> | undefined
+ let customEventsData: Promise<{ chart?: { events?: Record<string, unknown> } } | null> | undefined
+ let perfData: Promise<PerformanceDataResponse | null> | undefined
+ let perfOverallStats: Promise<Record<string, PerformanceOverallObject> | null> | undefined
+ let sessionsData: Promise<SessionsResponse | null> | undefined
+ let sessionDetails: Promise<SessionDetailsResponse | null> | undefined
+ let errorsData: Promise<ErrorsResponse | null> | undefined
+ let errorDetails: Promise<ErrorDetailsResponse | null> | undefined
+ let errorOverview: Promise<ErrorOverviewResponse | null> | undefined
+ let featureFlagsData: Promise<FeatureFlagsResponse | null> | undefined
+ let goalsData: Promise<GoalsResponse | null> | undefined
+ let alertsData: Promise<AlertsResponse | null> | undefined
+ let funnelData: Promise<FunnelDataResponse | null> | undefined
+
+ // Only fetch data if project is valid and not locked
+ if (project && !project.isLocked && projectId) {
+ if (tab === PROJECT_TABS.traffic) {
+ trafficData = getProjectDataServer(request, projectId, analyticsParams).then((res) => res.data)
+ overallStats = getOverallStatsServer(request, [projectId], analyticsParams).then((res) => res.data)
+
+ // Fetch compare data if enabled
+ if (compareEnabled && compareFrom && compareTo) {
+ const compareParams = {
+ ...analyticsParams,
+ period: 'custom' as const,
+ from: compareFrom,
+ to: compareTo,
+ }
+ trafficCompareData = getProjectDataServer(request, projectId, compareParams).then((res) => res.data)
+ overallCompareStats = getOverallStatsServer(request, [projectId], compareParams).then((res) => res.data)
+ }
+
+ // Fetch custom events data if any custom events are selected
+ if (customEvents.length > 0) {
+ customEventsData = getCustomEventsDataServer(request, projectId, analyticsParams, customEvents).then(
+ (res) => res.data,
+ )
+ }
+ } else if (tab === PROJECT_TABS.performance) {
+ // Use measure from URL, or 'quantiles' if perfMetric is quantiles
+ const effectiveMeasure = perfMetric === 'quantiles' ? 'quantiles' : measure
+ const perfParams = { ...analyticsParams, measure: effectiveMeasure }
+ perfData = getPerfDataServer(request, projectId, perfParams).then((res) => res.data)
+ perfOverallStats = getPerformanceOverallStatsServer(request, [projectId], perfParams).then((res) => res.data)
+ } else if (tab === PROJECT_TABS.sessions) {
+ sessionsData = getSessionsServer(request, projectId, analyticsParams).then((res) => res.data)
+ // Fetch session details if psid is in URL
+ const psid = url.searchParams.get('psid')
+ if (psid) {
+ sessionDetails = getSessionServer(request, projectId, psid, timezone, password || undefined).then(
+ (res) => res.data,
+ )
+ }
+ } else if (tab === PROJECT_TABS.errors) {
+ errorsData = getErrorsServer(request, projectId, analyticsParams).then((res) => res.data)
+ errorOverview = getErrorOverviewServer(request, projectId, analyticsParams).then((res) => res.data)
+ // Fetch error details if eid is in URL
+ const eid = url.searchParams.get('eid')
+ if (eid) {
+ errorDetails = getErrorServer(request, projectId, eid, analyticsParams).then((res) => res.data)
+ }
+ } else if (tab === PROJECT_TABS.featureFlags) {
+ featureFlagsData = getProjectFeatureFlagsServer(request, projectId).then((res) => res.data)
+ } else if (tab === PROJECT_TABS.goals) {
+ goalsData = getProjectGoalsServer(request, projectId).then((res) => res.data)
+ } else if (tab === PROJECT_TABS.alerts) {
+ alertsData = getProjectAlertsServer(request, projectId).then((res) => res.data)
+ } else if (tab === PROJECT_TABS.funnels) {
+ // Fetch funnel data if funnelId is in URL
+ const funnelId = url.searchParams.get('funnelId')
+ if (funnelId) {
+ const funnelFrom = from || ''
+ const funnelTo = to || ''
+ const funnelPeriod = period === 'custom' ? '' : period
+ funnelData = getFunnelDataServer(
+ request,
+ projectId,
+ funnelId,
+ funnelPeriod,
+ funnelFrom,
+ funnelTo,
+ timezone,
+ password || undefined,
+ ).then((res) => res.data)
+ }
+ }
+ }
+
+ return data<ProjectLoaderData>(
+ {
+ project,
+ isPasswordRequired: false,
+ trafficData,
+ overallStats,
+ trafficCompareData,
+ overallCompareStats,
+ customEventsData,
+ perfData,
+ perfOverallStats,
+ sessionsData,
+ sessionDetails,
+ errorsData,
+ errorDetails,
+ errorOverview,
+ featureFlagsData,
+ goalsData,
+ alertsData,
+ funnelData,
+ },
+ { headers: createHeadersWithCookies(cookies) },
+ )
+}
+
+export interface ProjectViewActionData {
+ success?: boolean
+ intent?: string
+ error?: string
+ data?: unknown
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ redirectIfNotAuthenticated(request)
+
+ const { id: projectId } = params
+ const formData = await request.formData()
+ const intent = formData.get('intent')?.toString()
+
+ switch (intent) {
+ // Goals
+ case 'create-goal': {
+ const name = formData.get('name')?.toString() || ''
+ const type = formData.get('type')?.toString() || 'pageview'
+ const matchType = formData.get('matchType')?.toString() || 'exact'
+ const value = formData.get('value')?.toString() || ''
+
+ const result = await serverFetch(request, 'goal', {
+ method: 'POST',
+ body: { pid: projectId, name, type, matchType, value },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-goal': {
+ const goalId = formData.get('goalId')?.toString()
+ const name = formData.get('name')?.toString()
+ const type = formData.get('type')?.toString()
+ const matchType = formData.get('matchType')?.toString()
+ const value = formData.get('value')?.toString()
+
+ const result = await serverFetch(request, `goal/${goalId}`, {
+ method: 'PUT',
+ body: { name, type, matchType, value },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-goal': {
+ const goalId = formData.get('goalId')?.toString()
+
+ const result = await serverFetch(request, `goal/${goalId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Funnels
+ case 'create-funnel': {
+ const name = formData.get('name')?.toString() || ''
+ const steps = JSON.parse(formData.get('steps')?.toString() || '[]')
+
+ const result = await serverFetch(request, 'project/funnel', {
+ method: 'POST',
+ body: { pid: projectId, name, steps },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-funnel': {
+ const funnelId = formData.get('funnelId')?.toString()
+ const name = formData.get('name')?.toString() || ''
+ const steps = JSON.parse(formData.get('steps')?.toString() || '[]')
+
+ const result = await serverFetch(request, 'project/funnel', {
+ method: 'PATCH',
+ body: { id: funnelId, pid: projectId, name, steps },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-funnel': {
+ const funnelId = formData.get('funnelId')?.toString()
+
+ const result = await serverFetch(request, `project/funnel/${funnelId}/${projectId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Alerts
+ case 'create-alert': {
+ const name = formData.get('name')?.toString() || ''
+ const queryMetric = formData.get('queryMetric')?.toString() || 'page_views'
+ const queryCondition = formData.get('queryCondition')?.toString() || null
+ const queryValue = formData.get('queryValue') ? Number(formData.get('queryValue')) : null
+ const queryTime = formData.get('queryTime')?.toString() || null
+ const queryCustomEvent = formData.get('queryCustomEvent')?.toString() || null
+ const alertOnNewErrorsOnly = formData.get('alertOnNewErrorsOnly') === 'true'
+ const alertOnEveryCustomEvent = formData.get('alertOnEveryCustomEvent') === 'true'
+
+ const result = await serverFetch(request, 'alert', {
+ method: 'POST',
+ body: {
+ pid: projectId,
+ name,
+ queryMetric,
+ queryCondition,
+ queryValue,
+ queryTime,
+ queryCustomEvent,
+ alertOnNewErrorsOnly,
+ alertOnEveryCustomEvent,
+ active: true,
+ },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-alert': {
+ const alertId = formData.get('alertId')?.toString()
+ const name = formData.get('name')?.toString()
+ const active = formData.get('active') === 'true'
+ const queryMetric = formData.get('queryMetric')?.toString()
+ const queryCondition = formData.get('queryCondition')?.toString() || null
+ const queryValue = formData.get('queryValue') ? Number(formData.get('queryValue')) : null
+ const queryTime = formData.get('queryTime')?.toString() || null
+ const queryCustomEvent = formData.get('queryCustomEvent')?.toString() || null
+ const alertOnNewErrorsOnly = formData.has('alertOnNewErrorsOnly')
+ ? formData.get('alertOnNewErrorsOnly') === 'true'
+ : undefined
+ const alertOnEveryCustomEvent = formData.has('alertOnEveryCustomEvent')
+ ? formData.get('alertOnEveryCustomEvent') === 'true'
+ : undefined
+
+ const body: Record<string, unknown> = {}
+ if (name !== undefined) body.name = name
+ body.active = active
+ if (queryMetric !== undefined) body.queryMetric = queryMetric
+ body.queryCondition = queryCondition
+ body.queryValue = queryValue
+ body.queryTime = queryTime
+ body.queryCustomEvent = queryCustomEvent
+ if (alertOnNewErrorsOnly !== undefined) body.alertOnNewErrorsOnly = alertOnNewErrorsOnly
+ if (alertOnEveryCustomEvent !== undefined) body.alertOnEveryCustomEvent = alertOnEveryCustomEvent
+
+ const result = await serverFetch(request, `alert/${alertId}`, {
+ method: 'PUT',
+ body,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-alert': {
+ const alertId = formData.get('alertId')?.toString()
+
+ const result = await serverFetch(request, `alert/${alertId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Annotations
+ case 'get-annotations': {
+ const password = formData.get('password')?.toString() || ''
+
+ const result = await serverFetch(request, `project/annotations/${projectId}`, {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'create-annotation': {
+ const date = formData.get('date')?.toString() || ''
+ const text = formData.get('text')?.toString() || ''
+
+ const result = await serverFetch(request, 'project/annotation', {
+ method: 'POST',
+ body: { pid: projectId, date, text },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-annotation': {
+ const annotationId = formData.get('annotationId')?.toString() || ''
+ const date = formData.get('date')?.toString() || ''
+ const text = formData.get('text')?.toString() || ''
+
+ const result = await serverFetch(request, 'project/annotation', {
+ method: 'PATCH',
+ body: { id: annotationId, pid: projectId, date, text },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-annotation': {
+ const annotationId = formData.get('annotationId')?.toString()
+
+ const result = await serverFetch(request, `project/annotation/${annotationId}/${projectId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Project Views
+ case 'get-project-views': {
+ const password = formData.get('password')?.toString() || ''
+
+ const result = await serverFetch(request, `project/${projectId}/views`, {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'create-project-view': {
+ const name = formData.get('name')?.toString() || ''
+ const type = formData.get('type')?.toString() || 'traffic'
+ const filters = JSON.parse(formData.get('filters')?.toString() || '[]')
+ const customEvents = JSON.parse(formData.get('customEvents')?.toString() || '[]')
+
+ const result = await serverFetch(request, `project/${projectId}/views`, {
+ method: 'POST',
+ body: { name, type, filters, customEvents },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-project-view': {
+ const viewId = formData.get('viewId')?.toString()
+ const name = formData.get('name')?.toString() || ''
+ const filters = JSON.parse(formData.get('filters')?.toString() || '[]')
+ const customEvents = JSON.parse(formData.get('customEvents')?.toString() || '[]')
+
+ const result = await serverFetch(request, `project/${projectId}/views/${viewId}`, {
+ method: 'PATCH',
+ body: { name, filters, customEvents },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-project-view': {
+ const viewId = formData.get('viewId')?.toString()
+
+ const result = await serverFetch(request, `project/${projectId}/views/${viewId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // AI Chat
+ case 'get-recent-ai-chats': {
+ const limit = Number(formData.get('limit') || '5')
+
+ const result = await serverFetch(request, `ai/${projectId}/chats?limit=${limit}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-all-ai-chats': {
+ const skip = Number(formData.get('skip') || '0')
+ const take = Number(formData.get('take') || '20')
+
+ const result = await serverFetch(request, `ai/${projectId}/chats/all?skip=${skip}&take=${take}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-ai-chat': {
+ const chatId = formData.get('chatId')?.toString()
+
+ const result = await serverFetch(request, `ai/${projectId}/chats/${chatId}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'create-ai-chat': {
+ const messages = JSON.parse(formData.get('messages')?.toString() || '[]')
+ const name = formData.get('name')?.toString()
+
+ const result = await serverFetch(request, `ai/${projectId}/chats`, {
+ method: 'POST',
+ body: { messages, name },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-ai-chat': {
+ const chatId = formData.get('chatId')?.toString()
+ const messages = formData.get('messages') ? JSON.parse(formData.get('messages')!.toString()) : undefined
+ const name = formData.get('name')?.toString()
+
+ const body: Record<string, unknown> = {}
+ if (messages) body.messages = messages
+ if (name !== undefined) body.name = name
+
+ const result = await serverFetch(request, `ai/${projectId}/chats/${chatId}`, {
+ method: 'POST',
+ body,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-ai-chat': {
+ const chatId = formData.get('chatId')?.toString()
+
+ const result = await serverFetch(request, `ai/${projectId}/chats/${chatId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Feature Flags
+ case 'get-project-feature-flags': {
+ const take = Number(formData.get('take') || '20')
+ const skip = Number(formData.get('skip') || '0')
+ const search = formData.get('search')?.toString() || ''
+
+ const params = new URLSearchParams({ take: String(take), skip: String(skip) })
+ if (search) params.append('search', search)
+
+ const result = await serverFetch(request, `feature-flag/project/${projectId}?${params.toString()}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-feature-flag': {
+ const flagId = formData.get('flagId')?.toString()
+
+ const result = await serverFetch(request, `feature-flag/${flagId}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'create-feature-flag': {
+ const key = formData.get('key')?.toString() || ''
+ const description = formData.get('description')?.toString() || ''
+ const flagType = formData.get('flagType')?.toString() || 'boolean'
+ const rolloutPercentage = Number(formData.get('rolloutPercentage') || '100')
+ const targetingRules = JSON.parse(formData.get('targetingRules')?.toString() || '[]')
+ const enabled = formData.get('enabled') === 'true'
+
+ const result = await serverFetch(request, 'feature-flag', {
+ method: 'POST',
+ body: { pid: projectId, key, description, flagType, rolloutPercentage, targetingRules, enabled },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-feature-flag': {
+ const flagId = formData.get('flagId')?.toString()
+ const key = formData.get('key')?.toString()
+ const description = formData.get('description')?.toString()
+ const flagType = formData.get('flagType')?.toString()
+ const rolloutPercentage = formData.get('rolloutPercentage')
+ ? Number(formData.get('rolloutPercentage'))
+ : undefined
+ const targetingRules = formData.get('targetingRules')
+ ? JSON.parse(formData.get('targetingRules')!.toString())
+ : undefined
+ const enabled = formData.has('enabled') ? formData.get('enabled') === 'true' : undefined
+
+ const body: Record<string, unknown> = {}
+ if (key !== undefined) body.key = key
+ if (description !== undefined) body.description = description
+ if (flagType !== undefined) body.flagType = flagType
+ if (rolloutPercentage !== undefined) body.rolloutPercentage = rolloutPercentage
+ if (targetingRules !== undefined) body.targetingRules = targetingRules
+ if (enabled !== undefined) body.enabled = enabled
+
+ const result = await serverFetch(request, `feature-flag/${flagId}`, {
+ method: 'PUT',
+ body,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-feature-flag': {
+ const flagId = formData.get('flagId')?.toString()
+
+ const result = await serverFetch(request, `feature-flag/${flagId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-feature-flag-stats': {
+ const flagId = formData.get('flagId')?.toString()
+ const period = formData.get('period')?.toString() || '7d'
+ const fromDate = formData.get('from')?.toString() || ''
+ const toDate = formData.get('to')?.toString() || ''
+ const tz = formData.get('timezone')?.toString() || ''
+
+ const params = new URLSearchParams({ period })
+ if (fromDate) params.append('from', fromDate)
+ if (toDate) params.append('to', toDate)
+ if (tz) params.append('timezone', tz)
+
+ const result = await serverFetch(request, `feature-flag/${flagId}/stats?${params.toString()}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: { flagId, stats: result.data } },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-feature-flag-profiles': {
+ const flagId = formData.get('flagId')?.toString()
+ const period = formData.get('period')?.toString() || '7d'
+ const fromDate = formData.get('from')?.toString() || ''
+ const toDate = formData.get('to')?.toString() || ''
+ const tz = formData.get('timezone')?.toString() || ''
+ const take = Number(formData.get('take') || '15')
+ const skip = Number(formData.get('skip') || '0')
+ const resultFilter = formData.get('result')?.toString() || ''
+
+ const params = new URLSearchParams({ period, take: String(take), skip: String(skip) })
+ if (fromDate) params.append('from', fromDate)
+ if (toDate) params.append('to', toDate)
+ if (tz) params.append('timezone', tz)
+ if (resultFilter && resultFilter !== 'all') params.append('result', resultFilter)
+
+ const result = await serverFetch(request, `feature-flag/${flagId}/profiles?${params.toString()}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ const profilesData = result.data as { profiles: unknown[]; total: number }
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: { flagId, profiles: profilesData.profiles, total: profilesData.total } },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Experiments
+ case 'get-project-experiments': {
+ const take = Number(formData.get('take') || '20')
+ const skip = Number(formData.get('skip') || '0')
+ const search = formData.get('search')?.toString() || ''
+
+ const params = new URLSearchParams({ take: String(take), skip: String(skip) })
+ if (search) params.append('search', search)
+
+ const result = await serverFetch(request, `experiment/project/${projectId}?${params.toString()}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-experiment': {
+ const experimentId = formData.get('experimentId')?.toString()
+
+ const result = await serverFetch(request, `experiment/${experimentId}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'create-experiment': {
+ const name = formData.get('name')?.toString() || ''
+ const description = formData.get('description')?.toString() || ''
+ const hypothesis = formData.get('hypothesis')?.toString() || ''
+ const exposureTrigger = formData.get('exposureTrigger')?.toString() || 'feature_flag'
+ const customEventName = formData.get('customEventName')?.toString() || ''
+ const multipleVariantHandling = formData.get('multipleVariantHandling')?.toString() || 'exclude'
+ const filterInternalUsers = formData.get('filterInternalUsers') === 'true'
+ const featureFlagMode = formData.get('featureFlagMode')?.toString() || 'create'
+ const featureFlagKey = formData.get('featureFlagKey')?.toString() || ''
+ const existingFeatureFlagId = formData.get('existingFeatureFlagId')?.toString() || ''
+ const goalId = formData.get('goalId')?.toString() || ''
+ const variants = JSON.parse(formData.get('variants')?.toString() || '[]')
+
+ const body: Record<string, unknown> = {
+ pid: projectId,
+ name,
+ variants,
+ }
+ if (description) body.description = description
+ if (hypothesis) body.hypothesis = hypothesis
+ if (exposureTrigger) body.exposureTrigger = exposureTrigger
+ if (customEventName) body.customEventName = customEventName
+ if (multipleVariantHandling) body.multipleVariantHandling = multipleVariantHandling
+ body.filterInternalUsers = filterInternalUsers
+ if (featureFlagMode) body.featureFlagMode = featureFlagMode
+ if (featureFlagKey) body.featureFlagKey = featureFlagKey
+ if (existingFeatureFlagId) body.existingFeatureFlagId = existingFeatureFlagId
+ if (goalId) body.goalId = goalId
+
+ const result = await serverFetch(request, 'experiment', {
+ method: 'POST',
+ body,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-experiment': {
+ const experimentId = formData.get('experimentId')?.toString()
+ const name = formData.get('name')?.toString()
+ const description = formData.get('description')?.toString()
+ const hypothesis = formData.get('hypothesis')?.toString()
+ const exposureTrigger = formData.get('exposureTrigger')?.toString()
+ const customEventName = formData.get('customEventName')?.toString()
+ const multipleVariantHandling = formData.get('multipleVariantHandling')?.toString()
+ const filterInternalUsers = formData.has('filterInternalUsers')
+ ? formData.get('filterInternalUsers') === 'true'
+ : undefined
+ const featureFlagMode = formData.get('featureFlagMode')?.toString()
+ const featureFlagKey = formData.get('featureFlagKey')?.toString()
+ const existingFeatureFlagId = formData.get('existingFeatureFlagId')?.toString()
+ const goalId = formData.get('goalId')?.toString()
+ const variants = formData.get('variants') ? JSON.parse(formData.get('variants')!.toString()) : undefined
+
+ const body: Record<string, unknown> = {}
+ if (name !== undefined) body.name = name
+ if (description !== undefined) body.description = description
+ if (hypothesis !== undefined) body.hypothesis = hypothesis
+ if (exposureTrigger !== undefined) body.exposureTrigger = exposureTrigger
+ if (customEventName !== undefined) body.customEventName = customEventName
+ if (multipleVariantHandling !== undefined) body.multipleVariantHandling = multipleVariantHandling
+ if (filterInternalUsers !== undefined) body.filterInternalUsers = filterInternalUsers
+ if (featureFlagMode !== undefined) body.featureFlagMode = featureFlagMode
+ if (featureFlagKey !== undefined) body.featureFlagKey = featureFlagKey
+ if (existingFeatureFlagId !== undefined) body.existingFeatureFlagId = existingFeatureFlagId
+ if (goalId !== undefined) body.goalId = goalId
+ if (variants !== undefined) body.variants = variants
+
+ const result = await serverFetch(request, `experiment/${experimentId}`, {
+ method: 'PUT',
+ body,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-experiment': {
+ const experimentId = formData.get('experimentId')?.toString()
+
+ const result = await serverFetch(request, `experiment/${experimentId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'start-experiment': {
+ const experimentId = formData.get('experimentId')?.toString()
+
+ const result = await serverFetch(request, `experiment/${experimentId}/start`, {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'pause-experiment': {
+ const experimentId = formData.get('experimentId')?.toString()
+
+ const result = await serverFetch(request, `experiment/${experimentId}/pause`, {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'complete-experiment': {
+ const experimentId = formData.get('experimentId')?.toString()
+
+ const result = await serverFetch(request, `experiment/${experimentId}/complete`, {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-experiment-results': {
+ const experimentId = formData.get('experimentId')?.toString()
+ const period = formData.get('period')?.toString() || '7d'
+ const timeBucket = formData.get('timeBucket')?.toString() || 'day'
+ const fromDate = formData.get('from')?.toString() || ''
+ const toDate = formData.get('to')?.toString() || ''
+ const tz = formData.get('timezone')?.toString() || ''
+
+ const params = new URLSearchParams({ period, timeBucket })
+ if (fromDate) params.append('from', fromDate)
+ if (toDate) params.append('to', toDate)
+ if (tz) params.append('timezone', tz)
+
+ const result = await serverFetch(request, `experiment/${experimentId}/results?${params.toString()}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Goals (getters)
+ case 'get-project-goals': {
+ const take = Number(formData.get('take') || '20')
+ const skip = Number(formData.get('skip') || '0')
+ const search = formData.get('search')?.toString() || ''
+
+ const params = new URLSearchParams({ take: String(take), skip: String(skip) })
+ if (search) params.append('search', search)
+
+ const result = await serverFetch(request, `goal/project/${projectId}?${params.toString()}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-goal': {
+ const goalId = formData.get('goalId')?.toString()
+
+ const result = await serverFetch(request, `goal/${goalId}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-goal-stats': {
+ const goalId = formData.get('goalId')?.toString()
+ const period = formData.get('period')?.toString() || '7d'
+ const fromDate = formData.get('from')?.toString() || ''
+ const toDate = formData.get('to')?.toString() || ''
+ const tz = formData.get('timezone')?.toString() || ''
+
+ const params = new URLSearchParams({ period })
+ if (fromDate) params.append('from', fromDate)
+ if (toDate) params.append('to', toDate)
+ if (tz) params.append('timezone', tz)
+
+ const result = await serverFetch(request, `goal/${goalId}/stats?${params.toString()}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-goal-chart': {
+ const goalId = formData.get('goalId')?.toString()
+ const period = formData.get('period')?.toString() || '7d'
+ const fromDate = formData.get('from')?.toString() || ''
+ const toDate = formData.get('to')?.toString() || ''
+ const timeBucket = formData.get('timeBucket')?.toString() || 'day'
+ const tz = formData.get('timezone')?.toString() || ''
+
+ const params = new URLSearchParams({ period, timeBucket })
+ if (fromDate) params.append('from', fromDate)
+ if (toDate) params.append('to', toDate)
+ if (tz) params.append('timezone', tz)
+
+ const result = await serverFetch(request, `goal/${goalId}/chart?${params.toString()}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Funnels (getters)
+ case 'get-funnels': {
+ const password = formData.get('password')?.toString() || ''
+
+ const result = await serverFetch(request, `project/funnels/${projectId}`, {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-funnel-data': {
+ const period = formData.get('period')?.toString() || ''
+ const fromDate = formData.get('from')?.toString() || ''
+ const toDate = formData.get('to')?.toString() || ''
+ const tz = formData.get('timezone')?.toString() || ''
+ const funnelId = formData.get('funnelId')?.toString() || ''
+ const password = formData.get('password')?.toString() || ''
+
+ const params = new URLSearchParams({ pid: projectId || '' })
+ if (period) params.append('period', period)
+ if (fromDate) params.append('from', fromDate)
+ if (toDate) params.append('to', toDate)
+ if (tz) params.append('timezone', tz)
+ if (funnelId) params.append('funnelId', funnelId)
+
+ const result = await serverFetch(request, `log/funnel?${params.toString()}`, {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Alerts (getters)
+ case 'get-project-alerts': {
+ const take = Number(formData.get('take') || '25')
+ const skip = Number(formData.get('skip') || '0')
+
+ const result = await serverFetch(request, `alert/project/${projectId}?take=${take}&skip=${skip}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-alert': {
+ const alertId = formData.get('alertId')?.toString()
+
+ const result = await serverFetch(request, `alert/${alertId}`, {
+ method: 'GET',
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Filters
+ case 'get-filters': {
+ const filterType = formData.get('type')?.toString() || ''
+ const password = formData.get('password')?.toString() || ''
+
+ const result = await serverFetch(request, `log/filters?pid=${projectId}&type=${filterType}`, {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-errors-filters': {
+ const filterType = formData.get('type')?.toString() || ''
+ const password = formData.get('password')?.toString() || ''
+
+ const result = await serverFetch(request, `log/errors-filters?pid=${projectId}&type=${filterType}`, {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-version-filters': {
+ const dataType = formData.get('dataType')?.toString() || 'traffic'
+ const column = formData.get('column')?.toString() || 'br'
+ const password = formData.get('password')?.toString() || ''
+
+ const result = await serverFetch(
+ request,
+ `log/filters/versions?pid=${projectId}&type=${dataType}&column=${column}`,
+ {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ },
+ )
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Error status update
+ case 'update-error-status': {
+ const eid = formData.get('eid')?.toString()
+ const eids = formData.get('eids') ? JSON.parse(formData.get('eids')!.toString()) : undefined
+ const status = formData.get('status')?.toString() || 'active'
+
+ const result = await serverFetch(request, 'log/error-status', {
+ method: 'PATCH',
+ body: { pid: projectId, eid, eids, status },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Project data
+ case 'get-project': {
+ const password = formData.get('password')?.toString() || ''
+
+ const result = await serverFetch(request, `project/${projectId}`, {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: result.status })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'check-password': {
+ const password = formData.get('password')?.toString() || ''
+
+ const result = await serverFetch<boolean>(request, `project/password/${projectId}`, {
+ method: 'GET',
+ headers: { 'x-password': password },
+ })
+
+ if (result.error) {
+ return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectViewActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ default:
+ return data<ProjectViewActionData>({ error: 'Unknown action' }, { status: 400 })
+ }
+}
+
export default function Index() {
const { id } = useRequiredParams<{ id: string }>()
diff --git a/web/app/routes/projects.settings.$id.tsx b/web/app/routes/projects.settings.$id.tsx
index add709021..39309abc9 100644
--- a/web/app/routes/projects.settings.$id.tsx
+++ b/web/app/routes/projects.settings.$id.tsx
@@ -1,9 +1,572 @@
-import type { LoaderFunctionArgs } from 'react-router'
+import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router'
+import { data, redirect } from 'react-router'
+import { serverFetch } from '~/api/api.server'
+import { Project } from '~/lib/models/Project'
+import { Subscriber } from '~/lib/models/Subscriber'
import ProjectSettings from '~/pages/Project/Settings'
+import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
-export async function loader({ request }: LoaderFunctionArgs) {
- return { requestOrigin: request.headers.get('origin') }
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ redirectIfNotAuthenticated(request)
+
+ const { id } = params
+
+ if (!id) {
+ throw new Response('Project ID is required', { status: 400 })
+ }
+
+ const result = await serverFetch<Project>(request, `project/${id}`)
+
+ if (result.error) {
+ return redirect('/dashboard')
+ }
+
+ return data(
+ {
+ project: result.data as Project,
+ requestOrigin: request.headers.get('origin'),
+ },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+}
+
+export interface RevenueStatus {
+ connected: boolean
+ provider?: string
+ currency?: string
+ lastSyncAt?: string
+}
+
+export interface GscStatus {
+ connected: boolean
+ email?: string | null
+}
+
+export interface GscProperty {
+ siteUrl: string
+ permissionLevel?: string
+}
+
+export interface ProjectSettingsActionData {
+ success?: boolean
+ intent?: string
+ error?: string
+ fieldErrors?: {
+ name?: string
+ origins?: string
+ ipBlacklist?: string
+ password?: string
+ transferEmail?: string
+ email?: string
+ }
+ project?: Project
+ subscriber?: Subscriber
+ subscribers?: Subscriber[]
+ subscribersCount?: number
+ revenueStatus?: RevenueStatus
+ gscAuthUrl?: string
+ gscStatus?: GscStatus
+ gscProperties?: GscProperty[]
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ redirectIfNotAuthenticated(request)
+
+ const { id } = params
+ const formData = await request.formData()
+ const intent = formData.get('intent')?.toString()
+
+ switch (intent) {
+ case 'update-project': {
+ const name = formData.get('name')?.toString()
+ const isPublic = formData.get('public') === 'true'
+ const isPasswordProtected = formData.get('isPasswordProtected') === 'true'
+ const password = formData.get('password')?.toString()
+ const origins = formData.get('origins')?.toString()
+ const ipBlacklist = formData.get('ipBlacklist')?.toString()
+ const botsProtectionLevel = formData.get('botsProtectionLevel')?.toString()
+ const countryBlacklist = formData.get('countryBlacklist')?.toString()
+ const websiteUrl = formData.get('websiteUrl')?.toString()
+ const captchaDifficulty = formData.get('captchaDifficulty')?.toString()
+
+ const fieldErrors: ProjectSettingsActionData['fieldErrors'] = {}
+
+ if (name && name.length > 50) {
+ fieldErrors.name = 'Project name must be 50 characters or less'
+ }
+
+ if (fieldErrors.name) {
+ return data<ProjectSettingsActionData>({ intent, fieldErrors }, { status: 400 })
+ }
+
+ const updateData: Record<string, unknown> = {}
+ if (name !== undefined) updateData.name = name
+ updateData.public = isPublic
+ updateData.isPasswordProtected = isPasswordProtected
+ if (password !== undefined) updateData.password = password
+ if (origins !== undefined) updateData.origins = origins ? origins.split(',').map((o) => o.trim()) : null
+ if (ipBlacklist !== undefined)
+ updateData.ipBlacklist = ipBlacklist ? ipBlacklist.split(',').map((ip) => ip.trim()) : null
+ if (botsProtectionLevel !== undefined) updateData.botsProtectionLevel = botsProtectionLevel
+ if (countryBlacklist !== undefined)
+ updateData.countryBlacklist = countryBlacklist ? JSON.parse(countryBlacklist) : []
+ if (websiteUrl !== undefined) updateData.websiteUrl = websiteUrl || null
+ if (captchaDifficulty !== undefined) updateData.captchaDifficulty = Number(captchaDifficulty)
+
+ const result = await serverFetch<Project>(request, `project/${id}`, {
+ method: 'PUT',
+ body: updateData,
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true, project: result.data as Project },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-project': {
+ const result = await serverFetch(request, `project/${id}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'reset-project': {
+ const result = await serverFetch(request, `project/reset/${id}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-partially': {
+ const from = formData.get('from')?.toString()
+ const to = formData.get('to')?.toString()
+
+ const result = await serverFetch(request, `project/partially/${id}`, {
+ method: 'DELETE',
+ body: { from, to },
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'reset-filters': {
+ const type = formData.get('type')?.toString()
+ const filters = formData.get('value')?.toString()
+
+ const result = await serverFetch(
+ request,
+ `project/reset-filters/${id}?type=${encodeURIComponent(type || '')}&filters=${encodeURIComponent(filters || '')}`,
+ {
+ method: 'DELETE',
+ },
+ )
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'transfer-project': {
+ const email = formData.get('email')?.toString() || ''
+
+ if (!email || !email.includes('@')) {
+ return data<ProjectSettingsActionData>(
+ { intent, fieldErrors: { transferEmail: 'Please enter a valid email address' } },
+ { status: 400 },
+ )
+ }
+
+ const result = await serverFetch(request, 'project/transfer', {
+ method: 'POST',
+ body: { projectId: id, email },
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'assign-organisation': {
+ const organisationId = formData.get('organisationId')?.toString()
+
+ const result = await serverFetch(request, `project/${id}/organisation`, {
+ method: 'PATCH',
+ body: { organisationId: organisationId || null },
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'regenerate-captcha-key': {
+ const result = await serverFetch<{ captchaSecretKey: string }>(request, `project/secret-gen/${id}`, {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true, project: { captchaSecretKey: result.data?.captchaSecretKey } as Project },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-subscribers': {
+ const offset = Number(formData.get('offset') || 0)
+ const limit = Number(formData.get('limit') || 10)
+
+ const result = await serverFetch<{ subscribers: Subscriber[]; count: number }>(
+ request,
+ `project/${id}/subscribers?offset=${offset}&limit=${limit}`,
+ )
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true, subscribers: result.data?.subscribers, subscribersCount: result.data?.count },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'add-subscriber': {
+ const email = formData.get('email')?.toString()
+ const reportFrequency = formData.get('reportFrequency')?.toString()
+
+ if (!email) {
+ return data<ProjectSettingsActionData>({ intent, error: 'Email is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch<Subscriber>(request, `project/${id}/subscribers`, {
+ method: 'POST',
+ body: { email, reportFrequency },
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true, subscriber: result.data as Subscriber },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-subscriber': {
+ const subscriberId = formData.get('subscriberId')?.toString()
+ const reportFrequency = formData.get('reportFrequency')?.toString()
+
+ if (!subscriberId) {
+ return data<ProjectSettingsActionData>({ intent, error: 'Subscriber ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch<Subscriber>(request, `project/${id}/subscribers/${subscriberId}`, {
+ method: 'PUT',
+ body: { reportFrequency },
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true, subscriber: result.data as Subscriber },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'remove-subscriber': {
+ const subscriberId = formData.get('subscriberId')?.toString()
+
+ if (!subscriberId) {
+ return data<ProjectSettingsActionData>({ intent, error: 'Subscriber ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `project/${id}/subscribers/${subscriberId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'share-project': {
+ const email = formData.get('email')?.toString()
+ const role = formData.get('role')?.toString()
+
+ if (!email) {
+ return data<ProjectSettingsActionData>({ intent, fieldErrors: { email: 'Email is required' } }, { status: 400 })
+ }
+
+ const result = await serverFetch<Project>(request, `project/${id}/share`, {
+ method: 'POST',
+ body: { email, role },
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true, project: result.data as Project },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-share-user': {
+ const userId = formData.get('userId')?.toString()
+
+ if (!userId) {
+ return data<ProjectSettingsActionData>({ intent, error: 'User ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `project/${id}/${userId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'change-share-role': {
+ const shareId = formData.get('shareId')?.toString()
+ const role = formData.get('role')?.toString()
+
+ if (!shareId) {
+ return data<ProjectSettingsActionData>({ intent, error: 'Share ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `project/share/${shareId}`, {
+ method: 'PUT',
+ body: { role },
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'get-revenue-status': {
+ const result = await serverFetch<RevenueStatus>(request, `project/${id}/revenue/status`)
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true, revenueStatus: result.data as RevenueStatus },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'connect-revenue': {
+ const provider = formData.get('provider')?.toString()
+ const apiKey = formData.get('apiKey')?.toString()
+ const currency = formData.get('currency')?.toString() || 'USD'
+
+ if (!provider || !apiKey) {
+ return data<ProjectSettingsActionData>({ intent, error: 'Provider and API key are required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `project/${id}/revenue/connect`, {
+ method: 'POST',
+ body: { provider, apiKey, currency },
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'disconnect-revenue': {
+ const result = await serverFetch(request, `project/${id}/revenue/disconnect`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'update-revenue-currency': {
+ const currency = formData.get('currency')?.toString()
+
+ if (!currency) {
+ return data<ProjectSettingsActionData>({ intent, error: 'Currency is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `project/${id}/revenue/currency`, {
+ method: 'POST',
+ body: { currency },
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ // Google Search Console
+ case 'gsc-connect': {
+ const result = await serverFetch<{ url: string }>(request, `v1/project/gsc/${id}/connect`, {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true, gscAuthUrl: result.data?.url },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'gsc-status': {
+ const result = await serverFetch<GscStatus>(request, `v1/project/gsc/${id}/status`)
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true, gscStatus: result.data as GscStatus },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'gsc-properties': {
+ const result = await serverFetch<GscProperty[]>(request, `v1/project/gsc/${id}/properties`)
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true, gscProperties: result.data as GscProperty[] },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'gsc-set-property': {
+ const propertyUri = formData.get('propertyUri')?.toString()
+
+ if (!propertyUri) {
+ return data<ProjectSettingsActionData>({ intent, error: 'Property URI is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `v1/project/gsc/${id}/property`, {
+ method: 'POST',
+ body: { propertyUri },
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'gsc-disconnect': {
+ const result = await serverFetch(request, `v1/project/gsc/${id}/disconnect`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<ProjectSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ default:
+ return data<ProjectSettingsActionData>({ error: 'Unknown action' }, { status: 400 })
+ }
}
export default function Index() {
diff --git a/web/app/routes/recovery.tsx b/web/app/routes/recovery.tsx
index ee80df904..69ccba1c3 100644
--- a/web/app/routes/recovery.tsx
+++ b/web/app/routes/recovery.tsx
@@ -1,7 +1,10 @@
-import type { HeadersFunction } from 'react-router'
+import type { ActionFunctionArgs, HeadersFunction, LoaderFunctionArgs } from 'react-router'
+import { data, redirect } from 'react-router'
import { SitemapFunction } from 'remix-sitemap'
+import { getAuthenticatedUser, serverFetch } from '~/api/api.server'
import ForgotPassword from '~/pages/Auth/ForgotPassword'
+import { isValidEmail } from '~/utils/validator'
export const sitemap: SitemapFunction = () => ({
exclude: true,
@@ -12,6 +15,49 @@ export const headers: HeadersFunction = ({ parentHeaders }) => {
return parentHeaders
}
+export async function loader({ request }: LoaderFunctionArgs) {
+ const authResult = await getAuthenticatedUser(request)
+
+ if (authResult) {
+ return redirect('/dashboard')
+ }
+
+ return null
+}
+
+export interface ForgotPasswordActionData {
+ success?: boolean
+ error?: string
+ fieldErrors?: {
+ email?: string
+ }
+ timestamp?: number
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const formData = await request.formData()
+ const email = formData.get('email')?.toString() || ''
+
+ if (!isValidEmail(email)) {
+ return data<ForgotPasswordActionData>(
+ { fieldErrors: { email: 'Please enter a valid email address' }, timestamp: Date.now() },
+ { status: 400 },
+ )
+ }
+
+ const result = await serverFetch(request, 'v1/auth/reset-password', {
+ method: 'POST',
+ body: { email },
+ skipAuth: true,
+ })
+
+ if (result.error) {
+ return data<ForgotPasswordActionData>({ error: result.error as string, timestamp: Date.now() }, { status: 400 })
+ }
+
+ return redirect('/?password_reset_sent=true')
+}
+
export default function Index() {
return <ForgotPassword />
}
diff --git a/web/app/routes/reports-unsubscribe.$token.tsx b/web/app/routes/reports-unsubscribe.$token.tsx
index 82a955903..83c2dec98 100644
--- a/web/app/routes/reports-unsubscribe.$token.tsx
+++ b/web/app/routes/reports-unsubscribe.$token.tsx
@@ -1,21 +1,65 @@
-import { redirect } from 'react-router'
+import type { LoaderFunctionArgs } from 'react-router'
+import { redirect, useLoaderData } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { serverFetch } from '~/api/api.server'
import { isSelfhosted } from '~/lib/constants'
-import Unsubscribe from '~/pages/Unsubscribe'
+import StatusPage from '~/ui/StatusPage'
+import routes from '~/utils/routes'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export async function loader() {
+export interface UnsubscribeLoaderData {
+ success: boolean
+ error?: string
+}
+
+export async function loader({ request, params }: LoaderFunctionArgs): Promise<UnsubscribeLoaderData | Response> {
if (isSelfhosted) {
return redirect('/login', 302)
}
- return null
+ const { token } = params
+
+ if (!token) {
+ return { success: false, error: 'Invalid token' }
+ }
+
+ const result = await serverFetch(request, `user/unsubscribe/${token}`, {
+ skipAuth: true,
+ })
+
+ if (result.error) {
+ const errorMessage = typeof result.error === 'string' ? result.error : 'Failed to unsubscribe'
+ return { success: false, error: errorMessage }
+ }
+
+ return { success: true }
}
-export default function Index() {
- return <Unsubscribe type='user-reports' />
+export default function ReportsUnsubscribeRoute() {
+ const data = useLoaderData<UnsubscribeLoaderData>()
+
+ if (data.error) {
+ return (
+ <StatusPage
+ type='error'
+ title={data.error}
+ actions={[
+ { label: 'Sign In', to: routes.signin, primary: true },
+ { label: 'Support', to: routes.contact },
+ ]}
+ />
+ )
+ }
+
+ return (
+ <StatusPage
+ type='success'
+ title='Successfully unsubscribed from email reports'
+ actions={[{ label: 'Sign In', to: routes.signin, primary: true }]}
+ />
+ )
}
diff --git a/web/app/routes/share.$id.tsx b/web/app/routes/share.$id.tsx
index 78eddd3bd..aa523bc3b 100644
--- a/web/app/routes/share.$id.tsx
+++ b/web/app/routes/share.$id.tsx
@@ -1,11 +1,58 @@
+import type { LoaderFunctionArgs } from 'react-router'
+import { useLoaderData } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
-import ConfirmShare from '~/pages/Project/ConfirmShare'
+import { serverFetch } from '~/api/api.server'
+import StatusPage from '~/ui/StatusPage'
+import routes from '~/utils/routes'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export default function Index() {
- return <ConfirmShare />
+export interface ShareLoaderData {
+ success: boolean
+ error?: string
+}
+
+export async function loader({ request, params }: LoaderFunctionArgs): Promise<ShareLoaderData> {
+ const { id } = params
+
+ if (!id) {
+ return { success: false, error: 'Invalid share link' }
+ }
+
+ const result = await serverFetch(request, `/project/share/${id}`)
+
+ if (result.error) {
+ const errorMessage = typeof result.error === 'string' ? result.error : 'Failed to accept invitation'
+ return { success: false, error: errorMessage }
+ }
+
+ return { success: true }
+}
+
+export default function ShareRoute() {
+ const data = useLoaderData<ShareLoaderData>()
+
+ if (data.error) {
+ return (
+ <StatusPage
+ type='error'
+ title={data.error}
+ actions={[
+ { label: 'Dashboard', to: routes.dashboard, primary: true },
+ { label: 'Support', to: routes.contact },
+ ]}
+ />
+ )
+ }
+
+ return (
+ <StatusPage
+ type='success'
+ title='Invitation accepted'
+ actions={[{ label: 'Dashboard', to: routes.dashboard, primary: true }]}
+ />
+ )
}
diff --git a/web/app/routes/signup.tsx b/web/app/routes/signup.tsx
index 6f284c1d7..96b97f4df 100644
--- a/web/app/routes/signup.tsx
+++ b/web/app/routes/signup.tsx
@@ -1,8 +1,11 @@
-import type { HeadersFunction } from 'react-router'
+import type { ActionFunctionArgs, HeadersFunction, LoaderFunctionArgs } from 'react-router'
+import { redirect, data } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { getAuthenticatedUser, registerUser } from '~/api/api.server'
import { isSelfhosted } from '~/lib/constants'
-import Singup from '~/pages/Auth/Signup'
+import Signup from '~/pages/Auth/Signup'
+import { createHeadersWithCookies } from '~/utils/session.server'
export const headers: HeadersFunction = ({ parentHeaders }) => {
parentHeaders.set('X-Frame-Options', 'DENY')
@@ -14,6 +17,76 @@ export const sitemap: SitemapFunction = () => ({
exclude: isSelfhosted,
})
+export async function loader({ request }: LoaderFunctionArgs) {
+ const authResult = await getAuthenticatedUser(request)
+
+ if (authResult) {
+ if (!authResult.user.user.hasCompletedOnboarding) {
+ return redirect('/onboarding')
+ }
+ return redirect('/dashboard')
+ }
+
+ return null
+}
+
+export interface SignupActionData {
+ error?: string | string[]
+ fieldErrors?: {
+ email?: string
+ password?: string
+ repeat?: string
+ tos?: string
+ }
+ timestamp?: number
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const formData = await request.formData()
+
+ const email = formData.get('email')?.toString() || ''
+ const password = formData.get('password')?.toString() || ''
+ const repeat = formData.get('repeat')?.toString() || ''
+ const tos = formData.get('tos') === 'true'
+ const checkIfLeaked = formData.get('checkIfLeaked') === 'true'
+
+ const fieldErrors: SignupActionData['fieldErrors'] = {}
+
+ if (!email || !email.includes('@')) {
+ fieldErrors.email = 'Please enter a valid email address'
+ }
+
+ if (!password || password.length < 8) {
+ fieldErrors.password = 'Password must be at least 8 characters'
+ }
+
+ if (password.length > 50) {
+ fieldErrors.password = 'Password must be at most 50 characters'
+ }
+
+ if (password !== repeat) {
+ fieldErrors.repeat = 'Passwords do not match'
+ }
+
+ if (!tos && !isSelfhosted) {
+ fieldErrors.tos = 'You must accept the Terms of Service'
+ }
+
+ if (fieldErrors.email || fieldErrors.password || fieldErrors.repeat || fieldErrors.tos) {
+ return data({ fieldErrors, timestamp: Date.now() }, { status: 400 })
+ }
+
+ const result = await registerUser(request, { email, password, checkIfLeaked }, true)
+
+ if (!result.success) {
+ return data({ error: result.error, timestamp: Date.now() }, { status: 400 })
+ }
+
+ return redirect('/onboarding', {
+ headers: createHeadersWithCookies(result.cookies),
+ })
+}
+
export default function SignupPage() {
- return <Singup />
+ return <Signup />
}
diff --git a/web/app/routes/user-settings.tsx b/web/app/routes/user-settings.tsx
index 732ff9a6a..1727775c8 100644
--- a/web/app/routes/user-settings.tsx
+++ b/web/app/routes/user-settings.tsx
@@ -1,11 +1,389 @@
+import type { ActionFunctionArgs, LoaderFunctionArgs } from 'react-router'
+import { data } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { serverFetch } from '~/api/api.server'
+import { User } from '~/lib/models/User'
import UserSettings from '~/pages/UserSettings'
+import { redirectIfNotAuthenticated, createHeadersWithCookies, createAuthCookies } from '~/utils/session.server'
+import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS } from '~/utils/validator'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
+export async function loader({ request }: LoaderFunctionArgs) {
+ redirectIfNotAuthenticated(request)
+ return null
+}
+
+export interface UserSettingsActionData {
+ success?: boolean
+ intent?: string
+ error?: string
+ fieldErrors?: {
+ email?: string
+ password?: string
+ repeat?: string
+ }
+ user?: Partial<User>
+ apiKey?: string
+ twoFAData?: {
+ secret?: string
+ otpauthUrl?: string
+ twoFactorRecoveryCode?: string
+ }
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ redirectIfNotAuthenticated(request)
+
+ const formData = await request.formData()
+ const intent = formData.get('intent')?.toString()
+
+ switch (intent) {
+ case 'update-profile': {
+ const email = formData.get('email')?.toString() || ''
+ const password = formData.get('password')?.toString() || ''
+ const repeat = formData.get('repeat')?.toString() || ''
+ const timezone = formData.get('timezone')?.toString()
+ const timeFormat = formData.get('timeFormat')?.toString()
+ const reportFrequency = formData.get('reportFrequency')?.toString()
+
+ const fieldErrors: UserSettingsActionData['fieldErrors'] = {}
+
+ if (email && !isValidEmail(email)) {
+ fieldErrors.email = 'Please enter a valid email address'
+ }
+
+ if (password) {
+ if (!isValidPassword(password)) {
+ fieldErrors.password = `Password must be at least ${MIN_PASSWORD_CHARS} characters`
+ }
+ if (password.length > MAX_PASSWORD_CHARS) {
+ fieldErrors.password = `Password must be at most ${MAX_PASSWORD_CHARS} characters`
+ }
+ if (password !== repeat) {
+ fieldErrors.repeat = 'Passwords do not match'
+ }
+ }
+
+ if (fieldErrors.email || fieldErrors.password || fieldErrors.repeat) {
+ return data<UserSettingsActionData>({ intent, fieldErrors }, { status: 400 })
+ }
+
+ const updateData: Record<string, unknown> = {}
+ if (email) updateData.email = email
+ if (password) updateData.password = password
+ if (timezone) updateData.timezone = timezone
+ if (timeFormat) updateData.timeFormat = timeFormat
+ if (reportFrequency) updateData.reportFrequency = reportFrequency
+
+ const result = await serverFetch<User>(request, 'user', {
+ method: 'PUT',
+ body: updateData,
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true, user: result.data as User },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'generate-api-key': {
+ const result = await serverFetch<{ apiKey: string }>(request, 'user/api-key', {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true, apiKey: result.data?.apiKey },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-api-key': {
+ const result = await serverFetch(request, 'user/api-key', {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'toggle-live-visitors': {
+ const show = formData.get('show') === 'true'
+
+ const result = await serverFetch<Partial<User>>(request, 'user/live-visitors', {
+ method: 'PUT',
+ body: { show },
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true, user: result.data as Partial<User> },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'toggle-login-notifications': {
+ const receiveLoginNotifications = formData.get('receiveLoginNotifications') === 'true'
+
+ const result = await serverFetch(request, 'user/recieve-login-notifications', {
+ method: 'POST',
+ body: { receiveLoginNotifications },
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'confirm-email': {
+ const result = await serverFetch(request, 'user/confirm_email', {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'delete-account': {
+ const feedback = formData.get('feedback')?.toString() || ''
+
+ const result = await serverFetch(request, 'user', {
+ method: 'DELETE',
+ body: { feedback },
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'generate-2fa': {
+ const result = await serverFetch<{ secret: string; otpauthUrl: string }>(request, '2fa/generate', {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true, twoFAData: result.data as { secret: string; otpauthUrl: string } },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'enable-2fa': {
+ const twoFactorAuthenticationCode = formData.get('code')?.toString() || ''
+
+ const result = await serverFetch<{ twoFactorRecoveryCode: string; accessToken: string; refreshToken: string }>(
+ request,
+ '2fa/enable',
+ {
+ method: 'POST',
+ body: { twoFactorAuthenticationCode },
+ },
+ )
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ // Set new auth cookies from the response
+ const { twoFactorRecoveryCode, accessToken, refreshToken } = result.data!
+ const cookies = createAuthCookies({ accessToken, refreshToken }, true)
+
+ return data<UserSettingsActionData>(
+ { intent, success: true, twoFAData: { twoFactorRecoveryCode } },
+ { headers: createHeadersWithCookies(cookies) },
+ )
+ }
+
+ case 'disable-2fa': {
+ const twoFactorAuthenticationCode = formData.get('code')?.toString() || ''
+
+ const result = await serverFetch(request, '2fa/disable', {
+ method: 'POST',
+ body: { twoFactorAuthenticationCode },
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'accept-project-share': {
+ const shareId = formData.get('shareId')?.toString()
+
+ if (!shareId) {
+ return data<UserSettingsActionData>({ intent, error: 'Share ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `user/share/${shareId}`, {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'reject-project-share': {
+ const shareId = formData.get('shareId')?.toString()
+
+ if (!shareId) {
+ return data<UserSettingsActionData>({ intent, error: 'Share ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `user/share/${shareId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'unlink-sso': {
+ const provider = formData.get('provider')?.toString()
+
+ if (!provider) {
+ return data<UserSettingsActionData>({ intent, error: 'Provider is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, 'v1/auth/sso/unlink', {
+ method: 'DELETE',
+ body: { provider },
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'remove-tg-integration': {
+ const tgID = formData.get('tgID')?.toString()
+
+ if (!tgID) {
+ return data<UserSettingsActionData>({ intent, error: 'Telegram ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `user/tg/${tgID}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'accept-organisation-invitation': {
+ const membershipId = formData.get('membershipId')?.toString()
+
+ if (!membershipId) {
+ return data<UserSettingsActionData>({ intent, error: 'Membership ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `user/organisation/${membershipId}`, {
+ method: 'POST',
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ case 'reject-organisation-invitation': {
+ const membershipId = formData.get('membershipId')?.toString()
+
+ if (!membershipId) {
+ return data<UserSettingsActionData>({ intent, error: 'Membership ID is required' }, { status: 400 })
+ }
+
+ const result = await serverFetch(request, `user/organisation/${membershipId}`, {
+ method: 'DELETE',
+ })
+
+ if (result.error) {
+ return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
+ default:
+ return data<UserSettingsActionData>({ error: 'Unknown action' }, { status: 400 })
+ }
+}
+
export default function UserSettingsPage() {
return <UserSettings />
}
diff --git a/web/app/routes/verify.$id.tsx b/web/app/routes/verify.$id.tsx
index 91a188e86..e04d2e56a 100644
--- a/web/app/routes/verify.$id.tsx
+++ b/web/app/routes/verify.$id.tsx
@@ -1,21 +1,65 @@
-import { redirect } from 'react-router'
+import type { LoaderFunctionArgs } from 'react-router'
+import { redirect, useLoaderData } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
+import { serverFetch } from '~/api/api.server'
import { isSelfhosted } from '~/lib/constants'
-import VerifyEmail from '~/pages/Auth/VerifyEmail'
+import StatusPage from '~/ui/StatusPage'
+import routes from '~/utils/routes'
export const sitemap: SitemapFunction = () => ({
exclude: true,
})
-export async function loader() {
+export interface VerifyEmailLoaderData {
+ success: boolean
+ error?: string
+}
+
+export async function loader({ request, params }: LoaderFunctionArgs): Promise<VerifyEmailLoaderData | Response> {
if (isSelfhosted) {
return redirect('/login', 302)
}
- return null
+ const { id } = params
+
+ if (!id) {
+ return { success: false, error: 'Invalid verification link' }
+ }
+
+ const result = await serverFetch(request, `v1/auth/verify-email/${id}`, {
+ skipAuth: true,
+ })
+
+ if (result.error) {
+ const errorMessage = typeof result.error === 'string' ? result.error : 'Verification failed'
+ return { success: false, error: errorMessage }
+ }
+
+ return { success: true }
}
-export default function Index() {
- return <VerifyEmail />
+export default function VerifyEmailRoute() {
+ const data = useLoaderData<VerifyEmailLoaderData>()
+
+ if (data.error) {
+ return (
+ <StatusPage
+ type='error'
+ title={data.error}
+ actions={[
+ { label: 'Dashboard', to: routes.dashboard, primary: true },
+ { label: 'Support', to: routes.contact },
+ ]}
+ />
+ )
+ }
+
+ return (
+ <StatusPage
+ type='success'
+ title='Email verified successfully'
+ actions={[{ label: 'Continue to Onboarding', to: routes.onboarding, primary: true }]}
+ />
+ )
}
diff --git a/web/app/utils/accessToken.ts b/web/app/utils/accessToken.ts
deleted file mode 100644
index 456438658..000000000
--- a/web/app/utils/accessToken.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import _isEmpty from 'lodash/isEmpty'
-
-import { TOKEN, isBrowser } from '~/lib/constants'
-
-import { getCookie, setCookie, deleteCookie } from './cookie'
-
-// 14 weeks in seconds
-const STORE_AUTH_TOKEN_FOR = 8467200
-
-// It's important to first check in cookie, then in session storage, not vice versa.
-export const getAccessToken = () => {
- if (!isBrowser) {
- return null
- }
-
- let accessToken = getCookie(TOKEN)
-
- if (_isEmpty(accessToken)) {
- accessToken = sessionStorage.getItem(TOKEN)
- }
-
- return accessToken
-}
-
-export const setAccessToken = (token: string, temporary = false) => {
- if (!isBrowser) {
- return null
- }
-
- if (temporary) {
- sessionStorage.setItem(TOKEN, token)
- return null
- }
-
- setCookie(TOKEN, token, STORE_AUTH_TOKEN_FOR)
-}
-
-export const removeAccessToken = () => {
- if (!isBrowser) {
- return null
- }
-
- deleteCookie(TOKEN)
- sessionStorage.removeItem(TOKEN)
-}
diff --git a/web/app/utils/auth.ts b/web/app/utils/auth.ts
index 78d39b840..529d2725b 100644
--- a/web/app/utils/auth.ts
+++ b/web/app/utils/auth.ts
@@ -1,4 +1,3 @@
-import { logoutAllApi, logoutApi } from '~/api'
import {
isSelfhosted,
LOW_EVENTS_WARNING,
@@ -7,10 +6,8 @@ import {
SHOW_BANNER_AT_PERC,
} from '~/lib/constants'
-import { removeAccessToken } from './accessToken'
import { getCookie } from './cookie'
import { removeItem } from './localstorage'
-import { getRefreshToken, removeRefreshToken } from './refreshToken'
export const shouldShowLowEventsBanner = (totalMonthlyEvents: number, maxEventsCount: number) => {
if (isSelfhosted) {
@@ -28,21 +25,11 @@ export const shouldShowLowEventsBanner = (totalMonthlyEvents: number, maxEventsC
return eventsUsedPercentage >= SHOW_BANNER_AT_PERC
}
-export const logout = async (invalidateAllSessions?: boolean) => {
- const refreshToken = getRefreshToken()
-
- try {
- if (invalidateAllSessions) {
- await logoutAllApi()
- } else {
- await logoutApi(refreshToken)
- }
- } catch (reason) {
- console.error('Failed to invalidate refresh token', reason)
- }
-
- removeAccessToken()
+/**
+ * Clears local storage items related to user session.
+ * Called before navigating to /logout route.
+ */
+export const clearLocalStorageOnLogout = () => {
removeItem(LS_VIEW_PREFS_SETTING)
removeItem(LS_CAPTCHA_VIEW_PREFS_SETTING)
- removeRefreshToken()
}
diff --git a/web/app/utils/blog.ts b/web/app/utils/blog.ts
new file mode 100644
index 000000000..c70e45901
--- /dev/null
+++ b/web/app/utils/blog.ts
@@ -0,0 +1,3 @@
+// Removes first 10 characters from the string (i.e. 2023-10-07-)
+export const getSlugFromFilename = (filename: string) => filename.substring(11)
+export const getDateFromFilename = (filename: string) => filename.substring(0, 10)
diff --git a/web/app/utils/compareConvertDate.ts b/web/app/utils/compareConvertDate.ts
deleted file mode 100644
index c5c737241..000000000
--- a/web/app/utils/compareConvertDate.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import dayjs from 'dayjs'
-import utc from 'dayjs/plugin/utc'
-
-import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'
-
-dayjs.extend(utc)
-
-export const periodToCompareDate: {
- period: string
- formula: (date?: Date[]) => {
- from: string
- to: string
- }
-}[] = [
- {
- period: '1d',
- formula: () => {
- const to = dayjs.utc().subtract(1, 'day').format('YYYY-MM-DD')
- const from = dayjs.utc().subtract(2, 'day').format('YYYY-MM-DD')
-
- return {
- from,
- to,
- }
- },
- },
- {
- period: '7d',
- formula: () => {
- const to = dayjs.utc().subtract(7, 'day').format('YYYY-MM-DD')
- const from = dayjs.utc().subtract(14, 'day').format('YYYY-MM-DD')
-
- return {
- from,
- to,
- }
- },
- },
- {
- period: '4w',
- formula: () => {
- const to = dayjs.utc().subtract(28, 'day').format('YYYY-MM-DD')
- const from = dayjs.utc().subtract(56, 'day').format('YYYY-MM-DD')
-
- return {
- from,
- to,
- }
- },
- },
- {
- period: '3M',
- formula: () => {
- const to = dayjs.utc().subtract(3, 'month').format('YYYY-MM-DD')
- const from = dayjs.utc().subtract(6, 'month').format('YYYY-MM-DD')
-
- return {
- from,
- to,
- }
- },
- },
- {
- period: '12M',
- formula: () => {
- const to = dayjs.utc().subtract(12, 'month').format('YYYY-MM-DD')
- const from = dayjs.utc().subtract(24, 'month').format('YYYY-MM-DD')
-
- return {
- from,
- to,
- }
- },
- },
- {
- period: 'custom',
- formula: (date) => {
- if (!date) {
- return {
- from: getFormatDate(new Date()),
- to: getFormatDate(new Date()),
- }
- }
- const days = (date[1].getTime() - date[0].getTime()) / (1000 * 3600 * 24)
- const to = dayjs.utc().subtract(days, 'day').format('YYYY-MM-DD')
- const from = dayjs
- .utc()
- .subtract(days * 2, 'day')
- .format('YYYY-MM-DD')
-
- return {
- from,
- to,
- }
- },
- },
-]
diff --git a/web/app/utils/cookie.ts b/web/app/utils/cookie.ts
index 6856f2f36..2e1726a1f 100644
--- a/web/app/utils/cookie.ts
+++ b/web/app/utils/cookie.ts
@@ -10,7 +10,11 @@ export const getCookie = (key: string) => {
const match = document.cookie.match(new RegExp(`(^| )${key}=([^;]+)`))
if (match) {
- return match[2]
+ try {
+ return decodeURIComponent(match[2])
+ } catch {
+ return match[2]
+ }
}
return null
@@ -27,12 +31,3 @@ export const setCookie = (key: string, value: string | number | boolean, maxAge
document.cookie = generateCookieString(key, value, maxAge, sameSite)
}
-
-export const deleteCookie = (key: string) => {
- if (!isBrowser) {
- return null
- }
-
- document.cookie = `${key}=; max-age=0; path=/; SameSite=strict`
- document.cookie = `${key}=; max-age=0; path=/; SameSite=strict${COOKIE_SUFFIX}`
-}
diff --git a/web/app/utils/getPosts.ts b/web/app/utils/getPosts.server.ts
similarity index 85%
rename from web/app/utils/getPosts.ts
rename to web/app/utils/getPosts.server.ts
index 792f1dc39..e9ed3f89f 100644
--- a/web/app/utils/getPosts.ts
+++ b/web/app/utils/getPosts.server.ts
@@ -2,7 +2,7 @@ import _isEmpty from 'lodash/isEmpty'
import { marked, type Tokens } from 'marked'
import sanitizeHtml from 'sanitize-html'
-import { getBlogPost, getBlogPostWithCategory } from '~/api'
+import { getBlogPost, getBlogPostWithCategory } from '~/api/api.server'
import { renderTimeToSwitchCta, renderDitchGoogleCta } from './renderCtaHtml'
import { extractTableOfContents, ensureHeaderIds, generateSlug, renderTocAsHtml } from './toc'
@@ -15,7 +15,6 @@ renderer.link = ({ href, text }: Tokens.Link) => {
try {
url = new URL(href, 'https://swetrix.com')
} catch {
- // If the href is invalid, render plain text to avoid breaking post rendering.
return text
}
@@ -26,18 +25,15 @@ renderer.link = ({ href, text }: Tokens.Link) => {
return `<a href="${url.toString()}" referrerpolicy="strict-origin-when-cross-origin" target="_blank" rel="noopener noreferrer">${text}</a>`
}
-// Add automatic ID generation to headers
renderer.heading = ({ text, depth }: Tokens.Heading) => {
const id = generateSlug(text)
return `<h${depth} id="${id}">${text}</h${depth}>`
}
-// Helper to parse inline markdown in table cells
function parseInlineMarkdown(text: string): string {
return marked.parseInline(text) as string
}
-// Check if a row is a section header (first cell is bold, other cells are empty)
function isSectionHeaderRow(row: Tokens.TableCell[]): boolean {
const firstCellText = row[0]?.text?.trim() || ''
const isBold = firstCellText.startsWith('**') && firstCellText.endsWith('**')
@@ -45,7 +41,6 @@ function isSectionHeaderRow(row: Tokens.TableCell[]): boolean {
return isBold && otherCellsEmpty
}
-// Custom table rendering with improved styling
renderer.table = ({ header, rows }: Tokens.Table) => {
const headerCells = header
.map(
@@ -59,12 +54,10 @@ renderer.table = ({ header, rows }: Tokens.Table) => {
const isHeader = isSectionHeaderRow(row)
if (isHeader) {
- // Section header row - spans all columns with background
const cellContent = parseInlineMarkdown(row[0].text)
return `<tr class="bg-slate-50 dark:bg-slate-800/70"><td colspan="${row.length}" class="px-4 py-3 text-sm font-semibold text-slate-900 dark:text-slate-100">${cellContent}</td></tr>`
}
- // Regular row
return `<tr class="border-b border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors">${row
.map((cell) => {
return `<td class="px-4 py-3 text-sm text-slate-700 dark:text-slate-300">${parseInlineMarkdown(cell.text)}</td>`
@@ -81,17 +74,14 @@ renderer.table = ({ header, rows }: Tokens.Table) => {
</div>`
}
-// SVG icons for checkmark, cross, and warning
const CHECK_ICON_SVG = `<span class="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-900/30 align-middle"><svg class="h-3.5 w-3.5 overflow-visible text-emerald-600 dark:text-emerald-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" role="img" aria-label="Yes"><path d="M20 6 9 17l-5-5"/></svg></span>`
const CROSS_ICON_SVG = `<span class="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/30 align-middle"><svg class="h-3.5 w-3.5 overflow-visible text-red-600 dark:text-red-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" role="img" aria-label="No"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg></span>`
const WARNING_ICON_SVG = `<span class="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/30 align-middle"><svg class="h-3.5 w-3.5 overflow-visible text-amber-600 dark:text-amber-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" role="img" aria-label="Warning"><path d="M12 9v4"/><path d="M12 17h.01"/><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/></svg></span>`
-// Inline Swetrix logo that inherits font size
const SWETRIX_LOGO_HTML = `<span class="inline-flex items-center gap-[0.15em] select-none whitespace-nowrap align-baseline"><img class="h-[0.9em] w-auto dark:hidden" src="/assets/logo/blue.png" alt="" /><img class="h-[0.9em] w-auto hidden dark:inline" src="/assets/logo/white.png" alt="" /><span class="font-bold text-indigo-950 dark:text-white">Swetrix</span></span>`
-// GitHub-style alert configurations
const ALERT_CONFIGS = {
NOTE: {
icon: `<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 16 16"><path d="M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm8-6.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM6.5 7.75A.75.75 0 0 1 7.25 7h1a.75.75 0 0 1 .75.75v2.75h.25a.75.75 0 0 1 0 1.5h-2a.75.75 0 0 1 0-1.5h.25v-2h-.25a.75.75 0 0 1-.75-.75ZM8 6a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z"/></svg>`,
@@ -142,10 +132,7 @@ const ALERT_CONFIGS = {
type AlertType = keyof typeof ALERT_CONFIGS
-// Custom blockquote rendering for GitHub-style alerts
renderer.blockquote = ({ text }: Tokens.Blockquote) => {
- // Check for alert syntax: [!NOTE], [!TIP], [!IMPORTANT], [!WARNING], [!CAUTION]
- // The text may be raw markdown or partially rendered, check for both formats
const alertMatch = text.match(/^\s*(?:<p>)?\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](?:<br\s*\/?>|\n)?(?:<\/p>)?\s*/i)
if (alertMatch) {
@@ -153,7 +140,6 @@ renderer.blockquote = ({ text }: Tokens.Blockquote) => {
const config = ALERT_CONFIGS[alertType]
const rawContent = text.replace(alertMatch[0], '').trim()
- // Process content through marked to render markdown (links, bold, italic, etc.)
const content = marked(rawContent, { renderer }) as string
return `<div class="not-prose my-6 rounded-lg border-l-4 ${config.borderClass} ${config.bgClass} p-4">
@@ -167,25 +153,18 @@ renderer.blockquote = ({ text }: Tokens.Blockquote) => {
</div>`
}
- // Default blockquote rendering - also process through marked for consistency
const renderedText = marked(text, { renderer }) as string
return `<blockquote>${renderedText}</blockquote>`
}
-// Function to replace emoji with styled icons
function replaceEmojiWithIcons(html: string): string {
return html.replace(/✅/g, CHECK_ICON_SVG).replace(/❌/g, CROSS_ICON_SVG).replace(/⚠️/g, WARNING_ICON_SVG)
}
-// Function to replace ::SWETRIX_LOGO:: placeholder
function replaceSwetrixLogo(html: string): string {
return html.replace(/::SWETRIX_LOGO::/g, SWETRIX_LOGO_HTML)
}
-// Removes first 10 characters from the string (i.e. 2023-10-07-)
-export const getSlugFromFilename = (filename: string) => filename.substring(11)
-export const getDateFromFilename = (filename: string) => filename.substring(0, 10)
-
interface GetPost {
slug: string
title?: string
@@ -198,14 +177,19 @@ interface GetPost {
twitter_handle?: string
}
-export async function getPost(slug: string, category?: string, tryStandalone?: boolean): Promise<GetPost | null> {
- let post: any = null
+export async function getPost(
+ request: Request,
+ slug: string,
+ category?: string,
+ tryStandalone?: boolean,
+): Promise<GetPost | null> {
+ let post: Awaited<ReturnType<typeof getBlogPost>> = null
try {
if (category) {
- post = await getBlogPostWithCategory(category, slug)
+ post = await getBlogPostWithCategory(request, category, slug)
} else {
- post = await getBlogPost(slug)
+ post = await getBlogPost(request, slug)
}
} catch {
return null
@@ -229,11 +213,7 @@ export async function getPost(slug: string, category?: string, tryStandalone?: b
let html = marked(post.body, { renderer }) as string
html = ensureHeaderIds(html)
-
- // Replace emoji icons with styled SVG icons
html = replaceEmojiWithIcons(html)
-
- // Replace ::SWETRIX_LOGO:: with inline logo
html = replaceSwetrixLogo(html)
const toc = extractTableOfContents(html)
@@ -243,23 +223,18 @@ export async function getPost(slug: string, category?: string, tryStandalone?: b
html = html.replace(new RegExp(tocPlaceholder, 'gi'), tocHtml)
}
- // Handle CTA:TIME_TO_SWITCH placeholder
if (hasCtaTimeToSwitch) {
const ctaHtml = renderTimeToSwitchCta()
html = html.replace(new RegExp(ctaTimeToSwitchPlaceholder, 'gi'), ctaHtml)
}
- // Handle CTA:TIME_TO_DITCH_GOOGLE placeholder
if (hasCtaDitchGoogle) {
const ctaHtml = renderDitchGoogleCta()
html = html.replace(new RegExp(ctaDitchGooglePlaceholder, 'gi'), ctaHtml)
}
- // Sanitize generated HTML before sending it to the client to prevent stored XSS
- // (CMS content, table-of-contents placeholder, and CTA placeholders).
html = sanitizeHtml(html, {
allowedTags: [
- // Document structure
'p',
'br',
'hr',
@@ -269,7 +244,6 @@ export async function getPost(slug: string, category?: string, tryStandalone?: b
'h4',
'h5',
'h6',
- // Text formatting
'strong',
'em',
's',
@@ -277,24 +251,19 @@ export async function getPost(slug: string, category?: string, tryStandalone?: b
'blockquote',
'pre',
'code',
- // Lists
'ul',
'ol',
'li',
- // Links / media
'a',
'img',
- // Tables
'table',
'thead',
'tbody',
'tr',
'th',
'td',
- // Layout used by CTAs / alerts / icons
'div',
'span',
- // Inline SVG used by our generated HTML snippets
'svg',
'path',
],
@@ -320,14 +289,11 @@ export async function getPost(slug: string, category?: string, tryStandalone?: b
],
path: ['d', 'fill', 'fill-rule', 'clip-rule'],
},
- // Keep it tight: no javascript: URLs, no data: URLs (especially for <img>),
- // but allow relative links and hash fragments.
allowedSchemes: ['http', 'https', 'mailto', 'tel'],
allowedSchemesByTag: {
img: ['http', 'https'],
},
allowProtocolRelative: false,
- // Avoid CSS injection; we only rely on Tailwind classes.
allowedStyles: {},
})
diff --git a/web/app/utils/refreshToken.ts b/web/app/utils/refreshToken.ts
deleted file mode 100644
index 24d600849..000000000
--- a/web/app/utils/refreshToken.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import _isEmpty from 'lodash/isEmpty'
-
-import { REFRESH_TOKEN, isBrowser } from '~/lib/constants'
-
-import { getCookie, setCookie, deleteCookie } from './cookie'
-
-// 14 weeks in seconds
-const STORE_REFRESH_TOKEN_FOR = 8467200
-
-export const getRefreshToken = () => {
- if (!isBrowser) {
- return null
- }
-
- let refreshToken = getCookie(REFRESH_TOKEN)
-
- if (_isEmpty(refreshToken)) {
- refreshToken = sessionStorage.getItem(REFRESH_TOKEN)
- }
-
- return refreshToken
-}
-
-export const setRefreshToken = (token: string, temporary = false) => {
- if (!isBrowser) {
- return null
- }
-
- if (temporary) {
- sessionStorage.setItem(REFRESH_TOKEN, token)
- return
- }
-
- setCookie(REFRESH_TOKEN, token, STORE_REFRESH_TOKEN_FOR)
-}
-
-export const removeRefreshToken = () => {
- if (!isBrowser) {
- return null
- }
-
- deleteCookie(REFRESH_TOKEN)
- sessionStorage.removeItem(REFRESH_TOKEN)
-}
diff --git a/web/app/utils/server.ts b/web/app/utils/server.ts
index 189c968be..45acd79dc 100644
--- a/web/app/utils/server.ts
+++ b/web/app/utils/server.ts
@@ -36,17 +36,6 @@ export function detectTheme(request: Request): ThemeType {
return 'light'
}
-function getAccessToken(request: Request): string | null {
- const cookie = request.headers.get('Cookie')
- const accessToken = cookie?.match(/(?<=access_token=)[^;]*/)?.[0]
-
- return accessToken || null
-}
-
-export function isAuthenticated(request: Request): boolean {
- return !!getAccessToken(request)
-}
-
export function isWWW(url: URL): boolean {
return _startsWith(url.hostname, 'www.')
}
diff --git a/web/app/utils/session.server.ts b/web/app/utils/session.server.ts
new file mode 100644
index 000000000..2b95a0379
--- /dev/null
+++ b/web/app/utils/session.server.ts
@@ -0,0 +1,182 @@
+import { redirect } from 'react-router'
+
+const ACCESS_TOKEN_COOKIE = 'access_token'
+const REFRESH_TOKEN_COOKIE = 'refresh_token'
+
+const PERSISTENT_COOKIE_MAX_AGE = 8467200 // 14 weeks in seconds
+
+export interface AuthTokens {
+ accessToken: string
+ refreshToken: string
+}
+
+function getCookieDomain(): string | undefined {
+ const domain = process.env.COOKIE_DOMAIN
+
+ // In development or selfhosted without explicit domain, don't set domain
+ // TODO: Eventually we should support this variable for selfhosted Swetrix as well
+ if (!domain || process.env.NODE_ENV === 'development' || process.env.__SELFHOSTED) {
+ return undefined
+ }
+
+ return domain
+}
+
+function isSecureCookie(): boolean {
+ // TODO: Eventually we should support this variable for selfhosted Swetrix as well
+ return process.env.NODE_ENV === 'production' && !process.env.__SELFHOSTED
+}
+
+function parseCookies(request: Request): Record<string, string> {
+ const cookieHeader = request.headers.get('Cookie')
+ if (!cookieHeader) return {}
+
+ const cookies: Record<string, string> = {}
+ for (const cookie of cookieHeader.split(';')) {
+ const [name, ...valueParts] = cookie.trim().split('=')
+ if (name) {
+ const rawValue = valueParts.join('=')
+ try {
+ cookies[name] = decodeURIComponent(rawValue)
+ } catch {
+ cookies[name] = rawValue
+ }
+ }
+ }
+ return cookies
+}
+
+export function getAccessToken(request: Request): string | null {
+ const cookies = parseCookies(request)
+ return cookies[ACCESS_TOKEN_COOKIE] || null
+}
+
+export function getRefreshToken(request: Request): string | null {
+ const cookies = parseCookies(request)
+ return cookies[REFRESH_TOKEN_COOKIE] || null
+}
+
+export function isPersistentSession(request: Request): boolean {
+ const cookies = parseCookies(request)
+ return cookies['is_persistent'] === 'true'
+}
+
+export function hasAuthTokens(request: Request): boolean {
+ return !!getAccessToken(request) || !!getRefreshToken(request)
+}
+
+export function redirectIfNotAuthenticated(request: Request, redirectTo = '/login'): Response | null {
+ if (hasAuthTokens(request)) {
+ return null
+ }
+
+ throw redirect(redirectTo, {
+ headers: createHeadersWithCookies(clearAuthCookies()),
+ })
+}
+
+function buildCookieHeader(
+ name: string,
+ value: string,
+ options: {
+ maxAge?: number // undefined = session cookie (expires on browser close)
+ path?: string
+ sameSite?: 'Strict' | 'Lax' | 'None'
+ secure?: boolean
+ httpOnly?: boolean
+ domain?: string
+ } = {},
+): string {
+ const {
+ maxAge,
+ path = '/',
+ sameSite = 'Strict',
+ secure = isSecureCookie(),
+ httpOnly = true,
+ domain = getCookieDomain(),
+ } = options
+
+ let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; SameSite=${sameSite}`
+
+ // Only add Max-Age for persistent cookies
+ // Session cookies (remember=false) should NOT have Max-Age
+ if (maxAge !== undefined) {
+ cookie += `; Max-Age=${maxAge}`
+ }
+
+ if (secure) {
+ cookie += '; Secure'
+ }
+
+ if (httpOnly) {
+ cookie += '; HttpOnly'
+ }
+
+ if (domain) {
+ cookie += `; Domain=${domain}`
+ }
+
+ return cookie
+}
+
+export function createAuthCookies(tokens: AuthTokens, remember: boolean): string[] {
+ const maxAge = remember ? PERSISTENT_COOKIE_MAX_AGE : undefined
+
+ const cookies = [
+ buildCookieHeader(ACCESS_TOKEN_COOKIE, tokens.accessToken, { maxAge }),
+ buildCookieHeader(REFRESH_TOKEN_COOKIE, tokens.refreshToken, { maxAge }),
+ ]
+
+ if (remember) {
+ cookies.push(buildCookieHeader('is_persistent', 'true', { maxAge: PERSISTENT_COOKIE_MAX_AGE }))
+ }
+
+ return cookies
+}
+
+/**
+ * @returns Array of Set-Cookie header values that expire the cookies
+ */
+export function clearAuthCookies(): string[] {
+ const domain = getCookieDomain()
+
+ // Clear with and without domain to ensure both are removed
+ const cookies = [
+ `${ACCESS_TOKEN_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax`,
+ `${REFRESH_TOKEN_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax`,
+ ]
+
+ if (domain) {
+ cookies.push(`${ACCESS_TOKEN_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax; Domain=${domain}`)
+ cookies.push(`${REFRESH_TOKEN_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax; Domain=${domain}`)
+ }
+
+ return cookies
+}
+
+function appendCookiesToHeaders(headers: Headers, cookies: string[]): Headers {
+ for (const cookie of cookies) {
+ headers.append('Set-Cookie', cookie)
+ }
+ return headers
+}
+
+export function createHeadersWithCookies(cookies: string[]): Headers {
+ const headers = new Headers()
+ return appendCookiesToHeaders(headers, cookies)
+}
+
+const PROJECT_PASSWORD_COOKIE_PREFIX = 'swx_pp_'
+const PROJECT_PASSWORD_MAX_AGE = 604800 // 1 week in seconds
+
+export function getProjectPasswordCookie(request: Request, projectId: string): string | null {
+ const cookies = parseCookies(request)
+ return cookies[`${PROJECT_PASSWORD_COOKIE_PREFIX}${projectId}`] || null
+}
+
+export function createProjectPasswordCookie(projectId: string, password: string): string {
+ return buildCookieHeader(`${PROJECT_PASSWORD_COOKIE_PREFIX}${projectId}`, password, {
+ maxAge: PROJECT_PASSWORD_MAX_AGE,
+ sameSite: 'Lax',
+ })
+}
diff --git a/web/package-lock.json b/web/package-lock.json
index 5c9fbd342..dff529b98 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -18,8 +18,6 @@
"@tanstack/react-virtual": "^3.13.13",
"@types/leaflet": "^1.9.21",
"@ua-parser-js/pro-business": "^2.0.6",
- "axios": "^1.13.2",
- "axios-auth-refresh": "^3.3.6",
"billboard.js": "^3.17.2",
"boring-avatars": "^2.0.4",
"clsx": "^2.1.1",
@@ -4463,12 +4461,6 @@
"node": ">= 0.4"
}
},
- "node_modules/asynckit": {
- "version": "0.4.0",
- "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
- "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
- "license": "MIT"
- },
"node_modules/available-typed-arrays": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",
@@ -4495,26 +4487,6 @@
"node": ">=4"
}
},
- "node_modules/axios": {
- "version": "1.13.2",
- "resolved": "https://registry.npmjs.org/axios/-/axios-1.13.2.tgz",
- "integrity": "sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==",
- "license": "MIT",
- "dependencies": {
- "follow-redirects": "^1.15.6",
- "form-data": "^4.0.4",
- "proxy-from-env": "^1.1.0"
- }
- },
- "node_modules/axios-auth-refresh": {
- "version": "3.3.6",
- "resolved": "https://registry.npmjs.org/axios-auth-refresh/-/axios-auth-refresh-3.3.6.tgz",
- "integrity": "sha512-2CeBUce/SxIfFxow5/n8vApJ97yYF6qoV4gh1UrswT7aEOnlOdBLxxyhOI4IaxGs6BY0l8YujU2jlc4aCmK17Q==",
- "license": "MIT",
- "peerDependencies": {
- "axios": ">= 0.18 < 0.19.0 || >= 0.19.1"
- }
- },
"node_modules/axobject-query": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
@@ -4880,18 +4852,6 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT"
},
- "node_modules/combined-stream": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
- "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
- "license": "MIT",
- "dependencies": {
- "delayed-stream": "~1.0.0"
- },
- "engines": {
- "node": ">= 0.8"
- }
- },
"node_modules/commander": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
@@ -5705,15 +5665,6 @@
"robust-predicates": "^3.0.2"
}
},
- "node_modules/delayed-stream": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
- "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
- "license": "MIT",
- "engines": {
- "node": ">=0.4.0"
- }
- },
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@@ -6040,6 +5991,7 @@
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+ "devOptional": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
@@ -7014,26 +6966,6 @@
"integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==",
"license": "ISC"
},
- "node_modules/follow-redirects": {
- "version": "1.15.11",
- "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz",
- "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==",
- "funding": [
- {
- "type": "individual",
- "url": "https://github.com/sponsors/RubenVerborgh"
- }
- ],
- "license": "MIT",
- "engines": {
- "node": ">=4.0"
- },
- "peerDependenciesMeta": {
- "debug": {
- "optional": true
- }
- }
- },
"node_modules/for-each": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz",
@@ -7050,22 +6982,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/form-data": {
- "version": "4.0.5",
- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
- "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
- "license": "MIT",
- "dependencies": {
- "asynckit": "^0.4.0",
- "combined-stream": "^1.0.8",
- "es-set-tostringtag": "^2.1.0",
- "hasown": "^2.0.2",
- "mime-types": "^2.1.12"
- },
- "engines": {
- "node": ">= 6"
- }
- },
"node_modules/formatly": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/formatly/-/formatly-0.3.0.tgz",
@@ -7421,6 +7337,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
+ "devOptional": true,
"license": "MIT",
"dependencies": {
"has-symbols": "^1.0.3"
@@ -9509,12 +9426,6 @@
"node": ">= 0.10"
}
},
- "node_modules/proxy-from-env": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
- "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
- "license": "MIT"
- },
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
diff --git a/web/package.json b/web/package.json
index 1747b6a0b..c765fe052 100644
--- a/web/package.json
+++ b/web/package.json
@@ -30,8 +30,6 @@
"@tanstack/react-virtual": "^3.13.13",
"@types/leaflet": "^1.9.21",
"@ua-parser-js/pro-business": "^2.0.6",
- "axios": "^1.13.2",
- "axios-auth-refresh": "^3.3.6",
"billboard.js": "^3.17.2",
"boring-avatars": "^2.0.4",
"clsx": "^2.1.1",
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 31d1be3a7..b252fca6e 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -1458,6 +1458,7 @@
"organisation": "Organisation",
"shields": "Shields",
"access": "Access settings",
+ "resetSuccess": "The project has been reset",
"gsc": {
"connect": "Connect your project to your Google Search Console account to get stats like what keywords people are using to find your website.",
"disconnected": "The project has been disconnected from your Google Search Console account.",