Compare commits

..

7 Commits

Author SHA1 Message Date
Bhagya Amarasinghe
972407eb93 fix: optimize license check flow (backport to 4.6) (#7193) 2026-02-02 19:21:11 +05:30
Dhruwang Jariwala
fcbb99c43d fix: (backport) jerky animation behaviour (#7158) (#7163) 2026-01-26 10:24:19 +05:30
Dhruwang Jariwala
ec415a7aa1 fix: (backport) nps & rating rtl UI (#7154) (#7162) 2026-01-23 18:29:09 +05:30
Anshuman Pandey
a1e53c9051 fix: [Backport] fixes response card UI for cta question (#7161) 2026-01-23 17:58:53 +05:30
Anshuman Pandey
680295c63e fix: [Backport] fixes the cta element survey not found error (#7160) 2026-01-23 17:58:31 +05:30
Anshuman Pandey
73b40469f7 fix: (BACKPORT) language variants not working for app surveys (#7151) (#7159) 2026-01-23 17:32:00 +05:30
Dhruwang Jariwala
282e061606 fix: language variants not working for app surveys (#7151) 2026-01-23 17:10:33 +05:30
29 changed files with 357 additions and 125 deletions

View File

@@ -36,7 +36,7 @@ export const EnvironmentLayout = async ({ layoutData, children }: EnvironmentLay
// Calculate derived values (no queries)
const { isMember, isOwner, isManager } = getAccessFlags(membership.role);
const { features, lastChecked, isPendingDowngrade, active } = license;
const { features, lastChecked, isPendingDowngrade, active, status } = license;
const isMultiOrgEnabled = features?.isMultiOrgEnabled ?? false;
const organizationProjectsLimit = await getOrganizationProjectsLimit(organization.billing.limits);
const isOwnerOrManager = isOwner || isManager;
@@ -63,6 +63,7 @@ export const EnvironmentLayout = async ({ layoutData, children }: EnvironmentLay
active={active}
environmentId={environment.id}
locale={user.locale}
status={status}
/>
<div className="flex h-full">

View File

@@ -254,6 +254,7 @@
"label": "Bezeichnung",
"language": "Sprache",
"learn_more": "Mehr erfahren",
"license_expired": "License Expired",
"light_overlay": "Helle Überlagerung",
"limits_reached": "Limits erreicht",
"link": "Link",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "Sie haben Ihr Limit von {projectLimit} Workspaces erreicht.",
"you_have_reached_your_monthly_miu_limit_of": "Du hast dein monatliches MIU-Limit erreicht",
"you_have_reached_your_monthly_response_limit_of": "Du hast dein monatliches Antwortlimit erreicht",
"you_will_be_downgraded_to_the_community_edition_on_date": "Du wirst am {date} auf die Community Edition herabgestuft."
"you_will_be_downgraded_to_the_community_edition_on_date": "Du wirst am {date} auf die Community Edition herabgestuft.",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "Annehmen",

View File

@@ -254,6 +254,7 @@
"label": "Label",
"language": "Language",
"learn_more": "Learn more",
"license_expired": "License Expired",
"light_overlay": "Light overlay",
"limits_reached": "Limits Reached",
"link": "Link",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "You have reached your limit of {projectLimit} workspaces.",
"you_have_reached_your_monthly_miu_limit_of": "You have reached your monthly MIU limit of",
"you_have_reached_your_monthly_response_limit_of": "You have reached your monthly response limit of",
"you_will_be_downgraded_to_the_community_edition_on_date": "You will be downgraded to the Community Edition on {date}."
"you_will_be_downgraded_to_the_community_edition_on_date": "You will be downgraded to the Community Edition on {date}.",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "Accept",

View File

@@ -254,6 +254,7 @@
"label": "Etiqueta",
"language": "Idioma",
"learn_more": "Saber más",
"license_expired": "License Expired",
"light_overlay": "Superposición clara",
"limits_reached": "Límites alcanzados",
"link": "Enlace",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "Has alcanzado tu límite de {projectLimit} espacios de trabajo.",
"you_have_reached_your_monthly_miu_limit_of": "Has alcanzado tu límite mensual de MIU de",
"you_have_reached_your_monthly_response_limit_of": "Has alcanzado tu límite mensual de respuestas de",
"you_will_be_downgraded_to_the_community_edition_on_date": "Serás degradado a la edición Community el {date}."
"you_will_be_downgraded_to_the_community_edition_on_date": "Serás degradado a la edición Community el {date}.",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "Aceptar",

View File

@@ -254,6 +254,7 @@
"label": "Étiquette",
"language": "Langue",
"learn_more": "En savoir plus",
"license_expired": "License Expired",
"light_overlay": "Claire",
"limits_reached": "Limites atteints",
"link": "Lien",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "Vous avez atteint votre limite de {projectLimit} espaces de travail.",
"you_have_reached_your_monthly_miu_limit_of": "Vous avez atteint votre limite mensuelle de MIU de",
"you_have_reached_your_monthly_response_limit_of": "Vous avez atteint votre limite de réponses mensuelle de",
"you_will_be_downgraded_to_the_community_edition_on_date": "Vous serez rétrogradé à l'édition communautaire le {date}."
"you_will_be_downgraded_to_the_community_edition_on_date": "Vous serez rétrogradé à l'édition communautaire le {date}.",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "Accepter",

View File

@@ -254,6 +254,7 @@
"label": "ラベル",
"language": "言語",
"learn_more": "詳細を見る",
"license_expired": "License Expired",
"light_overlay": "明るいオーバーレイ",
"limits_reached": "上限に達しました",
"link": "リンク",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "ワークスペースの上限である{projectLimit}件に達しました。",
"you_have_reached_your_monthly_miu_limit_of": "月間MIU月間アクティブユーザーの上限に達しました",
"you_have_reached_your_monthly_response_limit_of": "月間回答数の上限に達しました",
"you_will_be_downgraded_to_the_community_edition_on_date": "コミュニティ版へのダウングレードは {date} に行われます。"
"you_will_be_downgraded_to_the_community_edition_on_date": "コミュニティ版へのダウングレードは {date} に行われます。",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "承認",

View File

@@ -254,6 +254,7 @@
"label": "Label",
"language": "Taal",
"learn_more": "Meer informatie",
"license_expired": "License Expired",
"light_overlay": "Lichte overlay",
"limits_reached": "Grenzen bereikt",
"link": "Link",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "Je hebt je limiet van {projectLimit} werkruimtes bereikt.",
"you_have_reached_your_monthly_miu_limit_of": "U heeft uw maandelijkse MIU-limiet van bereikt",
"you_have_reached_your_monthly_response_limit_of": "U heeft uw maandelijkse responslimiet bereikt van",
"you_will_be_downgraded_to_the_community_edition_on_date": "Je wordt gedowngraded naar de Community-editie op {date}."
"you_will_be_downgraded_to_the_community_edition_on_date": "Je wordt gedowngraded naar de Community-editie op {date}.",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "Accepteren",

View File

@@ -254,6 +254,7 @@
"label": "Etiqueta",
"language": "Língua",
"learn_more": "Saiba mais",
"license_expired": "License Expired",
"light_overlay": "sobreposição leve",
"limits_reached": "Limites Atingidos",
"link": "link",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "Você atingiu seu limite de {projectLimit} espaços de trabalho.",
"you_have_reached_your_monthly_miu_limit_of": "Você atingiu o seu limite mensal de MIU de",
"you_have_reached_your_monthly_response_limit_of": "Você atingiu o limite mensal de respostas de",
"you_will_be_downgraded_to_the_community_edition_on_date": "Você será rebaixado para a Edição Comunitária em {date}."
"you_will_be_downgraded_to_the_community_edition_on_date": "Você será rebaixado para a Edição Comunitária em {date}.",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "Aceitar",

View File

@@ -254,6 +254,7 @@
"label": "Etiqueta",
"language": "Idioma",
"learn_more": "Saiba mais",
"license_expired": "License Expired",
"light_overlay": "Sobreposição leve",
"limits_reached": "Limites Atingidos",
"link": "Link",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "Atingiu o seu limite de {projectLimit} áreas de trabalho.",
"you_have_reached_your_monthly_miu_limit_of": "Atingiu o seu limite mensal de MIU de",
"you_have_reached_your_monthly_response_limit_of": "Atingiu o seu limite mensal de respostas de",
"you_will_be_downgraded_to_the_community_edition_on_date": "Será rebaixado para a Edição Comunitária em {date}."
"you_will_be_downgraded_to_the_community_edition_on_date": "Será rebaixado para a Edição Comunitária em {date}.",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "Aceitar",

View File

@@ -254,6 +254,7 @@
"label": "Etichetă",
"language": "Limba",
"learn_more": "Află mai multe",
"license_expired": "License Expired",
"light_overlay": "Suprapunere ușoară",
"limits_reached": "Limite atinse",
"link": "Legătura",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "Ați atins limita de {projectLimit} spații de lucru.",
"you_have_reached_your_monthly_miu_limit_of": "Ați atins limita lunară MIU de",
"you_have_reached_your_monthly_response_limit_of": "Ați atins limita lunară de răspunsuri de",
"you_will_be_downgraded_to_the_community_edition_on_date": "Vei fi retrogradat la ediția Community pe {date}."
"you_will_be_downgraded_to_the_community_edition_on_date": "Vei fi retrogradat la ediția Community pe {date}.",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "Acceptă",

View File

@@ -254,6 +254,7 @@
"label": "Метка",
"language": "Язык",
"learn_more": "Подробнее",
"license_expired": "License Expired",
"light_overlay": "Светлый оверлей",
"limits_reached": "Достигнуты лимиты",
"link": "Ссылка",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "Вы достигли лимита в {projectLimit} рабочих пространств.",
"you_have_reached_your_monthly_miu_limit_of": "Вы достигли месячного лимита MIU:",
"you_have_reached_your_monthly_response_limit_of": "Вы достигли месячного лимита ответов:",
"you_will_be_downgraded_to_the_community_edition_on_date": "Ваша версия будет понижена до Community Edition {date}."
"you_will_be_downgraded_to_the_community_edition_on_date": "Ваша версия будет понижена до Community Edition {date}.",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "Принять",

View File

@@ -254,6 +254,7 @@
"label": "Etikett",
"language": "Språk",
"learn_more": "Läs mer",
"license_expired": "License Expired",
"light_overlay": "Ljust överlägg",
"limits_reached": "Gränser nådda",
"link": "Länk",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "Du har nått din gräns på {projectLimit} arbetsytor.",
"you_have_reached_your_monthly_miu_limit_of": "Du har nått din månatliga MIU-gräns på",
"you_have_reached_your_monthly_response_limit_of": "Du har nått din månatliga svarsgräns på",
"you_will_be_downgraded_to_the_community_edition_on_date": "Du kommer att nedgraderas till Community Edition den {date}."
"you_will_be_downgraded_to_the_community_edition_on_date": "Du kommer att nedgraderas till Community Edition den {date}.",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "Acceptera",

View File

@@ -254,6 +254,7 @@
"label": "标签",
"language": "语言",
"learn_more": "了解 更多",
"license_expired": "License Expired",
"light_overlay": "浅色遮罩层",
"limits_reached": "限制 达到",
"link": "链接",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "您已达到 {projectLimit} 个工作区的上限。",
"you_have_reached_your_monthly_miu_limit_of": "您 已经 达到 每月 的 MIU 限制",
"you_have_reached_your_monthly_response_limit_of": "您 已经 达到 每月 的 响应 限制",
"you_will_be_downgraded_to_the_community_edition_on_date": "您将在 {date} 降级到社区版。"
"you_will_be_downgraded_to_the_community_edition_on_date": "您将在 {date} 降级到社区版。",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "接受",

View File

@@ -254,6 +254,7 @@
"label": "標籤",
"language": "語言",
"learn_more": "瞭解更多",
"license_expired": "License Expired",
"light_overlay": "淺色覆蓋",
"limits_reached": "已達上限",
"link": "連結",
@@ -460,7 +461,8 @@
"you_have_reached_your_limit_of_workspace_limit": "您已達到 {projectLimit} 個工作區的上限。",
"you_have_reached_your_monthly_miu_limit_of": "您已達到每月 MIU 上限:",
"you_have_reached_your_monthly_response_limit_of": "您已達到每月回應上限:",
"you_will_be_downgraded_to_the_community_edition_on_date": "您將於 '{'date'}' 降級至社群版。"
"you_will_be_downgraded_to_the_community_edition_on_date": "您將於 '{'date'}' 降級至社群版。",
"your_license_has_expired_please_renew": "Your enterprise license has expired. Please renew it to continue using enterprise features."
},
"emails": {
"accept": "接受",

View File

@@ -3,6 +3,7 @@
import { CheckCircle2Icon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { TResponseWithQuotas } from "@formbricks/types/responses";
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/constants";
import { TSurvey } from "@formbricks/types/surveys/types";
import { getTextContent } from "@formbricks/types/surveys/validation";
import { getLocalizedValue } from "@/lib/i18n/utils";
@@ -67,6 +68,16 @@ export const SingleResponseCardBody = ({
<VerifiedEmail responseData={response.data} />
)}
{elements.map((question) => {
// Skip CTA elements without external buttons only if they have no response data
// This preserves historical data from when buttonExternal was true
if (
question.type === TSurveyElementTypeEnum.CTA &&
!question.buttonExternal &&
!response.data[question.id]
) {
return null;
}
const skipped = skippedQuestions.find((skippedQuestionElement) =>
skippedQuestionElement.includes(question.id)
);

View File

@@ -157,6 +157,7 @@ describe("License Core Logic", () => {
lastChecked: expect.any(Date),
isPendingDowngrade: false,
fallbackLevel: "live" as const,
status: "active" as const,
};
test("should return cached license from FETCH_LICENSE_CACHE_KEY if available and valid", async () => {
@@ -233,6 +234,7 @@ describe("License Core Logic", () => {
lastChecked: previousTime,
isPendingDowngrade: true,
fallbackLevel: "grace" as const,
status: "unreachable" as const,
});
});
@@ -309,6 +311,7 @@ describe("License Core Logic", () => {
lastChecked: expect.any(Date),
isPendingDowngrade: false,
fallbackLevel: "default" as const,
status: "unreachable" as const,
});
});
@@ -356,6 +359,7 @@ describe("License Core Logic", () => {
lastChecked: expect.any(Date),
isPendingDowngrade: false,
fallbackLevel: "default" as const,
status: "unreachable" as const,
});
});
@@ -389,6 +393,7 @@ describe("License Core Logic", () => {
lastChecked: expect.any(Date),
isPendingDowngrade: false,
fallbackLevel: "default" as const,
status: "no-license" as const,
});
expect(mockCache.get).not.toHaveBeenCalled();
expect(mockCache.set).not.toHaveBeenCalled();
@@ -414,6 +419,7 @@ describe("License Core Logic", () => {
lastChecked: expect.any(Date),
isPendingDowngrade: false,
fallbackLevel: "default" as const,
status: "no-license" as const,
});
});
});

View File

@@ -38,6 +38,17 @@ const CONFIG = {
// Types
type FallbackLevel = "live" | "cached" | "grace" | "default";
type TEnterpriseLicenseStatusReturn = "active" | "expired" | "unreachable" | "no-license";
type TEnterpriseLicenseResult = {
active: boolean;
features: TEnterpriseLicenseFeatures | null;
lastChecked: Date;
isPendingDowngrade: boolean;
fallbackLevel: FallbackLevel;
status: TEnterpriseLicenseStatusReturn;
};
type TPreviousResult = {
active: boolean;
lastChecked: Date;
@@ -90,7 +101,7 @@ class LicenseApiError extends LicenseError {
// Cache keys using enterprise-grade hierarchical patterns
const getCacheIdentifier = () => {
if (typeof window !== "undefined") {
if (globalThis.window !== undefined) {
return "browser"; // Browser environment
}
if (!env.ENTERPRISE_LICENSE_KEY) {
@@ -142,36 +153,50 @@ const validateConfig = () => {
};
// Cache functions with async pattern
let getPreviousResultPromise: Promise<TPreviousResult> | null = null;
const getPreviousResult = async (): Promise<TPreviousResult> => {
if (typeof window !== "undefined") {
if (getPreviousResultPromise) return getPreviousResultPromise;
getPreviousResultPromise = (async () => {
if (globalThis.window !== undefined) {
return {
active: false,
lastChecked: new Date(0),
features: DEFAULT_FEATURES,
};
}
try {
const result = await cache.get<TPreviousResult>(getCacheKeys().PREVIOUS_RESULT_CACHE_KEY);
if (result.ok && result.data) {
return {
...result.data,
lastChecked: new Date(result.data.lastChecked),
};
}
} catch (error) {
logger.error({ error }, "Failed to get previous result from cache");
}
return {
active: false,
lastChecked: new Date(0),
features: DEFAULT_FEATURES,
};
}
})();
try {
const result = await cache.get<TPreviousResult>(getCacheKeys().PREVIOUS_RESULT_CACHE_KEY);
if (result.ok && result.data) {
return {
...result.data,
lastChecked: new Date(result.data.lastChecked),
};
}
} catch (error) {
logger.error({ error }, "Failed to get previous result from cache");
}
getPreviousResultPromise
.finally(() => {
getPreviousResultPromise = null;
})
.catch(() => {});
return {
active: false,
lastChecked: new Date(0),
features: DEFAULT_FEATURES,
};
return getPreviousResultPromise;
};
const setPreviousResult = async (previousResult: TPreviousResult) => {
if (typeof window !== "undefined") return;
if (globalThis.window !== undefined) return;
try {
const result = await cache.set(
@@ -221,12 +246,21 @@ const validateLicenseDetails = (data: unknown): TEnterpriseLicenseDetails => {
};
// Fallback functions
let memoryCache: {
data: TEnterpriseLicenseResult;
timestamp: number;
} | null = null;
const MEMORY_CACHE_TTL_MS = 60 * 1000; // 1 minute memory cache to avoid stampedes and reduce load when Redis is slow
let getEnterpriseLicensePromise: Promise<TEnterpriseLicenseResult> | null = null;
const getFallbackLevel = (
liveLicense: TEnterpriseLicenseDetails | null,
previousResult: TPreviousResult,
currentTime: Date
): FallbackLevel => {
if (liveLicense) return "live";
if (liveLicense?.status === "active") return "live";
if (previousResult.active) {
const elapsedTime = currentTime.getTime() - previousResult.lastChecked.getTime();
return elapsedTime < CONFIG.CACHE.GRACE_PERIOD_MS ? "grace" : "default";
@@ -234,7 +268,7 @@ const getFallbackLevel = (
return "default";
};
const handleInitialFailure = async (currentTime: Date) => {
const handleInitialFailure = async (currentTime: Date): Promise<TEnterpriseLicenseResult> => {
const initialFailResult: TPreviousResult = {
active: false,
features: DEFAULT_FEATURES,
@@ -247,10 +281,13 @@ const handleInitialFailure = async (currentTime: Date) => {
lastChecked: currentTime,
isPendingDowngrade: false,
fallbackLevel: "default" as const,
status: "unreachable" as const,
};
};
// API functions
let fetchLicensePromise: Promise<TEnterpriseLicenseDetails | null> | null = null;
const fetchLicenseFromServerInternal = async (retryCount = 0): Promise<TEnterpriseLicenseDetails | null> => {
if (!env.ENTERPRISE_LICENSE_KEY) return null;
@@ -266,6 +303,7 @@ const fetchLicenseFromServerInternal = async (retryCount = 0): Promise<TEnterpri
// first millisecond of next year => current year is fully included
const startOfNextYear = new Date(now.getFullYear() + 1, 0, 1);
const startTime = Date.now();
const [instanceId, responseCount] = await Promise.all([
// Skip instance ID during E2E tests to avoid license key conflicts
// as the instance ID changes with each test run
@@ -279,6 +317,11 @@ const fetchLicenseFromServerInternal = async (retryCount = 0): Promise<TEnterpri
},
}),
]);
const duration = Date.now() - startTime;
if (duration > 1000) {
logger.warn({ duration, responseCount }, "Slow license check prerequisite data fetching (DB count)");
}
// No organization exists, cannot perform license check
// (skip this check during E2E tests as we intentionally use null)
@@ -311,7 +354,19 @@ const fetchLicenseFromServerInternal = async (retryCount = 0): Promise<TEnterpri
if (res.ok) {
const responseJson = (await res.json()) as { data: unknown };
return validateLicenseDetails(responseJson.data);
const licenseDetails = validateLicenseDetails(responseJson.data);
logger.debug(
{
status: licenseDetails.status,
instanceId: instanceId ?? "not-set",
responseCount,
timestamp: new Date().toISOString(),
},
"License check API response received"
);
return licenseDetails;
}
const error = new LicenseApiError(`License check API responded with status: ${res.status}`, res.status);
@@ -342,23 +397,41 @@ export const fetchLicense = async (): Promise<TEnterpriseLicenseDetails | null>
return null;
}
return await cache.withCache(
async () => {
return await fetchLicenseFromServerInternal();
},
getCacheKeys().FETCH_LICENSE_CACHE_KEY,
CONFIG.CACHE.FETCH_LICENSE_TTL_MS
);
if (fetchLicensePromise) {
return fetchLicensePromise;
}
fetchLicensePromise = (async () => {
return await cache.withCache(
async () => {
return await fetchLicenseFromServerInternal();
},
getCacheKeys().FETCH_LICENSE_CACHE_KEY,
CONFIG.CACHE.FETCH_LICENSE_TTL_MS
);
})();
fetchLicensePromise
.finally(() => {
fetchLicensePromise = null;
})
.catch(() => {});
return fetchLicensePromise;
};
export const getEnterpriseLicense = reactCache(
async (): Promise<{
active: boolean;
features: TEnterpriseLicenseFeatures | null;
lastChecked: Date;
isPendingDowngrade: boolean;
fallbackLevel: FallbackLevel;
}> => {
export const getEnterpriseLicense = reactCache(async (): Promise<TEnterpriseLicenseResult> => {
if (
process.env.NODE_ENV !== "test" &&
memoryCache &&
Date.now() - memoryCache.timestamp < MEMORY_CACHE_TTL_MS
) {
return memoryCache.data;
}
if (getEnterpriseLicensePromise) return getEnterpriseLicensePromise;
getEnterpriseLicensePromise = (async () => {
validateConfig();
if (!env.ENTERPRISE_LICENSE_KEY || env.ENTERPRISE_LICENSE_KEY.length === 0) {
@@ -368,12 +441,11 @@ export const getEnterpriseLicense = reactCache(
lastChecked: new Date(),
isPendingDowngrade: false,
fallbackLevel: "default" as const,
status: "no-license" as const,
};
}
const currentTime = new Date();
const liveLicenseDetails = await fetchLicense();
const previousResult = await getPreviousResult();
const [liveLicenseDetails, previousResult] = await Promise.all([fetchLicense(), getPreviousResult()]);
const fallbackLevel = getFallbackLevel(liveLicenseDetails, previousResult, currentTime);
trackFallbackUsage(fallbackLevel);
@@ -381,41 +453,84 @@ export const getEnterpriseLicense = reactCache(
let currentLicenseState: TPreviousResult | undefined;
switch (fallbackLevel) {
case "live":
case "live": {
if (!liveLicenseDetails) throw new Error("Invalid state: live license expected");
currentLicenseState = {
active: liveLicenseDetails.status === "active",
features: liveLicenseDetails.features,
lastChecked: currentTime,
};
await setPreviousResult(currentLicenseState);
return {
// Only update previous result if it's actually different or if it's old (1 hour)
// This prevents hammering Redis on every request when the license is active
if (
!previousResult.active ||
previousResult.active !== currentLicenseState.active ||
currentTime.getTime() - previousResult.lastChecked.getTime() > 60 * 60 * 1000
) {
await setPreviousResult(currentLicenseState);
}
const liveResult: TEnterpriseLicenseResult = {
active: currentLicenseState.active,
features: currentLicenseState.features,
lastChecked: currentTime,
isPendingDowngrade: false,
fallbackLevel: "live" as const,
status: liveLicenseDetails.status,
};
memoryCache = { data: liveResult, timestamp: Date.now() };
return liveResult;
}
case "grace":
case "grace": {
if (!validateFallback(previousResult)) {
return handleInitialFailure(currentTime);
return await handleInitialFailure(currentTime);
}
return {
const graceResult: TEnterpriseLicenseResult = {
active: previousResult.active,
features: previousResult.features,
lastChecked: previousResult.lastChecked,
isPendingDowngrade: true,
fallbackLevel: "grace" as const,
status: (liveLicenseDetails?.status as TEnterpriseLicenseStatusReturn) ?? "unreachable",
};
memoryCache = { data: graceResult, timestamp: Date.now() };
return graceResult;
}
case "default":
return handleInitialFailure(currentTime);
case "default": {
if (liveLicenseDetails?.status === "expired") {
const expiredResult: TEnterpriseLicenseResult = {
active: false,
features: DEFAULT_FEATURES,
lastChecked: currentTime,
isPendingDowngrade: false,
fallbackLevel: "default" as const,
status: "expired" as const,
};
memoryCache = { data: expiredResult, timestamp: Date.now() };
return expiredResult;
}
const failResult = await handleInitialFailure(currentTime);
memoryCache = { data: failResult, timestamp: Date.now() };
return failResult;
}
}
return handleInitialFailure(currentTime);
}
);
const finalFailResult = await handleInitialFailure(currentTime);
memoryCache = { data: finalFailResult, timestamp: Date.now() };
return finalFailResult;
})();
getEnterpriseLicensePromise
.finally(() => {
getEnterpriseLicensePromise = null;
})
.catch(() => {});
return getEnterpriseLicensePromise;
});
export const getLicenseFeatures = async (): Promise<TEnterpriseLicenseFeatures | null> => {
try {

View File

@@ -15,6 +15,7 @@ type TEnterpriseLicense = {
lastChecked: Date;
isPendingDowngrade: boolean;
fallbackLevel: string;
status: "active" | "expired" | "unreachable" | "no-license";
};
export const ZEnvironmentAuth = z.object({

View File

@@ -425,11 +425,19 @@ export const SurveyMenuBar = ({
const segment = await handleSegmentUpdate();
clearSurveyLocalStorage();
await updateSurveyAction({
const publishResult = await updateSurveyAction({
...localSurvey,
status,
segment,
});
if (!publishResult?.data) {
const errorMessage = getFormattedErrorMessage(publishResult);
toast.error(errorMessage);
setIsSurveyPublishing(false);
return;
}
setIsSurveyPublishing(false);
// Set flag to prevent beforeunload warning during navigation
isSuccessfullySavedRef.current = true;
@@ -467,7 +475,7 @@ export const SurveyMenuBar = ({
/>
</div>
<div className="mt-3 flex items-center gap-2 sm:mt-0 sm:ml-4">
<div className="mt-3 flex items-center gap-2 sm:ml-4 sm:mt-0">
<AutoSaveIndicator isDraft={localSurvey.status === "draft"} lastSaved={lastAutoSaved} />
{!isStorageConfigured && (
<div>

View File

@@ -12,6 +12,7 @@ interface PendingDowngradeBannerProps {
isPendingDowngrade: boolean;
environmentId: string;
locale: TUserLocale;
status: "active" | "expired" | "unreachable" | "no-license";
}
export const PendingDowngradeBanner = ({
@@ -20,11 +21,12 @@ export const PendingDowngradeBanner = ({
isPendingDowngrade,
environmentId,
locale,
status,
}: PendingDowngradeBannerProps) => {
const threeDaysInMillis = 3 * 24 * 60 * 60 * 1000;
const { t } = useTranslation();
const isLastCheckedWithin72Hours = lastChecked
? new Date().getTime() - lastChecked.getTime() < threeDaysInMillis
? Date.now() - lastChecked.getTime() < threeDaysInMillis
: false;
const scheduledDowngradeDate = new Date(lastChecked.getTime() + threeDaysInMillis);
@@ -36,7 +38,34 @@ export const PendingDowngradeBanner = ({
const [show, setShow] = useState(true);
if (show && active && isPendingDowngrade) {
const isExpired = status === "expired";
const getDescription = () => {
if (isExpired) {
const expiredMessage = t("common.your_license_has_expired_please_renew");
const downgradedMessage = t("common.you_are_downgraded_to_the_community_edition");
return `${expiredMessage} ${downgradedMessage}`;
}
const unreachableMessage = t(
"common.we_were_unable_to_verify_your_license_because_the_license_server_is_unreachable"
);
if (!active) {
return `${unreachableMessage} ${t("common.you_are_downgraded_to_the_community_edition")}`;
}
if (isLastCheckedWithin72Hours) {
const scheduledMessage = t("common.you_will_be_downgraded_to_the_community_edition_on_date", {
date: formattedDate,
});
return `${unreachableMessage} ${scheduledMessage}`;
}
return `${unreachableMessage} ${t("common.you_are_downgraded_to_the_community_edition")}`;
};
if (show && (isPendingDowngrade || isExpired)) {
return (
<div
aria-live="assertive"
@@ -50,17 +79,10 @@ export const PendingDowngradeBanner = ({
<TriangleAlertIcon className="text-error h-6 w-6" aria-hidden="true" />
</div>
<div className="ml-3 w-0 flex-1">
<p className="text-base font-medium text-slate-900">{t("common.pending_downgrade")}</p>
<p className="mt-1 text-sm text-slate-500">
{t(
"common.we_were_unable_to_verify_your_license_because_the_license_server_is_unreachable"
)}{" "}
{isLastCheckedWithin72Hours
? t("common.you_will_be_downgraded_to_the_community_edition_on_date", {
date: formattedDate,
})
: t("common.you_are_downgraded_to_the_community_edition")}
<p className="text-base font-medium text-slate-900">
{isExpired ? t("common.license_expired") : t("common.pending_downgrade")}
</p>
<p className="mt-1 text-sm text-slate-500">{getDescription()}</p>
<Link href={`/environments/${environmentId}/settings/enterprise`}>
<span className="text-sm text-slate-900">{t("common.learn_more")}</span>

View File

@@ -259,6 +259,7 @@ export const PreviewSurvey = ({
setBlockId = f;
}}
onFinished={onFinished}
placement={placement}
isSpamProtectionEnabled={isSpamProtectionEnabled}
/>
</Modal>
@@ -363,6 +364,7 @@ export const PreviewSurvey = ({
}}
onFinished={onFinished}
isSpamProtectionEnabled={isSpamProtectionEnabled}
placement={placement}
/>
</Modal>
) : (

View File

@@ -170,7 +170,7 @@ export const getLanguageCode = (survey: TEnvironmentStateSurvey, language?: stri
const selectedLanguage = survey.languages.find((surveyLanguage) => {
return (
surveyLanguage.language.code === language.toLowerCase() ||
surveyLanguage.language.code.toLowerCase() === language.toLowerCase() ||
surveyLanguage.language.alias?.toLowerCase() === language.toLowerCase()
);
});

View File

@@ -2,7 +2,7 @@ import * as React from "react";
import { ElementError } from "@/components/general/element-error";
import { ElementHeader } from "@/components/general/element-header";
import { Label } from "@/components/general/label";
import { cn } from "@/lib/utils";
import { cn, getRTLScaleOptionClasses } from "@/lib/utils";
interface NPSProps {
/** Unique identifier for the element container */
@@ -97,18 +97,9 @@ function NPS({
const isLast = number === 10; // Last option is 10
const isFirst = number === 0; // First option is 0
// Determine border radius and border classes
// Use right border for all items to create separators, left border only on first item
let borderRadiusClasses = "";
let borderClasses = "border-t border-b border-r";
if (isFirst) {
borderRadiusClasses = dir === "rtl" ? "rounded-r-input" : "rounded-l-input";
borderClasses = "border-t border-b border-l border-r";
} else if (isLast) {
borderRadiusClasses = dir === "rtl" ? "rounded-l-input" : "rounded-r-input";
// Last item keeps right border for rounded corner
}
// Use CSS logical properties for RTL-aware borders and border radius
// The fieldset's dir attribute automatically handles direction
const { borderRadiusClasses, borderClasses } = getRTLScaleOptionClasses(isFirst, isLast);
return (
// eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- label is interactive
@@ -183,7 +174,7 @@ function NPS({
{/* NPS Options */}
<div className="relative">
<ElementError errorMessage={errorMessage} dir={dir} />
<fieldset className="w-full px-[2px]">
<fieldset className="w-full px-[2px]" dir={dir}>
<legend className="sr-only">NPS rating options</legend>
<div className="flex w-full">{npsOptions.map((number) => renderNPSOption(number))}</div>

View File

@@ -15,7 +15,7 @@ import {
TiredFace,
WearyFace,
} from "@/components/general/smileys";
import { cn } from "@/lib/utils";
import { cn, getRTLScaleOptionClasses } from "@/lib/utils";
/**
* Get smiley color class based on range and index
@@ -220,18 +220,9 @@ function Rating({
const isLast = totalLength === number;
const isFirst = number === 1;
// Determine border radius and border classes
// Use right border for all items to create separators, left border only on first item
let borderRadiusClasses = "";
let borderClasses = "border-t border-b border-r";
if (isFirst) {
borderRadiusClasses = dir === "rtl" ? "rounded-r-input" : "rounded-l-input";
borderClasses = "border-t border-b border-l border-r";
} else if (isLast) {
borderRadiusClasses = dir === "rtl" ? "rounded-l-input" : "rounded-r-input";
// Last item keeps right border for rounded corner
}
// Use CSS logical properties for RTL-aware borders and border radius
// The parent div's dir attribute automatically handles direction
const { borderRadiusClasses, borderClasses } = getRTLScaleOptionClasses(isFirst, isLast);
return (
// eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- label is interactive
@@ -418,7 +409,7 @@ function Rating({
{/* Rating Options */}
<div className="relative">
<ElementError errorMessage={errorMessage} dir={dir} />
<fieldset className="w-full">
<fieldset className="w-full" dir={dir}>
<legend className="sr-only">Rating options</legend>
<div className="flex w-full px-[2px]">
{ratingOptions.map((number, index) => {

View File

@@ -35,3 +35,29 @@ export const stripInlineStyles = (html: string): string => {
KEEP_CONTENT: true,
});
};
/**
* Generate RTL-aware border radius and border classes for rating/NPS scale options
* Uses CSS logical properties that automatically adapt to text direction
* @param isFirst - Whether this is the first item in the scale
* @param isLast - Whether this is the last item in the scale
* @returns Object containing borderRadiusClasses and borderClasses
*/
export const getRTLScaleOptionClasses = (
isFirst: boolean,
isLast: boolean
): { borderRadiusClasses: string; borderClasses: string } => {
const borderRadiusClasses = cn(
isFirst &&
"[border-start-start-radius:var(--fb-input-border-radius)] [border-end-start-radius:var(--fb-input-border-radius)]",
isLast &&
"[border-start-end-radius:var(--fb-input-border-radius)] [border-end-end-radius:var(--fb-input-border-radius)]"
);
const borderClasses = cn(
"border-t border-b border-e", // block borders (top/bottom) and inline-end border
isFirst && "border-s" // inline-start border for first item
);
return { borderRadiusClasses, borderClasses };
};

View File

@@ -76,6 +76,7 @@ export function Survey({
isSpamProtectionEnabled,
dir = "auto",
setDir,
placement,
}: SurveyContainerProps) {
let apiClient: ApiClient | null = null;
@@ -916,6 +917,7 @@ export function Survey({
setBlockId={setBlockId}
shouldResetBlockId={shouldResetQuestionId}
fullSizeCards={fullSizeCards}
placement={placement}
/>
);
}

View File

@@ -2,6 +2,7 @@ import { MutableRef } from "preact/hooks";
import { useEffect, useMemo, useState } from "preact/hooks";
import { JSX } from "preact/jsx-runtime";
import React from "react";
import { type TPlacement } from "@formbricks/types/common";
import { TJsEnvironmentStateSurvey } from "@formbricks/types/js";
import { TCardArrangementOptions } from "@formbricks/types/styling";
@@ -17,6 +18,7 @@ interface StackedCardProps {
cardWidth: number;
hovered: boolean;
cardArrangement: TCardArrangementOptions;
placement: TPlacement;
}
export const StackedCard = ({
@@ -31,17 +33,24 @@ export const StackedCard = ({
cardWidth,
hovered,
cardArrangement,
placement,
}: StackedCardProps) => {
const isHidden = offset < 0;
const [delayedOffset, setDelayedOffset] = useState<number>(offset);
const [contentOpacity, setContentOpacity] = useState<number>(0);
const currentCardHeight = offset === 0 ? "auto" : offset < 0 ? "initial" : cardHeight;
const getBottomStyles = () => {
const getTopBottomStyles = () => {
if (survey.type !== "link")
return {
bottom: 0,
};
if (placement === "bottomLeft" || placement === "bottomRight") {
return {
bottom: 0,
};
} else if (placement === "topLeft" || placement === "topRight") {
return {
top: 0,
};
}
};
const getDummyCardContent = () => {
@@ -111,7 +120,7 @@ export const StackedCard = ({
pointerEvents: offset === 0 ? "auto" : "none",
...borderStyles,
...straightCardArrangementStyles,
...getBottomStyles(),
...getTopBottomStyles(),
}}
className="pointer rounded-custom bg-survey-bg absolute inset-x-0 overflow-hidden">
<div

View File

@@ -1,5 +1,6 @@
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import type { JSX } from "react";
import { type TPlacement } from "@formbricks/types/common";
import { type TJsEnvironmentStateSurvey } from "@formbricks/types/js";
import { type TProjectStyling } from "@formbricks/types/project";
import { type TCardArrangementOptions } from "@formbricks/types/styling";
@@ -19,6 +20,7 @@ interface StackedCardsContainerProps {
setBlockId: (blockId: string) => void;
shouldResetBlockId?: boolean;
fullSizeCards: boolean;
placement?: TPlacement;
}
export function StackedCardsContainer({
@@ -30,6 +32,7 @@ export function StackedCardsContainer({
setBlockId,
shouldResetBlockId = true,
fullSizeCards = false,
placement = "bottomRight",
}: Readonly<StackedCardsContainerProps>) {
const [hovered, setHovered] = useState(false);
const highlightBorderColor = survey.styling?.overwriteThemeStyling
@@ -179,6 +182,7 @@ export function StackedCardsContainer({
cardWidth={cardWidth}
hovered={hovered}
cardArrangement={cardArrangement}
placement={placement}
/>
);
})

View File

@@ -36,18 +36,35 @@ export const renderSurvey = (props: SurveyContainerProps) => {
throw new Error(`renderSurvey: Element with id ${containerId} not found.`);
}
const { placement, darkOverlay, onClose, clickOutside, ...surveyInlineProps } = props;
// if survey type is link, we don't pass the placement, darkOverlay, clickOutside, onClose
if (props.survey.type === "link") {
const { placement, darkOverlay, onClose, clickOutside, ...surveyInlineProps } = props;
render(
h(
I18nProvider,
{ language },
h(RenderSurvey, {
...surveyInlineProps,
})
),
element
);
render(
h(
I18nProvider,
{ language },
h(RenderSurvey, {
...surveyInlineProps,
})
),
element
);
} else {
// For non-link surveys, pass placement through so it can be used in StackedCard
const { darkOverlay, onClose, clickOutside, ...surveyInlineProps } = props;
render(
h(
I18nProvider,
{ language },
h(RenderSurvey, {
...surveyInlineProps,
})
),
element
);
}
} else {
const modalContainer = document.createElement("div");
modalContainer.id = "formbricks-modal-container";