Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,199 @@
|
||||
import { useFetcher, useNavigate, useParams } from "react-router";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import { OnboardingSessionWithDetails } from "~/modules/onboarding/db/onboardingSessions.db.server";
|
||||
import { OnboardingSessionActionDto } from "~/modules/onboarding/dtos/OnboardingSessionActionDto";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { OnboardingBlockDto } from "./OnboardingBlockUtils";
|
||||
import { resolveOnboardingHref } from "./OnboardingLinkUtils";
|
||||
import OnboardingVariantModal from "./OnboardingVariantModal";
|
||||
|
||||
export default function OnboardingBlock({
|
||||
session,
|
||||
item,
|
||||
open,
|
||||
onClose,
|
||||
}: {
|
||||
session?: OnboardingSessionWithDetails | null;
|
||||
item: OnboardingBlockDto;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const fetcher = useFetcher();
|
||||
const navigate = useNavigate();
|
||||
const params = useParams();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const rootData = useRootData();
|
||||
|
||||
const errorModal = useRef<RefErrorModal>(null);
|
||||
|
||||
const [block, setBlock] = useState<OnboardingBlockDto>(item);
|
||||
const [currentStepIdx, setCurrentStepIdx] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
setBlock(item);
|
||||
}, [item]);
|
||||
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
const stepIdx = session.sessionSteps.findIndex((f) => !f.completedAt);
|
||||
if (stepIdx !== undefined && stepIdx !== -1 && stepIdx < item.steps.length) {
|
||||
setCurrentStepIdx(stepIdx);
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const [stepStates, setStepStates] = useState<{ idx: number; state: { [key: string]: string } }[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (session && !session.startedAt) {
|
||||
const form = new FormData();
|
||||
form.set("action", "started");
|
||||
submitSessionForm(form);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
function onUpdateCurrentStepState(state: { [key: string]: string }) {
|
||||
setStepStates((prev) => {
|
||||
const idx = prev.findIndex((x) => x.idx === currentStepIdx);
|
||||
if (idx === -1) {
|
||||
return [...prev, { idx: currentStepIdx, state }];
|
||||
}
|
||||
return [...prev.slice(0, idx), { idx: currentStepIdx, state }, ...prev.slice(idx + 1)];
|
||||
});
|
||||
}
|
||||
|
||||
function submitSessionForm(form: FormData, actions?: OnboardingSessionActionDto[]) {
|
||||
if (session) {
|
||||
if (rootData.csrf && !form.has("csrf")) {
|
||||
form.set("csrf", rootData.csrf);
|
||||
}
|
||||
if (actions) {
|
||||
actions
|
||||
.filter((f) => f.value)
|
||||
.forEach((action) => {
|
||||
form.append("actions[]", JSON.stringify(action));
|
||||
});
|
||||
}
|
||||
fetcher.submit(form, {
|
||||
action: "/onboarding/" + session.id,
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function onDismiss() {
|
||||
if (validInput()) {
|
||||
if (session && !session.dismissedAt) {
|
||||
const form = new FormData();
|
||||
form.set("action", "dismissed");
|
||||
submitSessionForm(form);
|
||||
}
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
|
||||
function setStep(idx: number) {
|
||||
const form = new FormData();
|
||||
form.set("action", "set-step");
|
||||
form.set("fromIdx", currentStepIdx.toString());
|
||||
form.set("toIdx", idx.toString());
|
||||
const currentState = stepStates.find((x) => x.idx === currentStepIdx);
|
||||
const keyValuePairs = Object.entries(currentState?.state || {});
|
||||
submitSessionForm(
|
||||
form,
|
||||
keyValuePairs.map(([key, value]) => {
|
||||
return { type: "input", name: key, value };
|
||||
})
|
||||
);
|
||||
|
||||
const currentStep = block.steps[currentStepIdx];
|
||||
currentStep.completedAt = new Date();
|
||||
setBlock({ ...block, steps: [...block.steps.slice(0, currentStepIdx), currentStep, ...block.steps.slice(currentStepIdx + 1)] });
|
||||
|
||||
if (validInput()) {
|
||||
setCurrentStepIdx(idx);
|
||||
}
|
||||
}
|
||||
|
||||
function validInput() {
|
||||
const missingFields = getMissingFields();
|
||||
if (missingFields.length === 0) {
|
||||
return true;
|
||||
} else {
|
||||
errorModal.current?.show(t("shared.error"), t("onboarding.errors.missingInput", { 0: missingFields.join(", ") }));
|
||||
}
|
||||
}
|
||||
|
||||
function onComplete() {
|
||||
if (session && !session.completedAt) {
|
||||
const form = new FormData();
|
||||
form.set("action", "complete");
|
||||
form.set("fromIdx", currentStepIdx.toString());
|
||||
submitSessionForm(form);
|
||||
}
|
||||
|
||||
if (validInput()) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
|
||||
function onLinkClick(item: { text: string; href: string }) {
|
||||
const form = new FormData();
|
||||
form.set("action", "add-actions");
|
||||
submitSessionForm(form, [
|
||||
{
|
||||
type: "click",
|
||||
name: item.text,
|
||||
value: item.href,
|
||||
},
|
||||
]);
|
||||
|
||||
const linkWithVariables = resolveOnboardingHref(item.href, params, appOrAdminData?.user?.id);
|
||||
|
||||
navigate(linkWithVariables);
|
||||
onClose();
|
||||
}
|
||||
function getMissingFields() {
|
||||
const step = block.steps[currentStepIdx];
|
||||
const fields: string[] = [];
|
||||
step.input.forEach((input) => {
|
||||
if (input.isRequired) {
|
||||
const currentState = stepStates.find((x) => x.idx === currentStepIdx);
|
||||
if (!currentState?.state[input.name]) {
|
||||
fields.push(t(input.title));
|
||||
}
|
||||
}
|
||||
});
|
||||
return fields;
|
||||
}
|
||||
|
||||
function onClosing() {
|
||||
if (validInput()) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{item.style === "modal" && (
|
||||
<OnboardingVariantModal
|
||||
block={block}
|
||||
currentStepIdx={currentStepIdx}
|
||||
setStep={setStep}
|
||||
open={open}
|
||||
onClose={onClosing}
|
||||
onDismiss={onDismiss}
|
||||
onComplete={onComplete}
|
||||
onLinkClick={onLinkClick}
|
||||
onUpdateCurrentStepState={onUpdateCurrentStepState}
|
||||
/>
|
||||
)}
|
||||
<ErrorModal ref={errorModal} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EntityIcon from "~/components/layouts/icons/EntityIcon";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
import QuestionMarkFilledIcon from "~/components/ui/icons/QuestionMarkFilledIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import InputCheckbox from "~/components/ui/input/InputCheckbox";
|
||||
import InputRadioGroup from "~/components/ui/input/InputRadioGroup";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import CollapsibleRow from "~/components/ui/tables/CollapsibleRow";
|
||||
import OnboardingStepUtils from "~/modules/onboarding/utils/OnboardingStepUtils";
|
||||
import OnboardingGridForm from "./grid/OnboardingGridForm";
|
||||
import StringUtils from "~/utils/shared/StringUtils";
|
||||
import { defaultOnboardingStepBlocks } from "./defaultOnboarding/defaultOnboardingStepBlocks";
|
||||
import {
|
||||
defaultOnboardingBlock,
|
||||
defaultOnboardingStepBlock,
|
||||
OnboardingBlockDto,
|
||||
OnboardingBlockStyle,
|
||||
OnboardingBlockStyles,
|
||||
OnboardingInputOptionDto,
|
||||
OnboardingStepBlockDto,
|
||||
} from "./OnboardingBlockUtils";
|
||||
import ReactSortablePkg from "react-sortablejs";
|
||||
const { ReactSortable } = ReactSortablePkg;
|
||||
|
||||
export default function OnboardingBlockForm({ item, onUpdate }: { item?: OnboardingBlockDto; onUpdate: (item: OnboardingBlockDto) => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [state, setState] = useState<OnboardingBlockDto>(item || defaultOnboardingBlock);
|
||||
useEffect(() => {
|
||||
onUpdate(state);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [state]);
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<InputGroup title={t("onboarding.block.design")}>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
className="col-span-2"
|
||||
title={t("onboarding.block.style")}
|
||||
value={state.style}
|
||||
setValue={(value) => setState({ ...state, style: value as OnboardingBlockStyle })}
|
||||
options={OnboardingBlockStyles.map((f) => f)}
|
||||
/>
|
||||
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
title={t("onboarding.block.height")}
|
||||
value={state.height}
|
||||
disabled={state.style !== "modal"}
|
||||
setValue={(value) => setState({ ...state, height: value as any })}
|
||||
options={[
|
||||
{ value: "xs", name: "xs" },
|
||||
{ value: "sm", name: "sm" },
|
||||
{ value: "md", name: "md" },
|
||||
{ value: "lg", name: "lg" },
|
||||
{ value: "xl", name: "xl" },
|
||||
{ value: "auto", name: "auto" },
|
||||
]}
|
||||
/>
|
||||
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
title={t("onboarding.block.canBeDismissed")}
|
||||
value={state.canBeDismissed ? "true" : "false"}
|
||||
disabled={state.style !== "modal"}
|
||||
setValue={(value) => setState({ ...state, canBeDismissed: value === "true" })}
|
||||
options={[
|
||||
{ value: "true", name: t("shared.yes") },
|
||||
{ value: "false", name: t("shared.no") },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
|
||||
<InputGroup title={t("onboarding.step.plural")} description={t("onboarding.block.stepsDescription")}>
|
||||
<div className="space-y-2">
|
||||
<ReactSortable className="flex flex-col space-y-2" animation={200} list={state.steps} setList={(steps) => setState({ ...state, steps })}>
|
||||
{state.steps.map((item, index) => (
|
||||
<CollapsibleRow
|
||||
draggable
|
||||
key={item.id}
|
||||
title={item.title || t("onboarding.block.untitledStep")}
|
||||
value={OnboardingStepUtils.getStepDescription(item)}
|
||||
initial={!item.title}
|
||||
onRemove={() => {
|
||||
const steps = state.steps ?? [];
|
||||
const index = steps.findIndex((e) => e.id === item.id);
|
||||
if (index > -1) {
|
||||
steps.splice(index, 1);
|
||||
setState({ ...state, steps });
|
||||
}
|
||||
}}
|
||||
>
|
||||
<StepForm
|
||||
item={item}
|
||||
onUpdate={(item) => {
|
||||
const steps = state.steps ?? [];
|
||||
steps[index] = item;
|
||||
setState({ ...state, steps });
|
||||
}}
|
||||
/>
|
||||
</CollapsibleRow>
|
||||
))}
|
||||
</ReactSortable>
|
||||
<div className="flex justify-between space-x-2">
|
||||
<ButtonTertiary
|
||||
onClick={() =>
|
||||
setState({
|
||||
...state,
|
||||
steps: [
|
||||
...(state.steps ?? []),
|
||||
{
|
||||
id: Math.floor(Math.random() * 10000).toString(),
|
||||
// ...defaultOnboardingStepBlock,
|
||||
title: "",
|
||||
description: "",
|
||||
links: [],
|
||||
gallery: [],
|
||||
input: [],
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
{t("onboarding.block.actions.addStep")}
|
||||
</ButtonTertiary>
|
||||
<div>
|
||||
{state.steps.length > 0 ? (
|
||||
<ButtonTertiary
|
||||
destructive
|
||||
onClick={() => {
|
||||
if (prompt(t("onboarding.block.confirmClearPrompt")) === "yes") setState({ ...state, steps: [] });
|
||||
}}
|
||||
>
|
||||
{t("shared.clear")}
|
||||
</ButtonTertiary>
|
||||
) : (
|
||||
<ButtonTertiary onClick={() => setState({ ...state, steps: defaultOnboardingStepBlocks })}>{t("onboarding.block.actions.loadSampleSteps")}</ButtonTertiary>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</InputGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepForm({ item, onUpdate }: { item: OnboardingStepBlockDto; onUpdate: (item: OnboardingStepBlockDto) => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [state, setState] = useState<OnboardingStepBlockDto>(item || defaultOnboardingStepBlock);
|
||||
useEffect(() => {
|
||||
onUpdate(state);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [state]);
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 p-2">
|
||||
<InputText title={t("onboarding.step.title")} value={state.title} setValue={(e) => setState({ ...state, title: e?.toString() })} required />
|
||||
<InputText
|
||||
title={t("shared.description")}
|
||||
value={state.description}
|
||||
setValue={(e) => setState({ ...state, description: e?.toString() })}
|
||||
rows={5}
|
||||
hint={t("onboarding.block.markdownSupported")}
|
||||
/>
|
||||
<InputText
|
||||
title={t("shared.icon")}
|
||||
value={state.icon}
|
||||
setValue={(e) => setState({ ...state, icon: e?.toString() })}
|
||||
hint={<div className="text-muted-foreground">{t("onboarding.block.iconHint")}</div>}
|
||||
button={
|
||||
<div className="absolute inset-y-0 right-0 flex py-0.5 pr-0.5 ">
|
||||
<kbd className="border-border text-muted-foreground bg-secondary inline-flex w-10 items-center justify-center rounded border px-1 text-center font-sans text-xs font-medium">
|
||||
{state.icon ? (
|
||||
<EntityIcon className="text-muted-foreground h-7 w-7" icon={state.icon} title={state.title} />
|
||||
) : (
|
||||
<QuestionMarkFilledIcon className="text-muted-foreground h-5 w-5" aria-hidden="true" />
|
||||
)}
|
||||
</kbd>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
<InputGroup title={t("onboarding.block.links")}>
|
||||
<div className="flex flex-col space-y-2">
|
||||
{state.links.map((link, index) => (
|
||||
<div key={index} className="group relative grid grid-cols-4 gap-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
const links = state.links;
|
||||
links.splice(index, 1);
|
||||
setState({ ...state, links });
|
||||
}}
|
||||
type="button"
|
||||
className="bg-background text-muted-foreground absolute right-0 top-0 -mt-3 hidden origin-top-right justify-center rounded-full hover:text-red-500 group-hover:flex"
|
||||
>
|
||||
<XIcon className="h-6 w-6" />
|
||||
</button>
|
||||
<InputText
|
||||
title={t("shared.link")}
|
||||
value={link.text}
|
||||
setValue={(e) => setState({ ...state, links: state.links.map((step, i) => (i === index ? { ...step, text: e.toString() } : step)) })}
|
||||
/>
|
||||
<InputText
|
||||
title={t("onboarding.block.href")}
|
||||
value={link.href}
|
||||
setValue={(e) => setState({ ...state, links: state.links.map((step, i) => (i === index ? { ...step, href: e.toString() } : step)) })}
|
||||
/>
|
||||
<InputCheckbox
|
||||
title={t("onboarding.block.isPrimary")}
|
||||
value={link.isPrimary}
|
||||
setValue={(e) => setState({ ...state, links: state.links.map((link, i) => (i === index ? { ...link, isPrimary: Boolean(e) } : link)) })}
|
||||
/>
|
||||
<InputCheckbox
|
||||
title={t("onboarding.block.targetBlank")}
|
||||
value={link.target === "_blank"}
|
||||
setValue={(e) => setState({ ...state, links: state.links.map((link, i) => (i === index ? { ...link, target: e ? "_blank" : "" } : link)) })}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<ButtonTertiary onClick={() => setState({ ...state, links: [...state.links, { text: t("shared.link"), href: "#", isPrimary: false }] })}>
|
||||
{t("onboarding.block.actions.addLink")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</InputGroup>
|
||||
|
||||
<InputGroup title={t("onboarding.block.gallery")}>
|
||||
<div className="flex flex-col space-y-2">
|
||||
<ReactSortable className="flex flex-col space-y-2" animation={200} list={state.gallery} setList={(gallery) => setState({ ...state, gallery })}>
|
||||
{state.gallery.map((item, index) => (
|
||||
<CollapsibleRow
|
||||
key={index}
|
||||
title={item.title || t("onboarding.block.untitledGalleryItem")}
|
||||
value={item.title || t("onboarding.block.untitledGalleryItem")}
|
||||
initial={!item.title}
|
||||
onRemove={() => {
|
||||
const gallery = state.gallery ?? [];
|
||||
gallery.splice(index, 1);
|
||||
setState({ ...state, gallery });
|
||||
}}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
<InputRadioGroup
|
||||
title={t("onboarding.step.type")}
|
||||
value={item.type}
|
||||
setValue={(e) =>
|
||||
setState({
|
||||
...state,
|
||||
gallery: state.gallery.map((item, i) => (i === index ? { ...item, type: e?.toString() as "image" | "video" } : item)),
|
||||
})
|
||||
}
|
||||
options={[
|
||||
{ name: t("onboarding.block.mediaTypes.image"), value: "image" },
|
||||
{ name: t("onboarding.block.mediaTypes.video"), value: "video" },
|
||||
]}
|
||||
/>
|
||||
<InputText
|
||||
title={t("onboarding.step.title")}
|
||||
type="text"
|
||||
value={item.title}
|
||||
setValue={(e) => setState({ ...state, gallery: state.gallery.map((item, i) => (i === index ? { ...item, title: e.toString() } : item)) })}
|
||||
/>
|
||||
<InputText
|
||||
title={t("onboarding.block.src")}
|
||||
type="text"
|
||||
value={item.src}
|
||||
setValue={(e) => setState({ ...state, gallery: state.gallery.map((item, i) => (i === index ? { ...item, src: e.toString() } : item)) })}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleRow>
|
||||
))}
|
||||
</ReactSortable>
|
||||
<ButtonTertiary
|
||||
onClick={() =>
|
||||
setState({
|
||||
...state,
|
||||
gallery: [
|
||||
...(state.gallery ?? []),
|
||||
{
|
||||
id: Math.floor(Math.random() * 10000).toString(),
|
||||
type: "image",
|
||||
title: t("onboarding.block.defaultGalleryTitle", { number: state.gallery.length + 1 }),
|
||||
src: "",
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
{t("onboarding.block.actions.addGalleryItem")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</InputGroup>
|
||||
|
||||
<InputGroup title={t("onboarding.block.input")}>
|
||||
<div className="flex flex-col space-y-2">
|
||||
<OnboardingGridForm item={state.inputGrid} onUpdate={(item) => setState({ ...state, inputGrid: item })} />
|
||||
<ReactSortable className="flex flex-col space-y-2" animation={200} list={state.input} setList={(input) => setState({ ...state, input })}>
|
||||
{state.input.map((item, index) => (
|
||||
<CollapsibleRow
|
||||
key={index}
|
||||
title={item.title || t("onboarding.block.untitledInput")}
|
||||
value={item.title || t("onboarding.block.untitledInput")}
|
||||
initial={!item.title}
|
||||
onRemove={() => {
|
||||
const input = state.input ?? [];
|
||||
input.splice(index, 1);
|
||||
setState({ ...state, input });
|
||||
}}
|
||||
>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<InputText
|
||||
title={t("onboarding.step.title")}
|
||||
type="text"
|
||||
value={item.title}
|
||||
setValue={(e) =>
|
||||
setState({
|
||||
...state,
|
||||
input: state.input.map((item, i) =>
|
||||
i === index ? { ...item, title: e.toString(), name: StringUtils.toCamelCase(e?.toString().toLowerCase()) } : item
|
||||
),
|
||||
})
|
||||
}
|
||||
/>
|
||||
<InputText
|
||||
title={t("shared.name")}
|
||||
type="text"
|
||||
value={item.name}
|
||||
setValue={(e) => setState({ ...state, input: state.input.map((item, i) => (i === index ? { ...item, name: e.toString() } : item)) })}
|
||||
/>
|
||||
<InputCheckbox
|
||||
title={t("onboarding.block.isRequired")}
|
||||
value={item.isRequired}
|
||||
setValue={(e) => setState({ ...state, input: state.input.map((item, i) => (i === index ? { ...item, isRequired: Boolean(e) } : item)) })}
|
||||
/>
|
||||
|
||||
<InputSelect
|
||||
className="col-span-3"
|
||||
title={t("onboarding.step.type")}
|
||||
value={item.type}
|
||||
setValue={(e) =>
|
||||
setState({
|
||||
...state,
|
||||
input: state.input.map((item, i) => (i === index ? { ...item, type: e?.toString() as "text" | "select" } : item)),
|
||||
})
|
||||
}
|
||||
options={[
|
||||
{ name: t("onboarding.block.inputTypes.text"), value: "text" },
|
||||
{ name: t("onboarding.block.inputTypes.select"), value: "select" },
|
||||
]}
|
||||
/>
|
||||
{item.type === "select" && (
|
||||
<div className="col-span-3">
|
||||
<SelectOptionsForm
|
||||
options={item.options}
|
||||
setOptions={(options) => setState({ ...state, input: state.input.map((item, i) => (i === index ? { ...item, options } : item)) })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CollapsibleRow>
|
||||
))}
|
||||
</ReactSortable>
|
||||
<ButtonTertiary
|
||||
onClick={() =>
|
||||
setState({
|
||||
...state,
|
||||
input: [
|
||||
...(state.input ?? []),
|
||||
{
|
||||
id: Math.floor(Math.random() * 10000).toString(),
|
||||
type: "text",
|
||||
name: "",
|
||||
title: "",
|
||||
isRequired: false,
|
||||
options: [],
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
>
|
||||
{t("onboarding.block.actions.addInput")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</InputGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectOptionsForm({ options, setOptions }: { options: OnboardingInputOptionDto[]; setOptions: (options: OnboardingInputOptionDto[]) => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [state, setState] = useState<OnboardingInputOptionDto[]>(options ?? []);
|
||||
|
||||
useEffect(() => {
|
||||
setOptions(state);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [state]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col space-y-2">
|
||||
{options.map((option, index) => (
|
||||
<div key={index} className="group relative grid grid-cols-2 gap-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
const options = state ?? [];
|
||||
options.splice(index, 1);
|
||||
setState(options);
|
||||
}}
|
||||
type="button"
|
||||
className="bg-background text-muted-foreground absolute right-0 top-0 -mt-3 hidden origin-top-right justify-center rounded-full hover:text-red-500 group-hover:flex"
|
||||
>
|
||||
<XIcon className="h-6 w-6" />
|
||||
</button>
|
||||
<InputText
|
||||
title={t("onboarding.step.title")}
|
||||
value={option.name}
|
||||
setValue={(e) =>
|
||||
setState(
|
||||
options.map((option, i) =>
|
||||
i === index ? { ...option, name: e.toString(), value: StringUtils.toCamelCase(e?.toString().toLowerCase()) } : option
|
||||
)
|
||||
)
|
||||
}
|
||||
/>
|
||||
<InputText
|
||||
title={t("shared.value")}
|
||||
value={option.value}
|
||||
setValue={(e) => setState(options.map((option, i) => (i === index ? { ...option, value: e.toString() } : option)))}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<ButtonTertiary onClick={() => setState([...options, { value: "", name: "" }])}>{t("onboarding.block.actions.addOption")}</ButtonTertiary>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { OnboardingGridDto } from "./grid/OnboardingGridUtils";
|
||||
|
||||
export type OnboardingBlockDto = {
|
||||
style: OnboardingBlockStyle;
|
||||
title: string;
|
||||
canBeDismissed: boolean;
|
||||
height: OnboardingHeightDto;
|
||||
steps: OnboardingStepBlockDto[];
|
||||
};
|
||||
|
||||
export type OnboardingHeightDto = "xs" | "sm" | "md" | "lg" | "xl" | "auto";
|
||||
|
||||
export interface OnboardingStepBlockDto {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
links: OnboardingLinkDto[];
|
||||
gallery: OnboardingGalleryDto[];
|
||||
input: OnboardingInputDto[];
|
||||
inputGrid?: OnboardingGridDto;
|
||||
icon?: string;
|
||||
completedAt?: Date | null;
|
||||
}
|
||||
|
||||
interface OnboardingLinkDto {
|
||||
text: string;
|
||||
href: string;
|
||||
isPrimary: boolean;
|
||||
target?: string;
|
||||
}
|
||||
|
||||
interface OnboardingGalleryDto {
|
||||
id: string;
|
||||
type: "image" | "video";
|
||||
title: string;
|
||||
src: string;
|
||||
}
|
||||
|
||||
export interface OnboardingInputOptionDto {
|
||||
name: string;
|
||||
value: string;
|
||||
color?: Colors;
|
||||
}
|
||||
|
||||
interface OnboardingInputDto {
|
||||
id: string;
|
||||
type: "text" | "select";
|
||||
name: string;
|
||||
title: string;
|
||||
isRequired: boolean;
|
||||
options: OnboardingInputOptionDto[];
|
||||
}
|
||||
|
||||
export const OnboardingBlockStyles = [{ value: "modal", name: "Modal" }] as const;
|
||||
export type OnboardingBlockStyle = (typeof OnboardingBlockStyles)[number]["value"];
|
||||
|
||||
export const defaultOnboardingStepBlock: OnboardingStepBlockDto = {
|
||||
id: "",
|
||||
title: i18nT("onboarding.block.defaults.stepTitle"),
|
||||
description: i18nT("onboarding.block.defaults.stepDescription"),
|
||||
icon: `<svg fill="currentColor" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="32" height="32" viewBox="0 0 32 32"> <path d="M 19 6 L 19 7.4375 L 19.09375 7.625 L 20.125 10 L 11.4375 10 L 11.125 10.4375 L 8.40625 14.28125 C 7.800781 14.09375 7.164063 14 6.5 14 C 2.917969 14 0 16.914063 0 20.5 C 0 24.085938 2.914063 27 6.5 27 C 9.914063 27 12.707031 24.347656 12.96875 21 L 16.40625 21 L 16.71875 20.5625 L 21.59375 13.375 L 22.25 14.875 C 20.308594 16.003906 19 18.109375 19 20.5 C 19 24.070313 21.929688 27 25.5 27 C 29.070313 27 32 24.070313 32 20.5 C 32 16.929688 29.070313 14 25.5 14 C 25.019531 14 24.546875 14.054688 24.09375 14.15625 L 21.40625 8 L 24.5 8 C 24.785156 8 25 8.214844 25 8.5 C 25 8.785156 24.785156 9 24.5 9 L 24.5 11 C 25.867188 11 27 9.867188 27 8.5 C 27 7.132813 25.867188 6 24.5 6 Z M 8 7 L 8 9 L 14 9 L 13 7 Z M 13.46875 12 L 20.125 12 L 16.09375 17.9375 Z M 11.71875 13 L 14.34375 19 L 6 19 L 6 21 L 10.9375 21 C 10.683594 23.242188 8.808594 25 6.5 25 C 4.019531 25 2 22.980469 2 20.5 C 2 18.019531 4.019531 16 6.5 16 C 8.058594 16 9.441406 16.796875 10.25 18 L 12.5 18 C 12.019531 16.847656 11.230469 15.859375 10.21875 15.15625 Z M 25.5 16 C 27.980469 16 30 18.019531 30 20.5 C 30 22.980469 27.980469 25 25.5 25 C 23.019531 25 21 22.980469 21 20.5 C 21 18.925781 21.832031 17.554688 23.0625 16.75 L 25.09375 21.40625 L 26.90625 20.59375 L 24.9375 16.0625 C 25.125 16.039063 25.308594 16 25.5 16 Z"></path> </svg>`,
|
||||
links: [
|
||||
{
|
||||
text: i18nT("onboarding.block.defaults.primaryLink"),
|
||||
href: "#",
|
||||
isPrimary: true,
|
||||
},
|
||||
{
|
||||
text: i18nT("onboarding.block.defaults.secondaryLink"),
|
||||
href: "#",
|
||||
isPrimary: false,
|
||||
},
|
||||
],
|
||||
gallery: [
|
||||
{
|
||||
id: "",
|
||||
type: "image",
|
||||
title: i18nT("onboarding.block.defaults.gallery.image1"),
|
||||
src: "https://placehold.co/1000x600?text=Image%201",
|
||||
},
|
||||
{
|
||||
id: "",
|
||||
type: "image",
|
||||
title: i18nT("onboarding.block.defaults.gallery.image2"),
|
||||
src: "https://placehold.co/1000x600?text=Image%202",
|
||||
},
|
||||
],
|
||||
input: [
|
||||
{
|
||||
id: "1",
|
||||
type: "text",
|
||||
name: "source",
|
||||
title: i18nT("onboarding.block.defaults.sourceQuestion"),
|
||||
isRequired: true,
|
||||
options: [],
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
type: "select",
|
||||
name: "What will you use it for?",
|
||||
title: i18nT("onboarding.block.defaults.useCaseSelect"),
|
||||
isRequired: false,
|
||||
options: [
|
||||
{ value: "research", name: i18nT("onboarding.block.defaults.useCases.research"), color: Colors.GRAY },
|
||||
{ value: "personal", name: i18nT("onboarding.block.defaults.useCases.personal"), color: Colors.BLUE },
|
||||
{ value: "smallBusiness", name: i18nT("onboarding.block.defaults.useCases.smallBusiness"), color: Colors.INDIGO },
|
||||
{ value: "largeCompany", name: i18nT("onboarding.block.defaults.useCases.largeCompany"), color: Colors.VIOLET },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const defaultOnboardingBlock: OnboardingBlockDto = {
|
||||
style: "modal",
|
||||
title: i18nT("onboarding.block.defaults.title"),
|
||||
canBeDismissed: true,
|
||||
height: "md",
|
||||
steps: [defaultOnboardingStepBlock],
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveOnboardingHref } from "./OnboardingLinkUtils";
|
||||
|
||||
describe("resolveOnboardingHref", () => {
|
||||
it("resolves app/admin placeholders without duplicate slashes", () => {
|
||||
expect(resolveOnboardingHref("$appOrAdmin/settings/profile", { tenant: "acme" }, "user_1")).toBe("/acme/settings/profile");
|
||||
expect(resolveOnboardingHref("$appOrAdmin/settings/profile", {}, "user_1")).toBe("/settings/profile");
|
||||
});
|
||||
|
||||
it("replaces tenant and user placeholders consistently", () => {
|
||||
expect(resolveOnboardingHref("/$tenant/users/$user/:tenant/{user}", { tenant: "acme" }, "user_1")).toBe("/acme/users/user_1/acme/user_1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Params } from "react-router";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
|
||||
const replaceTokens = (href: string, tokens: string[], value: string) => tokens.reduce((next, token) => next.split(token).join(value), href);
|
||||
|
||||
const getAppOrAdminBasePath = (params: Params) => {
|
||||
const basePath = params.tenant ? UrlUtils.currentTenantUrl(params) : adminPath(undefined, { mode: "host-aware" });
|
||||
return UrlUtils.stripTrailingSlash(basePath);
|
||||
};
|
||||
|
||||
export function resolveOnboardingHref(href: string, params: Params, userId?: string) {
|
||||
let resolved = href;
|
||||
resolved = replaceTokens(resolved, [":tenant", "{tenant}", "$tenant"], params.tenant ?? "");
|
||||
resolved = replaceTokens(resolved, [":user", "{user}", "$user"], userId ?? "");
|
||||
resolved = replaceTokens(resolved, [":appOrAdmin", "{appOrAdmin}", "$appOrAdmin"], getAppOrAdminBasePath(params));
|
||||
return resolved;
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
import clsx from "clsx";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import CustomCarousel from "~/components/ui/images/CustomCarousel";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { renderSanitizedMarkdown } from "~/utils/html-sanitizer";
|
||||
import { OnboardingBlockDto, OnboardingStepBlockDto } from "./OnboardingBlockUtils";
|
||||
import OnboardingGridUtils from "./grid/OnboardingGridUtils";
|
||||
|
||||
export default function OnboardingVariantModal({
|
||||
block,
|
||||
currentStepIdx,
|
||||
setStep,
|
||||
open,
|
||||
onClose,
|
||||
onDismiss,
|
||||
onComplete,
|
||||
onLinkClick,
|
||||
onUpdateCurrentStepState,
|
||||
}: {
|
||||
block: OnboardingBlockDto;
|
||||
currentStepIdx: number;
|
||||
open: boolean;
|
||||
setStep: (idx: number) => void;
|
||||
onClose: () => void;
|
||||
onDismiss: () => void;
|
||||
onComplete: () => void;
|
||||
onLinkClick: (item: { text: string; href: string }) => void;
|
||||
onUpdateCurrentStepState: (state: { [key: string]: string }) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
function dismiss() {
|
||||
onDismiss();
|
||||
}
|
||||
function onNext() {
|
||||
const nextStep = block.steps[currentStepIdx + 1];
|
||||
if (nextStep) {
|
||||
setStep(currentStepIdx + 1);
|
||||
} else {
|
||||
onComplete();
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
setOpen={() => {
|
||||
if (block.canBeDismissed) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
padding="none"
|
||||
>
|
||||
<div>
|
||||
<div className="border-border flex items-center justify-between space-x-2 border-b px-2 py-2">
|
||||
<div className="truncate text-lg font-bold">{t(block.title)}</div>
|
||||
<div className="hidden items-center space-x-1 sm:flex">
|
||||
{block.steps.map((step, idx) => {
|
||||
return (
|
||||
<button
|
||||
key={idx}
|
||||
type="button"
|
||||
onClick={() => setStep(idx)}
|
||||
aria-label={t(step.title)}
|
||||
aria-current={idx === currentStepIdx ? "step" : undefined}
|
||||
className={clsx(
|
||||
"flex min-h-10 min-w-10 items-center justify-center focus:outline-hidden focus-visible:ring-2 focus-visible:ring-teal-500 focus-visible:ring-offset-1",
|
||||
step.completedAt
|
||||
? "text-teal-500 hover:text-teal-600"
|
||||
: idx === currentStepIdx
|
||||
? "text-teal-600 hover:text-teal-700"
|
||||
: "hover:text-muted-foreground text-gray-300"
|
||||
)}
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className={clsx("h-4 w-4")}
|
||||
fill="currentColor"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
x="0px"
|
||||
y="0px"
|
||||
width="50"
|
||||
height="50"
|
||||
viewBox="0 0 50 50"
|
||||
>
|
||||
{" "}
|
||||
<path d="M 41 42 L 9 42 C 5.132813 42 2 38.867188 2 35 L 2 15 C 2 11.132813 5.132813 8 9 8 L 41 8 C 44.867188 8 48 11.132813 48 15 L 48 35 C 48 38.867188 44.867188 42 41 42 Z"></path>{" "}
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Tabs
|
||||
className="sm:hidden"
|
||||
onSelected={(e) => setStep(e)}
|
||||
tabs={block.steps.map((step) => {
|
||||
return { name: step.title };
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={clsx(
|
||||
"bg-secondary",
|
||||
block.height === "xs" && "h-20",
|
||||
block.height === "sm" && "h-40",
|
||||
block.height === "md" && "h-60",
|
||||
block.height === "lg" && "h-80",
|
||||
block.height === "xl" && "h-96",
|
||||
block.height === "auto" && "h-auto",
|
||||
block.height !== "auto" && "overflow-y-auto"
|
||||
)}
|
||||
>
|
||||
<div className="relative flex h-full">
|
||||
{block.steps.length > 0 && (
|
||||
<div className="divide-border bg-secondary/90 hidden w-1/2 divide-y-2 overflow-y-scroll sm:block">
|
||||
{block.steps.map((step, idx) => {
|
||||
return (
|
||||
<Fragment key={idx}>
|
||||
<button
|
||||
type="button"
|
||||
aria-current={idx === currentStepIdx ? "step" : undefined}
|
||||
className={clsx(
|
||||
"w-full truncate px-3 py-3 text-left text-base font-medium focus:outline-hidden focus-visible:ring-2 focus-visible:ring-teal-500 focus-visible:ring-inset",
|
||||
idx === currentStepIdx ? "text-foreground bg-background" : "border-border text-muted-foreground border-r-2"
|
||||
)}
|
||||
onClick={() => setStep(idx)}
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
{step.icon && (
|
||||
<>
|
||||
{step.icon.startsWith("<svg") ? (
|
||||
<div dangerouslySetInnerHTML={{ __html: step.icon.replace("<svg", `<svg class='${"h-5 w-5"}'`) ?? "" }} />
|
||||
) : step.icon.startsWith("http") ? (
|
||||
<img className="h-5 w-5" src={step.icon} alt={step.title} />
|
||||
) : (
|
||||
<div className="w-5">{step.icon}</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<div>{t(step.title)}</div>
|
||||
</div>
|
||||
</button>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
<div className="border-border h-full border-r-2 p-2"></div>
|
||||
</div>
|
||||
)}
|
||||
{block.steps.length > 0 && (
|
||||
<div className={clsx("bg-background w-full overflow-y-auto px-4 pb-4")}>
|
||||
{block.steps.length > currentStepIdx && (
|
||||
<OnboardingStep step={block.steps[currentStepIdx]} onLinkClick={onLinkClick} onUpdate={onUpdateCurrentStepState} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-border bg-secondary flex items-center justify-between space-x-2 border-t px-2 py-2">
|
||||
<div className="flex items-center space-x-2 truncate px-2 py-2">
|
||||
<ButtonSecondary type="button" disabled={currentStepIdx === 0} onClick={() => setStep(currentStepIdx - 1)} className="sm:hidden">
|
||||
{t("shared.back")}
|
||||
</ButtonSecondary>
|
||||
{block.canBeDismissed && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground rounded-md px-2 py-2 text-xs hover:underline focus:underline focus:outline-hidden"
|
||||
onClick={dismiss}
|
||||
>
|
||||
{t("shared.dontShowThisAgain")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-end space-x-2 truncate px-2 py-2">
|
||||
<ButtonSecondary type="button" disabled={currentStepIdx === 0} onClick={() => setStep(currentStepIdx - 1)} className="hidden sm:block">
|
||||
{t("shared.back")}
|
||||
</ButtonSecondary>
|
||||
<ButtonSecondary
|
||||
disabled={block.steps.length === currentStepIdx + 1}
|
||||
type="button"
|
||||
onClick={onNext}
|
||||
className={clsx(block.steps.length === currentStepIdx + 1 && "hidden sm:block")}
|
||||
>
|
||||
{t("shared.next")}
|
||||
</ButtonSecondary>
|
||||
<ButtonPrimary
|
||||
disabled={block.steps.length !== currentStepIdx + 1}
|
||||
type="button"
|
||||
onClick={onComplete}
|
||||
className={clsx(block.steps.length !== currentStepIdx + 1 && "hidden sm:block")}
|
||||
>
|
||||
{t("shared.complete")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function OnboardingStep({
|
||||
step,
|
||||
onLinkClick,
|
||||
onUpdate,
|
||||
}: {
|
||||
step: OnboardingStepBlockDto;
|
||||
onLinkClick: (link: { text: string; href: string }) => void;
|
||||
onUpdate: (state: { [key: string]: string }) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [state, setState] = useState<{ [key: string]: string }>({});
|
||||
useEffect(() => {
|
||||
if (onUpdate) {
|
||||
onUpdate(state);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [state]);
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{step.description && (
|
||||
<div className="prose">
|
||||
<div
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: renderSanitizedMarkdown(step.description),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{step.links && step.links.length > 0 && (
|
||||
<div className="-mx-0.5 flex flex-wrap items-center">
|
||||
{step.links.map((link, idx) => {
|
||||
return (
|
||||
<div key={idx} className="p-0.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onLinkClick(link)}
|
||||
className={clsx(
|
||||
"rounded-md px-2 py-1 text-sm",
|
||||
link.isPrimary ? "bg-theme-700 text-white" : "border-border text-foreground bg-secondary/90 border"
|
||||
)}
|
||||
>
|
||||
{t(link.text)}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{step.gallery && step.gallery.length > 0 && (
|
||||
<div className="flex flex-col justify-center space-y-2">
|
||||
<CustomCarousel items={step.gallery} />
|
||||
{/* {step.gallery.map((galleryItem, idx) => {
|
||||
return (
|
||||
<Fragment key={idx}>
|
||||
{galleryItem.type === "image" && (
|
||||
<img
|
||||
alt={galleryItem.title && t(galleryItem.title)}
|
||||
className="rounded-md border border-dashed border-border object-cover shadow-md"
|
||||
src={galleryItem.src}
|
||||
/>
|
||||
)}
|
||||
{galleryItem.type === "video" && (
|
||||
<iframe
|
||||
src={galleryItem?.src}
|
||||
title={galleryItem?.title ?? ""}
|
||||
frameBorder="0"
|
||||
loading="lazy"
|
||||
className="rounded-md border border-dashed border-border object-cover shadow-md"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
></iframe>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})} */}
|
||||
</div>
|
||||
)}
|
||||
{step.input && step.input.length > 0 && (
|
||||
<div className={clsx("truncate p-1", OnboardingGridUtils.getClasses(step.inputGrid ?? { columns: "2", gap: "sm" }))}>
|
||||
{step.input.map((input, idx) => {
|
||||
return (
|
||||
<div key={idx}>
|
||||
{input.type === "text" && (
|
||||
<InputText
|
||||
name={input.name}
|
||||
title={t(input.title)}
|
||||
required={input.isRequired}
|
||||
value={state?.[input.name] ?? ""}
|
||||
setValue={(e) => setState({ ...state, [input.name]: e.toString() })}
|
||||
/>
|
||||
)}
|
||||
{input.type === "select" && (
|
||||
<InputSelect
|
||||
name={input.name}
|
||||
title={t(input.title)}
|
||||
required={input.isRequired}
|
||||
options={
|
||||
input.options?.map((f) => {
|
||||
return { value: f.value, name: t(f.name) };
|
||||
}) ?? []
|
||||
}
|
||||
value={state?.[input.name] ?? ""}
|
||||
setValue={(e) => setState({ ...state, [input.name]: e?.toString() ?? "" })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export default function OnboardingVariantPage() {
|
||||
const { t } = useTranslation();
|
||||
return <div>{t("onboarding.block.variantPageFallback")}</div>;
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
import { OnboardingStepBlockDto } from "../OnboardingBlockUtils";
|
||||
import { t as i18nT } from "i18next";
|
||||
|
||||
export const defaultOnboardingStepBlocks: OnboardingStepBlockDto[] = [
|
||||
{
|
||||
id: "1",
|
||||
title: i18nT("onboarding.block.samples.welcome.title"),
|
||||
description: i18nT("onboarding.block.samples.welcome.description"),
|
||||
links: [],
|
||||
gallery: [],
|
||||
input: [],
|
||||
icon: '<svg className={className} fill="currentColor" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="32" height="32" viewBox="0 0 32 32"> <path d="M 19 6 L 19 7.4375 L 19.09375 7.625 L 20.125 10 L 11.4375 10 L 11.125 10.4375 L 8.40625 14.28125 C 7.800781 14.09375 7.164063 14 6.5 14 C 2.917969 14 0 16.914063 0 20.5 C 0 24.085938 2.914063 27 6.5 27 C 9.914063 27 12.707031 24.347656 12.96875 21 L 16.40625 21 L 16.71875 20.5625 L 21.59375 13.375 L 22.25 14.875 C 20.308594 16.003906 19 18.109375 19 20.5 C 19 24.070313 21.929688 27 25.5 27 C 29.070313 27 32 24.070313 32 20.5 C 32 16.929688 29.070313 14 25.5 14 C 25.019531 14 24.546875 14.054688 24.09375 14.15625 L 21.40625 8 L 24.5 8 C 24.785156 8 25 8.214844 25 8.5 C 25 8.785156 24.785156 9 24.5 9 L 24.5 11 C 25.867188 11 27 9.867188 27 8.5 C 27 7.132813 25.867188 6 24.5 6 Z M 8 7 L 8 9 L 14 9 L 13 7 Z M 13.46875 12 L 20.125 12 L 16.09375 17.9375 Z M 11.71875 13 L 14.34375 19 L 6 19 L 6 21 L 10.9375 21 C 10.683594 23.242188 8.808594 25 6.5 25 C 4.019531 25 2 22.980469 2 20.5 C 2 18.019531 4.019531 16 6.5 16 C 8.058594 16 9.441406 16.796875 10.25 18 L 12.5 18 C 12.019531 16.847656 11.230469 15.859375 10.21875 15.15625 Z M 25.5 16 C 27.980469 16 30 18.019531 30 20.5 C 30 22.980469 27.980469 25 25.5 25 C 23.019531 25 21 22.980469 21 20.5 C 21 18.925781 21.832031 17.554688 23.0625 16.75 L 25.09375 21.40625 L 26.90625 20.59375 L 24.9375 16.0625 C 25.125 16.039063 25.308594 16 25.5 16 Z"></path> </svg>',
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
title: i18nT("onboarding.block.samples.filters.title"),
|
||||
description: i18nT("onboarding.block.samples.filters.description"),
|
||||
links: [],
|
||||
gallery: [],
|
||||
input: [],
|
||||
icon: '<svg className={className} xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" /> </svg>',
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
title: i18nT("onboarding.block.samples.steps.title"),
|
||||
description: i18nT("onboarding.block.samples.steps.description"),
|
||||
links: [],
|
||||
gallery: [],
|
||||
input: [],
|
||||
icon: '<svg className={className} xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" /> </svg>',
|
||||
},
|
||||
{
|
||||
id: "4",
|
||||
title: i18nT("onboarding.block.samples.links.title"),
|
||||
description: i18nT("onboarding.block.samples.links.description"),
|
||||
links: [
|
||||
{
|
||||
text: i18nT("onboarding.block.samples.links.profileLink"),
|
||||
href: "$appOrAdmin/settings/profile",
|
||||
isPrimary: true,
|
||||
},
|
||||
{
|
||||
text: i18nT("onboarding.block.samples.links.newTabLink"),
|
||||
href: "https://example.com",
|
||||
isPrimary: false,
|
||||
target: "_blank",
|
||||
},
|
||||
],
|
||||
gallery: [],
|
||||
input: [],
|
||||
icon: '<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="50" height="50" viewBox="0 0 50 50" className={className} fill="currentColor"> {" "} <path d="M 37 4 C 34.596 4 32.336719 4.9367188 30.636719 6.6367188 L 25.636719 11.636719 C 24.191719 13.081719 23.2985 14.930688 23.0625 16.929688 C 23.0215 17.281688 23 17.64 23 18 C 23 19.368 23.313672 20.686766 23.888672 21.884766 L 25.414062 20.357422 C 25.147062 19.609422 25 18.817 25 18 C 25 16.13 25.728781 14.373781 27.050781 13.050781 L 32.050781 8.0507812 C 33.373781 6.7287812 35.13 6 37 6 C 38.87 6 40.626219 6.7287812 41.949219 8.0507812 C 43.272219 9.3727813 44 11.13 44 13 C 44 14.87 43.271219 16.626219 41.949219 17.949219 L 36.949219 22.949219 C 35.626219 24.271219 33.87 25 32 25 C 31.183 25 30.390578 24.852938 29.642578 24.585938 L 28.115234 26.111328 C 29.313234 26.686328 30.632 27 32 27 C 34.404 27 36.663281 26.063281 38.363281 24.363281 L 43.363281 19.363281 C 45.063281 17.663281 46 15.404 46 13 C 46 10.596 45.063281 8.3367187 43.363281 6.6367188 C 41.663281 4.9367187 39.404 4 37 4 z M 30.980469 17.990234 A 1.0001 1.0001 0 0 0 30.292969 18.292969 L 18.292969 30.292969 A 1.0001 1.0001 0 1 0 19.707031 31.707031 L 31.707031 19.707031 A 1.0001 1.0001 0 0 0 30.980469 17.990234 z M 18 23 C 15.596 23 13.336719 23.936719 11.636719 25.636719 L 6.6367188 30.636719 C 5.0727187 32.199719 4.1545781 34.236828 4.0175781 36.423828 C 4.0055781 36.614828 4 36.807 4 37 C 4 39.404 4.9367188 41.663281 6.6367188 43.363281 C 8.3367187 45.063281 10.596 46 13 46 C 15.404 46 17.663281 45.063281 19.363281 43.363281 L 24.363281 38.363281 C 26.063281 36.663281 27 34.404 27 32 C 27 30.632 26.686328 29.313234 26.111328 28.115234 L 24.585938 29.642578 C 24.852938 30.390578 25 31.183 25 32 C 25 33.87 24.271219 35.626219 22.949219 36.949219 L 17.949219 41.949219 C 16.626219 43.271219 14.87 44 13 44 C 11.13 44 9.3737813 43.271219 8.0507812 41.949219 C 6.7277812 40.627219 6 38.87 6 37 C 6 35.13 6.7287812 33.373781 8.0507812 32.050781 L 13.050781 27.050781 C 14.373781 25.728781 16.13 25 18 25 C 18.817 25 19.609422 25.147062 20.357422 25.414062 L 21.884766 23.888672 C 20.686766 23.313672 19.368 23 18 23 z"></path> </svg>',
|
||||
},
|
||||
{
|
||||
id: "5",
|
||||
title: i18nT("onboarding.block.samples.media.title"),
|
||||
description: i18nT("onboarding.block.samples.media.description"),
|
||||
links: [],
|
||||
gallery: [
|
||||
{
|
||||
id: "1",
|
||||
type: "video",
|
||||
title: i18nT("onboarding.block.samples.media.pageBlockBuilder"),
|
||||
src: "https://www.loom.com/embed/eccf927d35cd4ad3b4a1d512257cea53",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
type: "image",
|
||||
title: i18nT("onboarding.block.samples.media.adminPortal"),
|
||||
src: "https://placehold.co/1200x800?text=Admin+Portal",
|
||||
},
|
||||
],
|
||||
input: [],
|
||||
icon: '<svg className={className} xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" /> </svg>',
|
||||
},
|
||||
{
|
||||
id: "6",
|
||||
title: i18nT("onboarding.block.samples.inputs.title"),
|
||||
description: i18nT("onboarding.block.samples.inputs.description"),
|
||||
links: [],
|
||||
gallery: [],
|
||||
input: [
|
||||
{ id: "1", type: "text", name: "firstName", title: i18nT("onboarding.block.samples.inputs.firstName"), isRequired: true, options: [] },
|
||||
{ id: "2", type: "text", name: "lastName", title: i18nT("onboarding.block.samples.inputs.lastName"), isRequired: false, options: [] },
|
||||
{
|
||||
id: "3",
|
||||
type: "select",
|
||||
name: "whereDidYouHearAboutUs",
|
||||
title: i18nT("onboarding.block.defaults.sourceQuestion"),
|
||||
isRequired: false,
|
||||
options: [
|
||||
{ value: "google", name: i18nT("onboarding.block.samples.inputs.sources.google") },
|
||||
{ value: "youtube", name: i18nT("onboarding.block.samples.inputs.sources.youtube") },
|
||||
{ value: "twitter", name: i18nT("onboarding.block.samples.inputs.sources.twitter") },
|
||||
{ value: "other", name: i18nT("onboarding.block.samples.inputs.sources.other") },
|
||||
],
|
||||
},
|
||||
],
|
||||
icon: '<svg className={clsx(className, "h-5 w-5 shrink-0")} xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="24" height="24" viewBox="0 0 172 172" fill="currentColor" > <g fill="none" fillRule="nonzero" stroke="none" strokeWidth="1" strokeLinecap="butt" strokeLinejoin="miter" strokeMiterlimit="10" strokeDasharray="" strokeDashoffset="0" fontFamily="none" fontWeight="none" fontSize="none" textAnchor="none" > <path d="M0,172v-172h172v172z" fill="none"></path> <g fill="currentColor"> <path d="M146.59473,57.24935c-5.28183,0 -9.90758,1.23715 -13.89941,3.69531c-3.98467,2.451 -7.04629,5.9742 -9.19629,10.56803c-2.14283,4.59384 -3.2194,9.90187 -3.2194,15.92904v3.83528c0,9.44567 2.33353,16.88702 6.9847,22.29785c4.65117,5.41083 11.04261,8.11849 19.16244,8.11849c7.42467,0 13.40816,-1.93175 17.94466,-5.80892c4.5365,-3.87717 7.05009,-9.19203 7.54459,-15.94304v-0.014h-13.03157c-0.29383,3.81983 -1.4442,6.6341 -3.42936,8.45443c-1.98517,1.8275 -4.99348,2.74349 -9.02832,2.74349c-4.46483,0 -7.74101,-1.5573 -9.81218,-4.68913c-2.07117,-3.12467 -3.10742,-8.08556 -3.10742,-14.86523v-4.73112c0.05733,-6.48583 1.16705,-11.2725 3.33138,-14.36133c2.16433,-3.08883 5.40602,-4.63314 9.75618,-4.63314c4.00617,0 6.98784,0.92316 8.94434,2.74349c1.96367,1.82033 3.10686,4.7552 3.42936,8.80436h13.04557c-0.69517,-7.009 -3.27573,-12.4438 -7.74056,-16.32096c-4.46483,-3.87717 -10.36871,-5.82292 -17.67871,-5.82292zM23.58561,58.11719l-23.58561,62.70833h13.88542l4.35319,-12.91959h22.87174l4.40918,12.91959h13.87142l-23.71159,-62.70833zM65.31185,58.11719v62.70833h24.63542c7.19533,-0.05733 12.73058,-1.64195 16.61491,-4.74511c3.8915,-3.10317 5.83691,-7.66229 5.83691,-13.68946c0,-3.53317 -0.94298,-6.52167 -2.81348,-8.95833c-1.8705,-2.43667 -4.43807,-4.06842 -7.68457,-4.87109c2.84517,-1.08933 5.06459,-2.79355 6.66276,-5.13705c1.59816,-2.3435 2.39355,-5.04399 2.39355,-8.11849c0,-5.62583 -1.98539,-9.90478 -5.96289,-12.82161c-3.9775,-2.91683 -9.80692,-4.36719 -17.49675,-4.36719zM78.35742,68.58724h9.1403c3.59767,0 6.2247,0.61465 7.89453,1.86165c1.66983,1.247 2.50553,3.29969 2.50553,6.14486c0,5.08117 -3.29599,7.68189 -9.88216,7.79655h-9.6582zM29.63249,73.96224l7.96452,23.47364h-15.84505zM78.35742,93.5306h11.96777c6.00567,0.086 9.00032,2.99387 9.00032,8.73438c0,2.55133 -0.86235,4.55722 -2.58952,6.00489c-1.72717,1.44767 -4.12016,2.16959 -7.19466,2.16959h-11.18392z"></path> </g> </g> </svg>',
|
||||
},
|
||||
{
|
||||
id: "7",
|
||||
title: i18nT("onboarding.block.samples.activity.title"),
|
||||
description: i18nT("onboarding.block.samples.activity.description"),
|
||||
links: [],
|
||||
gallery: [],
|
||||
input: [],
|
||||
icon: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" class="w-6 h-6"> <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" /> </svg>',
|
||||
},
|
||||
{
|
||||
id: "8",
|
||||
title: i18nT("onboarding.block.samples.end.title"),
|
||||
description: "",
|
||||
links: [],
|
||||
gallery: [{ id: "1", type: "image", title: "", src: "https://www.gifcen.com/wp-content/uploads/2021/05/the-end-gif-13.gif" }],
|
||||
input: [],
|
||||
icon: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6"> <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12c0 1.268-.63 2.39-1.593 3.068a3.745 3.745 0 01-1.043 3.296 3.745 3.745 0 01-3.296 1.043A3.745 3.745 0 0112 21c-1.268 0-2.39-.63-3.068-1.593a3.746 3.746 0 01-3.296-1.043 3.745 3.745 0 01-1.043-3.296A3.745 3.745 0 013 12c0-1.268.63-2.39 1.593-3.068a3.745 3.745 0 011.043-3.296 3.746 3.746 0 013.296-1.043A3.746 3.746 0 0112 3c1.268 0 2.39.63 3.068 1.593a3.746 3.746 0 013.296 1.043 3.746 3.746 0 011.043 3.296A3.745 3.745 0 0121 12z" /> </svg>',
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import { onboardingGridCols, OnboardingGridDto, onboardingGridGaps } from "./OnboardingGridUtils";
|
||||
|
||||
export default function OnboardingGridForm({ item, onUpdate }: { item?: OnboardingGridDto; onUpdate: (item: OnboardingGridDto) => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [columns, setColumns] = useState(item?.columns);
|
||||
const [gap, setGap] = useState(item?.gap);
|
||||
|
||||
useEffect(() => {
|
||||
onUpdate({ columns, gap });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [columns, gap]);
|
||||
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<label className="text-muted-foreground flex w-full justify-between gap-2 text-xs font-medium">
|
||||
<div className="flex items-center gap-1">{t("onboarding.block.grid.title")}</div>
|
||||
{(gap || columns) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setGap(undefined);
|
||||
setColumns(undefined);
|
||||
}}
|
||||
>
|
||||
{t("shared.remove")}
|
||||
</button>
|
||||
)}
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
value={columns}
|
||||
options={onboardingGridCols.map((value) => ({ name: t("onboarding.block.grid.columnsOption", { count: Number(value) }), value }))}
|
||||
setValue={(value) => setColumns((value as OnboardingGridDto["columns"]) ?? "4")}
|
||||
selectPlaceholder={t("onboarding.block.grid.columnsPlaceholder")}
|
||||
/>
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
value={gap}
|
||||
options={onboardingGridGaps.map((value) => ({ name: t("onboarding.block.grid.gapOption", { value }), value }))}
|
||||
setValue={(value) => setGap((value as OnboardingGridDto["gap"]) ?? "sm")}
|
||||
selectPlaceholder={t("onboarding.block.grid.gapPlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import clsx from "clsx";
|
||||
|
||||
export const onboardingGridCols = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"] as const;
|
||||
export const onboardingGridGaps = ["none", "xs", "sm", "md", "lg"] as const;
|
||||
|
||||
export interface OnboardingGridDto {
|
||||
columns?: (typeof onboardingGridCols)[number];
|
||||
gap?: (typeof onboardingGridGaps)[number];
|
||||
}
|
||||
|
||||
function getClasses(grid?: OnboardingGridDto) {
|
||||
return clsx(
|
||||
"grid",
|
||||
grid?.gap === "none" && "gap-0",
|
||||
(!grid?.gap || grid?.gap === "sm") && "gap-4",
|
||||
grid?.gap === "xs" && "gap-2",
|
||||
grid?.gap === "md" && "gap-8",
|
||||
grid?.gap === "lg" && "gap-12",
|
||||
grid?.columns === "2" && "grid-cols-1 sm:grid-cols-2",
|
||||
grid?.columns === "3" && "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",
|
||||
(!grid?.columns || grid?.columns === "4") && "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4",
|
||||
grid?.columns === "5" && "grid-cols-1 sm:grid-cols-2 lg:grid-cols-5",
|
||||
grid?.columns === "6" && "grid-cols-2 sm:grid-cols-3 lg:grid-cols-6",
|
||||
grid?.columns === "7" && "grid-cols-2 sm:grid-cols-3 lg:grid-cols-7",
|
||||
grid?.columns === "8" && "grid-cols-2 sm:grid-cols-3 lg:grid-cols-8",
|
||||
grid?.columns === "9" && "grid-cols-4 sm:grid-cols-4 lg:grid-cols-9",
|
||||
grid?.columns === "10" && "grid-cols-4 sm:grid-cols-5 lg:grid-cols-10",
|
||||
grid?.columns === "11" && "grid-cols-4 sm:grid-cols-5 lg:grid-cols-11",
|
||||
grid?.columns === "12" && "grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 xl:grid-cols-12"
|
||||
);
|
||||
}
|
||||
|
||||
export default {
|
||||
getClasses,
|
||||
};
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const sourcePaths = [
|
||||
"apps/web/app/modules/onboarding/blocks/OnboardingBlockForm.tsx",
|
||||
"apps/web/app/modules/onboarding/blocks/OnboardingBlockUtils.ts",
|
||||
"apps/web/app/modules/onboarding/blocks/OnboardingVariantPage.tsx",
|
||||
"apps/web/app/modules/onboarding/blocks/defaultOnboarding/defaultOnboardingStepBlocks.ts",
|
||||
"apps/web/app/modules/onboarding/utils/OnboardingStepUtils.tsx",
|
||||
].map((file) => path.resolve(process.cwd(), file));
|
||||
|
||||
describe("onboarding block form i18n", () => {
|
||||
it("uses semantic translation keys for visible block editor labels and defaults", () => {
|
||||
const source = sourcePaths.map((sourcePath) => fs.readFileSync(sourcePath, "utf8")).join("\n");
|
||||
|
||||
expect(source).toContain("onboarding.block.canBeDismissed");
|
||||
expect(source).toContain("onboarding.block.stepsDescription");
|
||||
expect(source).toContain("onboarding.block.actions.addGalleryItem");
|
||||
expect(source).toContain("onboarding.block.defaultGalleryTitle");
|
||||
expect(source).toContain("onboarding.block.targetBlank");
|
||||
expect(source).toContain("onboarding.block.defaults.title");
|
||||
expect(source).toContain("onboarding.block.defaults.stepTitle");
|
||||
expect(source).toContain("onboarding.block.defaults.stepDescription");
|
||||
expect(source).toContain("onboarding.block.defaults.sourceQuestion");
|
||||
expect(source).toContain("onboarding.block.defaults.primaryLink");
|
||||
expect(source).toContain("onboarding.block.defaults.secondaryLink");
|
||||
expect(source).toContain("onboarding.block.defaults.gallery.image1");
|
||||
expect(source).toContain("onboarding.block.defaults.gallery.image2");
|
||||
expect(source).toContain("onboarding.block.defaults.useCaseSelect");
|
||||
expect(source).toContain("onboarding.block.defaults.useCases.research");
|
||||
expect(source).toContain("onboarding.block.defaults.useCases.personal");
|
||||
expect(source).toContain("onboarding.block.defaults.useCases.smallBusiness");
|
||||
expect(source).toContain("onboarding.block.defaults.useCases.largeCompany");
|
||||
expect(source).toContain("onboarding.block.samples.welcome.title");
|
||||
expect(source).toContain("onboarding.block.samples.welcome.description");
|
||||
expect(source).toContain("onboarding.block.samples.filters.title");
|
||||
expect(source).toContain("onboarding.block.samples.filters.description");
|
||||
expect(source).toContain("onboarding.block.samples.steps.title");
|
||||
expect(source).toContain("onboarding.block.samples.steps.description");
|
||||
expect(source).toContain("onboarding.block.samples.links.title");
|
||||
expect(source).toContain("onboarding.block.samples.links.description");
|
||||
expect(source).toContain("onboarding.block.samples.links.profileLink");
|
||||
expect(source).toContain("onboarding.block.samples.links.newTabLink");
|
||||
expect(source).toContain("onboarding.block.samples.media.title");
|
||||
expect(source).toContain("onboarding.block.samples.media.description");
|
||||
expect(source).toContain("onboarding.block.samples.media.pageBlockBuilder");
|
||||
expect(source).toContain("onboarding.block.samples.media.adminPortal");
|
||||
expect(source).toContain("onboarding.block.samples.inputs.title");
|
||||
expect(source).toContain("onboarding.block.samples.inputs.description");
|
||||
expect(source).toContain("onboarding.block.samples.inputs.firstName");
|
||||
expect(source).toContain("onboarding.block.samples.inputs.lastName");
|
||||
expect(source).toContain("onboarding.block.samples.inputs.sources.google");
|
||||
expect(source).toContain("onboarding.block.samples.inputs.sources.youtube");
|
||||
expect(source).toContain("onboarding.block.samples.inputs.sources.twitter");
|
||||
expect(source).toContain("onboarding.block.samples.inputs.sources.other");
|
||||
expect(source).toContain("onboarding.block.samples.activity.title");
|
||||
expect(source).toContain("onboarding.block.samples.activity.description");
|
||||
expect(source).toContain("onboarding.block.samples.end.title");
|
||||
expect(source).toContain("onboarding.block.variantPageFallback");
|
||||
expect(source).toContain("onboarding.stepSummary.linksCount");
|
||||
expect(source).toContain("onboarding.stepSummary.galleryItemsCount");
|
||||
expect(source).toContain("onboarding.stepSummary.inputFieldsCount");
|
||||
expect(source).toContain("shared.notSet");
|
||||
expect(source).toContain("QuestionMarkFilledIcon");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain('text-red-600">?</span>');
|
||||
expect(source).not.toContain('title="target=_blank"');
|
||||
expect(source).not.toContain('"Item "');
|
||||
expect(source).not.toContain("{block.links.length} links");
|
||||
expect(source).not.toContain("{block.gallery.length} gallery items");
|
||||
expect(source).not.toContain("{block.input.length} input fields");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { Onboarding } from "@toolctrl/db/prisma-browser";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
|
||||
export default function OnboardingBadge({ item }: { item: Onboarding }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
{item.active && <SimpleBadge title={t("shared.active")} color={Colors.GREEN} />}
|
||||
{!item.active && <SimpleBadge title={t("shared.inactive")} color={Colors.GRAY} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import OnboardingBlock from "../blocks/OnboardingBlock";
|
||||
import { OnboardingBlockDto, OnboardingBlockStyle, OnboardingHeightDto, OnboardingStepBlockDto } from "../blocks/OnboardingBlockUtils";
|
||||
|
||||
export default function OnboardingSession({ open, setOpen }: { open: boolean; setOpen: (open: boolean) => void }) {
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const [onboardingBlock, setOnboardingBlock] = useState<OnboardingBlockDto>();
|
||||
|
||||
useEffect(() => {
|
||||
if (appOrAdminData.onboardingSession && !onboardingBlock) {
|
||||
const onboarding = appOrAdminData.onboardingSession.onboarding;
|
||||
setOnboardingBlock({
|
||||
style: onboarding.type as OnboardingBlockStyle,
|
||||
title: onboarding.title,
|
||||
canBeDismissed: onboarding.canBeDismissed,
|
||||
height: (onboarding.height ?? "md") as OnboardingHeightDto,
|
||||
steps: appOrAdminData.onboardingSession.sessionSteps.map((f) => {
|
||||
const block = JSON.parse(f.step.block) as OnboardingStepBlockDto;
|
||||
block.completedAt = f.completedAt;
|
||||
return block;
|
||||
}),
|
||||
});
|
||||
if (onboarding.type === "modal") {
|
||||
setOpen(true);
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [appOrAdminData.onboardingSession]);
|
||||
return (
|
||||
<>{onboardingBlock && <OnboardingBlock session={appOrAdminData.onboardingSession} item={onboardingBlock} open={open} onClose={() => setOpen(false)} />}</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { OnboardingSession } from "@toolctrl/db/prisma-browser";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
|
||||
export default function OnboardingSessionBadge({ item }: { item: OnboardingSession }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
{item.status === "active" && <SimpleBadge title={t("onboarding.object.sessions.active")} color={Colors.YELLOW} />}
|
||||
{item.status === "started" && <SimpleBadge title={t("onboarding.object.sessions.started")} color={Colors.INDIGO} />}
|
||||
{item.status === "dismissed" && <SimpleBadge title={t("onboarding.object.sessions.dismissed")} color={Colors.ORANGE} />}
|
||||
{item.status === "completed" && <SimpleBadge title={t("onboarding.object.sessions.completed")} color={Colors.GREEN} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import TenantCell from "~/components/core/tenants/TenantCell";
|
||||
import UserBadge from "~/components/core/users/UserBadge";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { formatNumber, useLocaleFormatters } from "~/locale/format";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { OnboardingSessionWithDetails } from "../db/onboardingSessions.db.server";
|
||||
import { OnboardingFilterMetadataDto } from "../dtos/OnboardingFilterMetadataDto";
|
||||
import OnboardingSessionUtils, { OnboardingSessionActivityDto } from "../utils/OnboardingSessionUtils";
|
||||
import OnboardingBadge from "./OnboardingBadge";
|
||||
import OnboardingSessionBadge from "./OnboardingSessionBadge";
|
||||
|
||||
export default function OnboardingSessionsTable({
|
||||
items,
|
||||
onDelete,
|
||||
metadata,
|
||||
withOnboarding = true,
|
||||
}: {
|
||||
items: OnboardingSessionWithDetails[];
|
||||
onDelete?: (item: OnboardingSessionWithDetails) => void;
|
||||
metadata: OnboardingFilterMetadataDto;
|
||||
withOnboarding?: boolean;
|
||||
}) {
|
||||
const { i18n, t } = useTranslation();
|
||||
const [selected, setSelected] = useState<OnboardingSessionWithDetails>();
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<OnboardingSessionWithDetails>[]>([]);
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const locale = i18n.language;
|
||||
|
||||
useEffect(() => {
|
||||
const headers: RowHeaderDisplayDto<OnboardingSessionWithDetails>[] = [
|
||||
{
|
||||
name: "status",
|
||||
title: t("onboarding.session.status"),
|
||||
value: (i) => <OnboardingSessionBadge item={i} />,
|
||||
},
|
||||
{
|
||||
name: "user",
|
||||
title: t("models.user.object"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
<UserBadge item={i.user} />
|
||||
<TenantCell item={i.tenant} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
// {
|
||||
// name: "tenant",
|
||||
// title: t("models.tenant.object"),
|
||||
// // eslint-disable-next-line react/jsx-no-undef
|
||||
// value: (item) => <TenantCell item={item.tenant} />,
|
||||
// },
|
||||
{
|
||||
name: "activity",
|
||||
title: t("onboarding.session.activity"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
<button type="button" onClick={() => setSelected(i)} className="hover:border-theme-400 border-border border-b border-dotted hover:border-dashed">
|
||||
{t("onboarding.session.activitiesCount", { count: OnboardingSessionUtils.getActivity({ t, item: i, metadata }).length })}
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "steps",
|
||||
title: t("onboarding.session.steps"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
<button type="button" onClick={() => setSelected(i)} className="hover:border-theme-400 border-border border-b border-dotted hover:border-dashed">
|
||||
{t("onboarding.session.stepsCompletedCount", {
|
||||
completed: formatNumber(i.sessionSteps.filter((f) => f.completedAt).length, locale),
|
||||
total: formatNumber(i.sessionSteps.length, locale),
|
||||
})}
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "actions",
|
||||
title: t("onboarding.session.actions"),
|
||||
value: (i) => (
|
||||
<ShowPayloadModalButton
|
||||
title={t("onboarding.session.actions")}
|
||||
description={t("onboarding.session.actionsCount", { count: i.actions.length })}
|
||||
payload={JSON.stringify(i.actions, null, 2)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (i) => <div className="flex justify-center">{i.createdAt ? <DateCell date={i.createdAt} /> : <XIcon className="h-4 w-4 text-red-500" />}</div>,
|
||||
},
|
||||
{
|
||||
name: "startedAt",
|
||||
title: t("onboarding.session.startedAt"),
|
||||
value: (i) => <div className="flex justify-center">{i.startedAt ? <DateCell date={i.startedAt} /> : <XIcon className="h-4 w-4 text-red-500" />}</div>,
|
||||
},
|
||||
{
|
||||
name: "dismissedAt",
|
||||
title: t("onboarding.session.dismissedAt"),
|
||||
value: (i) => (
|
||||
<div className="flex justify-center">{i.dismissedAt ? <DateCell date={i.dismissedAt} /> : <XIcon className="h-4 w-4 text-red-500" />}</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "completedAt",
|
||||
title: t("onboarding.session.completedAt"),
|
||||
value: (i) => (
|
||||
<div className="flex justify-center">{i.completedAt ? <DateCell date={i.completedAt} /> : <XIcon className="h-4 w-4 text-red-500" />}</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
if (withOnboarding) {
|
||||
headers.unshift({
|
||||
name: "onboarding",
|
||||
title: t("onboarding.title"),
|
||||
value: (i) => (
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="text-base font-bold">{i.onboarding.title}</div>
|
||||
<div>
|
||||
<OnboardingBadge item={i.onboarding} />
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
});
|
||||
}
|
||||
headers.push({
|
||||
name: "actions",
|
||||
title: t("shared.actions"),
|
||||
value: (i) => (
|
||||
<div className="flex items-center space-x-2">
|
||||
{onDelete && (
|
||||
<ButtonTertiary disabled={!getUserHasPermission(appOrAdminData, "admin.onboarding.delete")} destructive type="button" onClick={() => onDelete(i)}>
|
||||
{t("shared.delete")}
|
||||
</ButtonTertiary>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
});
|
||||
setHeaders(headers);
|
||||
}, [appOrAdminData, locale, metadata, onDelete, t, withOnboarding]);
|
||||
return (
|
||||
<>
|
||||
<SessionModal item={selected} open={selected !== undefined} onClose={() => setSelected(undefined)} metadata={metadata} />
|
||||
<TableSimple
|
||||
items={items}
|
||||
actions={
|
||||
[
|
||||
// { title: t("shared.overview"), onClickRoute: (_, i) => `${i.id}` }
|
||||
]
|
||||
}
|
||||
headers={headers}
|
||||
noRecords={
|
||||
<div className="p-12 text-center">
|
||||
<h3 className="text-foreground mt-1 text-sm font-medium">{t("onboarding.session.empty.title")}</h3>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("onboarding.session.empty.description")}</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SessionModal({
|
||||
item,
|
||||
open,
|
||||
onClose,
|
||||
metadata,
|
||||
}: {
|
||||
item?: OnboardingSessionWithDetails;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
metadata: OnboardingFilterMetadataDto;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const [items, setItems] = useState<OnboardingSessionActivityDto[]>([]);
|
||||
useEffect(() => {
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
setItems(OnboardingSessionUtils.getActivity({ t, item, metadata }));
|
||||
}, [item, metadata, t]);
|
||||
return (
|
||||
<Modal open={open} setOpen={onClose} size="2xl">
|
||||
<div className="bg-background inline-block w-full overflow-hidden text-left align-bottom sm:align-middle">
|
||||
<div className="flex justify-between space-x-2">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("onboarding.session.object")}</h3>
|
||||
<div className="text-muted-foreground text-sm italic">{item?.id}</div>
|
||||
</div>
|
||||
<div className="mt-4 space-y-2">
|
||||
{" "}
|
||||
<TableSimple
|
||||
items={items}
|
||||
headers={[
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("onboarding.session.activityDate"),
|
||||
value: (i) => (
|
||||
<div className="text-muted-foreground">
|
||||
{i.createdAt ? formatters.dateTime(i.createdAt, { timeStyle: "medium" }) : t("shared.notSet")}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "type",
|
||||
title: t("shared.type"),
|
||||
value: (i) => i.type,
|
||||
},
|
||||
{
|
||||
name: "description",
|
||||
title: t("onboarding.session.activityEvents.descriptionColumn"),
|
||||
value: (i) => i.description,
|
||||
className: "w-full",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Link } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { OnboardingWithDetails } from "../db/onboarding.db.server";
|
||||
import OnboardingBadge from "./OnboardingBadge";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export default function OnboardingsList({ items, groupByStatus }: { items: OnboardingWithDetails[]; groupByStatus: { status: string; count: number }[] }) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const sessionStatusCountKeys = {
|
||||
active: "onboarding.session.statusCount.active",
|
||||
started: "onboarding.session.statusCount.started",
|
||||
dismissed: "onboarding.session.statusCount.dismissed",
|
||||
completed: "onboarding.session.statusCount.completed",
|
||||
} as const;
|
||||
const formatSessionStatusCount = (status: "active" | "started" | "dismissed" | "completed", count: number) =>
|
||||
t(sessionStatusCountKeys[status], { count, value: formatters.number(count) });
|
||||
|
||||
return (
|
||||
<TableSimple
|
||||
items={items}
|
||||
actions={[{ title: t("shared.overview"), onClickRoute: (_, i) => `${i.id}` }]}
|
||||
headers={[
|
||||
{
|
||||
name: "title",
|
||||
title: t("onboarding.object.title"),
|
||||
className: "w-full",
|
||||
value: (i) => {
|
||||
const sessionsTotal = i.sessions.length;
|
||||
const activeTotal = i.sessions.filter((f) => f.status === "active").length;
|
||||
const startedTotal = i.sessions.filter((f) => f.status === "started").length;
|
||||
const dismissedTotal = i.sessions.filter((f) => f.status === "dismissed").length;
|
||||
const completedTotal = i.sessions.filter((f) => f.status === "completed").length;
|
||||
|
||||
return (
|
||||
<Link to={adminPath(`onboarding/onboardings/${i.id}`, { mode: "host-aware" })} className="group flex flex-col">
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="text-base font-bold group-hover:underline">{i.title}</div>
|
||||
<div>
|
||||
<OnboardingBadge item={i} />
|
||||
</div>
|
||||
{i.createdAt ? (
|
||||
<>
|
||||
<div>•</div>
|
||||
<div className="text-muted-foreground text-sm">
|
||||
<span>{formatters.relativeDate(i.createdAt)}</span>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("onboarding.session.count", { count: sessionsTotal, value: formatters.number(sessionsTotal) })}
|
||||
</div>
|
||||
<div>•</div>
|
||||
<div className="text-muted-foreground text-sm">{formatSessionStatusCount("active", activeTotal)}</div>
|
||||
<div>•</div>
|
||||
<div className="text-muted-foreground text-sm">{formatSessionStatusCount("started", startedTotal)}</div>
|
||||
<div>•</div>
|
||||
<div className="text-muted-foreground text-sm">{formatSessionStatusCount("dismissed", dismissedTotal)}</div>
|
||||
<div>•</div>
|
||||
<div className="text-muted-foreground text-sm">{formatSessionStatusCount("completed", completedTotal)}</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
noRecords={
|
||||
<div className="p-12 text-center">
|
||||
<h3 className="text-foreground mt-1 text-sm font-medium">{t("onboarding.object.empty.title")}</h3>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("onboarding.object.empty.description")}</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type OnboardingPaginationDbMocks = {
|
||||
onboardingFindMany: ReturnType<typeof vi.fn>;
|
||||
onboardingCount: ReturnType<typeof vi.fn>;
|
||||
onboardingSessionFindMany: ReturnType<typeof vi.fn>;
|
||||
onboardingSessionCount: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
function getDbMocks(): OnboardingPaginationDbMocks {
|
||||
const store = globalThis as typeof globalThis & { __onboardingPaginationDbMocks__?: OnboardingPaginationDbMocks };
|
||||
store.__onboardingPaginationDbMocks__ ??= {
|
||||
onboardingFindMany: vi.fn(),
|
||||
onboardingCount: vi.fn(),
|
||||
onboardingSessionFindMany: vi.fn(),
|
||||
onboardingSessionCount: vi.fn(),
|
||||
};
|
||||
return store.__onboardingPaginationDbMocks__;
|
||||
}
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
onboarding: {
|
||||
findMany: getDbMocks().onboardingFindMany,
|
||||
count: getDbMocks().onboardingCount,
|
||||
},
|
||||
onboardingSession: {
|
||||
findMany: getDbMocks().onboardingSessionFindMany,
|
||||
count: getDbMocks().onboardingSessionCount,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { getOnboardingsWithPagination } from "./onboarding.db.server";
|
||||
import { getOnboardingSessionsWithPagination } from "./onboardingSessions.db.server";
|
||||
|
||||
const dbMocks = getDbMocks();
|
||||
|
||||
describe("onboarding pagination queries", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
dbMocks.onboardingFindMany.mockResolvedValue([{ id: "onboarding_1" }]);
|
||||
dbMocks.onboardingCount.mockResolvedValue(21);
|
||||
dbMocks.onboardingSessionFindMany.mockResolvedValue([{ id: "session_1" }]);
|
||||
dbMocks.onboardingSessionCount.mockResolvedValue(12);
|
||||
});
|
||||
|
||||
it("fetches onboarding page rows and totals with stable query args", async () => {
|
||||
await expect(
|
||||
getOnboardingsWithPagination({
|
||||
where: { active: true },
|
||||
pagination: { page: 2, pageSize: 10 },
|
||||
})
|
||||
).resolves.toEqual({
|
||||
items: [{ id: "onboarding_1" }],
|
||||
pagination: { page: 2, pageSize: 10, totalItems: 21, totalPages: 3 },
|
||||
});
|
||||
|
||||
expect(dbMocks.onboardingFindMany).toHaveBeenCalledWith({
|
||||
where: { active: true },
|
||||
take: 10,
|
||||
skip: 10,
|
||||
include: { filters: { orderBy: { createdAt: "asc" } }, steps: { orderBy: { order: "asc" } }, sessions: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
expect(dbMocks.onboardingCount).toHaveBeenCalledWith({ where: { active: true } });
|
||||
});
|
||||
|
||||
it("fetches onboarding session page rows and totals with stable query args", async () => {
|
||||
await expect(
|
||||
getOnboardingSessionsWithPagination({
|
||||
where: { tenantId: "tenant_1" },
|
||||
pagination: { page: 3, pageSize: 5 },
|
||||
})
|
||||
).resolves.toEqual({
|
||||
items: [{ id: "session_1" }],
|
||||
pagination: { page: 3, pageSize: 5, totalItems: 12, totalPages: 3 },
|
||||
});
|
||||
|
||||
expect(dbMocks.onboardingSessionFindMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1" },
|
||||
take: 5,
|
||||
skip: 10,
|
||||
include: {
|
||||
onboarding: true,
|
||||
user: true,
|
||||
tenant: true,
|
||||
sessionSteps: { include: { step: true }, orderBy: { step: { order: "asc" } } },
|
||||
actions: true,
|
||||
matches: { include: { onboardingFilter: true } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
expect(dbMocks.onboardingSessionCount).toHaveBeenCalledWith({ where: { tenantId: "tenant_1" } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
import { Onboarding, OnboardingFilter, OnboardingStep, OnboardingSession, Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { OnboardingFilterType } from "../dtos/OnboardingFilterTypes";
|
||||
import { OnboardingSessionStatus } from "../dtos/OnboardingSessionStatus";
|
||||
|
||||
export type OnboardingWithDetails = Onboarding & {
|
||||
filters: OnboardingFilter[];
|
||||
steps: OnboardingStep[];
|
||||
sessions: OnboardingSession[];
|
||||
};
|
||||
|
||||
export async function getOnboardings({ active, realtime }: { active?: boolean; realtime?: boolean }): Promise<OnboardingWithDetails[]> {
|
||||
return await db.onboarding.findMany({
|
||||
where: { active, realtime },
|
||||
include: { filters: { orderBy: { createdAt: "asc" } }, steps: { orderBy: { order: "asc" } }, sessions: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOnboardingsWithPagination({
|
||||
where,
|
||||
pagination,
|
||||
}: {
|
||||
where?: Prisma.OnboardingWhereInput;
|
||||
pagination: { page: number; pageSize: number };
|
||||
}): Promise<{ items: OnboardingWithDetails[]; pagination: PaginationDto }> {
|
||||
const [items, totalItems] = await Promise.all([
|
||||
db.onboarding.findMany({
|
||||
where,
|
||||
take: pagination.pageSize,
|
||||
skip: (pagination.page - 1) * pagination.pageSize,
|
||||
include: { filters: { orderBy: { createdAt: "asc" } }, steps: { orderBy: { order: "asc" } }, sessions: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
db.onboarding.count({
|
||||
where,
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function getOnboarding(id: string): Promise<OnboardingWithDetails | null> {
|
||||
return await db.onboarding.findUnique({
|
||||
where: { id },
|
||||
include: { filters: { orderBy: { createdAt: "asc" } }, steps: { orderBy: { order: "asc" } }, sessions: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function createOnboarding(data: {
|
||||
title: string;
|
||||
type: "modal" | "page";
|
||||
active: boolean;
|
||||
realtime: boolean;
|
||||
canBeDismissed: boolean;
|
||||
height: string;
|
||||
filters: { type: OnboardingFilterType; value: string | null }[];
|
||||
steps: { order: number; block: string }[];
|
||||
}): Promise<Onboarding> {
|
||||
return await db.onboarding.create({
|
||||
data: {
|
||||
title: data.title,
|
||||
type: data.type.toString(),
|
||||
active: data.active,
|
||||
realtime: data.realtime,
|
||||
canBeDismissed: data.canBeDismissed,
|
||||
height: data.height,
|
||||
filters: { create: data.filters },
|
||||
steps: { create: data.steps },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateOnboarding(
|
||||
id: string,
|
||||
data: {
|
||||
title?: string;
|
||||
type?: "modal" | "page";
|
||||
realtime?: boolean;
|
||||
active?: boolean;
|
||||
canBeDismissed?: boolean;
|
||||
height?: string;
|
||||
filters?: {
|
||||
type: OnboardingFilterType;
|
||||
value: string | null;
|
||||
}[];
|
||||
steps?: { order: number; block: string }[];
|
||||
}
|
||||
): Promise<Onboarding> {
|
||||
const update: Prisma.OnboardingUpdateInput = {
|
||||
title: data.title,
|
||||
type: data.type?.toString(),
|
||||
realtime: data.realtime,
|
||||
active: data.active,
|
||||
canBeDismissed: data.canBeDismissed,
|
||||
height: data.height,
|
||||
};
|
||||
if (data.filters) {
|
||||
update.filters = {
|
||||
deleteMany: {},
|
||||
create: data.filters,
|
||||
};
|
||||
}
|
||||
if (data.steps) {
|
||||
update.steps = {
|
||||
deleteMany: {},
|
||||
create: data.steps,
|
||||
};
|
||||
}
|
||||
return await db.onboarding.update({
|
||||
where: { id },
|
||||
data: update,
|
||||
});
|
||||
}
|
||||
|
||||
export async function setOnboardingManualSessions(
|
||||
id: string,
|
||||
data: { userId: string; tenantId: string | null; status: OnboardingSessionStatus }[]
|
||||
): Promise<Onboarding> {
|
||||
const update: Prisma.OnboardingUpdateInput = {
|
||||
sessions: {
|
||||
deleteMany: {},
|
||||
create: data,
|
||||
},
|
||||
};
|
||||
return await db.onboarding.update({
|
||||
where: { id },
|
||||
data: update,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createOnboardingSession(
|
||||
onboarding: OnboardingWithDetails,
|
||||
session: { userId: string; tenantId: string | null; status: OnboardingSessionStatus; matchingFilters: OnboardingFilter[]; createdRealtime: boolean }
|
||||
) {
|
||||
return await db.onboardingSession.create({
|
||||
data: {
|
||||
onboardingId: onboarding.id,
|
||||
userId: session.userId,
|
||||
tenantId: session.tenantId,
|
||||
status: session.status,
|
||||
createdRealtime: session.createdRealtime,
|
||||
sessionSteps: {
|
||||
create: onboarding.steps.map((step) => ({
|
||||
stepId: step.id,
|
||||
})),
|
||||
},
|
||||
matches: {
|
||||
create: session.matchingFilters.map((filter) => ({
|
||||
onboardingFilterId: filter.id,
|
||||
})),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteOnboarding(id: string): Promise<Onboarding> {
|
||||
return await db.onboarding.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export async function updateOnboardingSessionStep(id: string, data: { seenAt?: Date; completedAt?: Date }) {
|
||||
return await db.onboardingSessionStep.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteOnboardingSessionSteps(ids: string[]) {
|
||||
return await db.onboardingSessionStep.deleteMany({
|
||||
where: { id: { in: ids } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteOnboardingSessionStepsInOnboardingSession({ onboardingSessionId, onboardingId }: { onboardingSessionId: string; onboardingId: string }) {
|
||||
return await db.onboardingSessionStep.deleteMany({
|
||||
where: {
|
||||
onboardingSessionId,
|
||||
onboardingSession: {
|
||||
onboardingId,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
describe("onboarding session DB scope", () => {
|
||||
test("deletes sessions and child steps through onboarding scope", () => {
|
||||
const sessionsSource = readRepoFile("apps/web/app/modules/onboarding/db/onboardingSessions.db.server.ts");
|
||||
const stepsSource = readRepoFile("apps/web/app/modules/onboarding/db/onboardingSessionSteps.db.server.ts");
|
||||
|
||||
expect(sessionsSource).toContain("export async function deleteOnboardingSession({ id, onboardingId }");
|
||||
expect(sessionsSource).toContain("db.onboardingSession.deleteMany");
|
||||
expect(sessionsSource).toContain("where: { id, onboardingId }");
|
||||
expect(stepsSource).toContain("export async function deleteOnboardingSessionStepsInOnboardingSession");
|
||||
expect(stepsSource).toContain("onboardingSession: {\n onboardingId,");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,222 @@
|
||||
import {
|
||||
Onboarding,
|
||||
OnboardingFilter,
|
||||
OnboardingSession,
|
||||
OnboardingSessionAction,
|
||||
OnboardingSessionFilterMatch,
|
||||
OnboardingSessionStep,
|
||||
OnboardingStep,
|
||||
Prisma,
|
||||
Tenant,
|
||||
} from "@toolctrl/db/prisma-browser";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { UserSimple } from "~/utils/db/users.db.server";
|
||||
import { OnboardingSessionActionDto } from "../dtos/OnboardingSessionActionDto";
|
||||
import { OnboardingSessionStatus } from "../dtos/OnboardingSessionStatus";
|
||||
|
||||
export type OnboardingSessionWithDetails = OnboardingSession & {
|
||||
onboarding: Onboarding;
|
||||
user: UserSimple;
|
||||
tenant: Tenant | null;
|
||||
sessionSteps: (OnboardingSessionStep & {
|
||||
step: OnboardingStep;
|
||||
})[];
|
||||
actions: OnboardingSessionAction[];
|
||||
matches: (OnboardingSessionFilterMatch & { onboardingFilter: OnboardingFilter })[];
|
||||
};
|
||||
|
||||
export async function getOnboardingSessions({
|
||||
onboardingId,
|
||||
userId,
|
||||
tenantId,
|
||||
status,
|
||||
hasBeenStarted,
|
||||
hasBeenCompleted,
|
||||
hasBeenDismissed,
|
||||
}: {
|
||||
onboardingId?: string;
|
||||
userId?: string;
|
||||
tenantId?: string | null;
|
||||
status?: OnboardingSessionStatus;
|
||||
hasBeenStarted?: boolean;
|
||||
hasBeenCompleted?: boolean;
|
||||
hasBeenDismissed?: boolean;
|
||||
}): Promise<OnboardingSessionWithDetails[]> {
|
||||
const where: Prisma.OnboardingSessionWhereInput = {
|
||||
onboardingId,
|
||||
userId,
|
||||
tenantId,
|
||||
status: status ? status.toString() : undefined,
|
||||
};
|
||||
if (hasBeenStarted !== undefined) {
|
||||
where.startedAt = hasBeenStarted ? { not: null } : null;
|
||||
}
|
||||
if (hasBeenCompleted !== undefined) {
|
||||
where.completedAt = hasBeenCompleted ? { not: null } : null;
|
||||
}
|
||||
if (hasBeenDismissed !== undefined) {
|
||||
where.dismissedAt = hasBeenDismissed ? { not: null } : null;
|
||||
}
|
||||
return await db.onboardingSession.findMany({
|
||||
where,
|
||||
include: {
|
||||
onboarding: true,
|
||||
user: true,
|
||||
tenant: true,
|
||||
sessionSteps: { include: { step: true }, orderBy: { step: { order: "asc" } } },
|
||||
actions: true,
|
||||
matches: { include: { onboardingFilter: true } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOnboardingSessionsWithPagination({
|
||||
where,
|
||||
pagination,
|
||||
}: {
|
||||
where?: Prisma.OnboardingSessionWhereInput;
|
||||
pagination: { page: number; pageSize: number };
|
||||
}): Promise<{ items: OnboardingSessionWithDetails[]; pagination: PaginationDto }> {
|
||||
const [items, totalItems] = await Promise.all([
|
||||
db.onboardingSession.findMany({
|
||||
where,
|
||||
take: pagination.pageSize,
|
||||
skip: (pagination.page - 1) * pagination.pageSize,
|
||||
include: {
|
||||
onboarding: true,
|
||||
user: true,
|
||||
tenant: true,
|
||||
sessionSteps: { include: { step: true }, orderBy: { step: { order: "asc" } } },
|
||||
actions: true,
|
||||
matches: { include: { onboardingFilter: true } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
db.onboardingSession.count({
|
||||
where,
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function getOnboardingSession(id: string): Promise<OnboardingSessionWithDetails | null> {
|
||||
return await db.onboardingSession.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
onboarding: true,
|
||||
user: true,
|
||||
tenant: true,
|
||||
sessionSteps: { include: { step: true }, orderBy: { step: { order: "asc" } } },
|
||||
actions: true,
|
||||
matches: { include: { onboardingFilter: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOnboardingSessionInOnboarding({ id, onboardingId }: { id: string; onboardingId: string }): Promise<OnboardingSessionWithDetails | null> {
|
||||
return await db.onboardingSession.findFirst({
|
||||
where: { id, onboardingId },
|
||||
include: {
|
||||
onboarding: true,
|
||||
user: true,
|
||||
tenant: true,
|
||||
sessionSteps: { include: { step: true }, orderBy: { step: { order: "asc" } } },
|
||||
actions: true,
|
||||
matches: { include: { onboardingFilter: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOnboardingSessionsByUser({
|
||||
userId,
|
||||
tenantId,
|
||||
status,
|
||||
}: {
|
||||
userId: string;
|
||||
tenantId: string | null;
|
||||
status?: OnboardingSessionStatus;
|
||||
}): Promise<OnboardingSessionWithDetails[]> {
|
||||
return await db.onboardingSession.findMany({
|
||||
where: { userId, tenantId, status },
|
||||
include: {
|
||||
onboarding: true,
|
||||
user: true,
|
||||
tenant: true,
|
||||
sessionSteps: { include: { step: true }, orderBy: { step: { order: "asc" } } },
|
||||
actions: true,
|
||||
matches: { include: { onboardingFilter: true } },
|
||||
},
|
||||
orderBy: { onboarding: { createdAt: "asc" } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateOnboardingSession(
|
||||
id: string,
|
||||
data: { status?: OnboardingSessionStatus; startedAt?: Date; completedAt?: Date; dismissedAt?: Date }
|
||||
) {
|
||||
return await db.onboardingSession.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function setOnboardingSessionActions(id: string, data: { actions: OnboardingSessionActionDto[] }) {
|
||||
await db.onboardingSessionAction.deleteMany({
|
||||
where: { onboardingSessionId: id },
|
||||
});
|
||||
return await db.onboardingSessionAction.createMany({
|
||||
data: data.actions.map((action) => ({
|
||||
onboardingSessionId: id,
|
||||
type: action.type.toString(),
|
||||
name: action.name,
|
||||
value: action.value,
|
||||
createdAt: action.createdAt,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateOnboardingSessions(ids: string[], data: { status?: OnboardingSessionStatus }) {
|
||||
return await db.onboardingSession.updateMany({
|
||||
where: { id: { in: ids } },
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteOnboardingSession({ id, onboardingId }: { id: string; onboardingId: string }) {
|
||||
const result = await db.onboardingSession.deleteMany({
|
||||
where: { id, onboardingId },
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw Error("Onboarding session not found");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function deleteOnboardingSessionInOnboarding({ id, onboardingId }: { id: string; onboardingId: string }) {
|
||||
return deleteOnboardingSession({ id, onboardingId });
|
||||
}
|
||||
|
||||
export async function deleteOnboardingSessions(onboardingId: string) {
|
||||
return await db.onboardingSession.deleteMany({
|
||||
where: { onboardingId },
|
||||
});
|
||||
}
|
||||
|
||||
export async function groupOnboardingSessionsByUser() {
|
||||
return await db.onboardingSession.groupBy({
|
||||
by: ["userId"],
|
||||
_count: {
|
||||
_all: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { UserSimple } from "~/utils/db/users.db.server";
|
||||
import { OnboardingFilterDto } from "./OnboardingFilterDto";
|
||||
|
||||
export interface OnboardingCandidateDto {
|
||||
user: UserSimple;
|
||||
tenant: { id: string; name: string; slug: string } | null;
|
||||
matchingFilters: OnboardingFilterDto[];
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { OnboardingFilterType } from "./OnboardingFilterTypes";
|
||||
|
||||
export interface OnboardingFilterDto {
|
||||
type: OnboardingFilterType;
|
||||
value: string | null;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Tenant, Entity, Role } from "@toolctrl/db/prisma-browser";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { UserSimple } from "~/utils/db/users.db.server";
|
||||
|
||||
export interface OnboardingFilterMetadataDto {
|
||||
users: UserSimple[];
|
||||
tenants: Tenant[];
|
||||
entities: Entity[];
|
||||
subscriptionProducts: SubscriptionProductDto[];
|
||||
roles: Role[];
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export const OnboardingFilterTypes = [
|
||||
"admin.portal",
|
||||
"user.is",
|
||||
"user.language",
|
||||
"user.firstName.notSet",
|
||||
"user.lastName.notSet",
|
||||
"user.avatar.notSet",
|
||||
"user.roles.contains",
|
||||
"user.roles.notContains",
|
||||
"tenant.portal",
|
||||
"tenant.is",
|
||||
"tenant.members.hasOne",
|
||||
"tenant.members.hasMany",
|
||||
"tenant.subscription.products.has",
|
||||
"tenant.subscription.active",
|
||||
"tenant.subscription.inactive",
|
||||
"tenant.api.used",
|
||||
"tenant.api.notUsed",
|
||||
"tenant.user.entity.hasCreated",
|
||||
"tenant.user.entity.hasNotCreated",
|
||||
] as const;
|
||||
export type OnboardingFilterType = (typeof OnboardingFilterTypes)[number];
|
||||
@@ -0,0 +1,5 @@
|
||||
import { OnboardingSessionFilterMatch, OnboardingFilter } from "@toolctrl/db/prisma-browser";
|
||||
|
||||
export type OnboardingMatchingFilterDto = OnboardingSessionFilterMatch & {
|
||||
onboardingFilter: OnboardingFilter;
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
export interface OnboardingSessionActionDto {
|
||||
type: "click" | "input";
|
||||
name: string;
|
||||
value: string;
|
||||
createdAt?: Date;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export const OnboardingSessionStatuses = ["active", "started", "dismissed", "completed"] as const;
|
||||
export type OnboardingSessionStatus = (typeof OnboardingSessionStatuses)[number];
|
||||
@@ -0,0 +1,4 @@
|
||||
export interface OnboardingStepDto {
|
||||
order: number;
|
||||
block: string;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export const OnboardingStepTypes = ["text", "gallery", "form"] as const;
|
||||
export type OnboardingStepType = (typeof OnboardingStepTypes)[number];
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const adminOnboardingFiles = [
|
||||
"apps/web/app/routes/admin/onboarding/onboardings.$id/danger.tsx",
|
||||
"apps/web/app/routes/admin/onboarding/onboardings.$id/filters.tsx",
|
||||
"apps/web/app/routes/admin/onboarding/onboardings.$id/index.tsx",
|
||||
"apps/web/app/routes/admin/onboarding/onboardings.$id/settings.tsx",
|
||||
"apps/web/app/routes/admin/onboarding/onboardings.$id/sessions.tsx",
|
||||
"apps/web/app/routes/admin/onboarding/onboardings.$id/steps.tsx",
|
||||
"apps/web/app/modules/onboarding/routes/components/sessions/OnboardingSessionsIndexRoute.tsx",
|
||||
"apps/web/app/modules/onboarding/routes/components/sessions/OnboardingSessionOverviewRoute.tsx",
|
||||
"apps/web/app/modules/onboarding/routes/components/OnboardingSummaryRoute.tsx",
|
||||
"apps/web/app/modules/onboarding/routes/components/onboardings/OnboardingsIndexRoute.tsx",
|
||||
"apps/web/app/modules/onboarding/components/OnboardingsList.tsx",
|
||||
"apps/web/app/modules/onboarding/components/OnboardingSessionsTable.tsx",
|
||||
"apps/web/app/modules/onboarding/utils/OnboardingSessionUtils.tsx",
|
||||
"apps/web/app/modules/onboarding/blocks/grid/OnboardingGridForm.tsx",
|
||||
];
|
||||
|
||||
const localeFiles = ["apps/web/public/locales/en/translations.json", "apps/web/public/locales/de/translations.json"];
|
||||
|
||||
function getNestedValue(source: Record<string, unknown>, path: string) {
|
||||
return path.split(".").reduce<unknown>((value, segment) => {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return (value as Record<string, unknown>)[segment];
|
||||
}, source);
|
||||
}
|
||||
|
||||
describe("admin onboarding notices i18n", () => {
|
||||
it("keeps active-state notices and filter modal labels behind semantic onboarding keys", () => {
|
||||
const source = adminOnboardingFiles.map((file) => readRepoFile(file)).join("\n");
|
||||
|
||||
expect(source).toContain("onboarding.notices.cannotDeleteActive");
|
||||
expect(source).toContain("onboarding.notices.cannotEditActive");
|
||||
expect(source).toContain("onboarding.notices.activeVisible");
|
||||
expect(source).toContain("onboarding.notices.inactiveSessions");
|
||||
expect(source).toContain("onboarding.filter.description");
|
||||
expect(source).toContain("onboarding.filter.actions.add");
|
||||
expect(source).toContain("onboarding.object.types.modal");
|
||||
expect(source).toContain("onboarding.object.types.page");
|
||||
expect(source).toContain("onboarding.filter.realtime.title");
|
||||
expect(source).toContain("onboarding.filter.realtime.description");
|
||||
expect(source).toContain("onboarding.object.candidates");
|
||||
expect(source).toContain("onboarding.filter.candidates.description");
|
||||
expect(source).toContain("onboarding.filter.empty.allUsersCandidates");
|
||||
expect(source).toContain("onboarding.session.saveCount");
|
||||
expect(source).toContain("onboarding.session.plural");
|
||||
expect(source).toContain("onboarding.session.description");
|
||||
expect(source).toContain("onboarding.summary.sessions");
|
||||
expect(source).toContain("onboarding.summary.latestSessions");
|
||||
expect(source).toContain("onboarding.actions.create");
|
||||
expect(source).toContain("onboarding.session.activityDescription");
|
||||
expect(source).toContain("onboarding.session.activityEvents.started");
|
||||
expect(source).toContain("onboarding.session.activityEvents.dismissed");
|
||||
expect(source).toContain("onboarding.session.activityEvents.completed");
|
||||
expect(source).toContain("onboarding.session.activityEvents.stepSeen");
|
||||
expect(source).toContain("onboarding.session.activityEvents.stepCompleted");
|
||||
expect(source).toContain("onboarding.session.activityEvents.descriptionColumn");
|
||||
expect(source).toContain("onboarding.session.count");
|
||||
expect(source).toContain("onboarding.session.statusCount.active");
|
||||
expect(source).toContain("onboarding.session.statusCount.completed");
|
||||
expect(source).toContain("onboarding.session.stepsCompletedCount");
|
||||
expect(source).toContain("models.user.email");
|
||||
expect(source).toContain("onboarding.block.grid.title");
|
||||
expect(source).toContain("onboarding.block.grid.columnsOption");
|
||||
expect(source).toContain("onboarding.block.grid.gapPlaceholder");
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formattedSessionCount");
|
||||
expect(source).toContain('t("shared.clickHereTo", { action: t("shared.preview").toLowerCase() })');
|
||||
expect(source).not.toContain("DateUtils");
|
||||
expect(source).not.toContain("NumberUtils");
|
||||
expect(source).not.toContain('t("onboarding.session.plural").toLowerCase()');
|
||||
expect(source).not.toContain('t("onboarding.object.sessions.active").toLowerCase()');
|
||||
expect(source).not.toContain('t("shared.completed").toLowerCase()');
|
||||
expect(source).not.toContain("Email:");
|
||||
expect(source).not.toContain("You cannot delete an active onboarding.");
|
||||
expect(source).not.toContain("You cannot edit an active onboarding.");
|
||||
expect(source).not.toContain("Current onboarding is not active, sessions will not be created/loaded.");
|
||||
expect(source).not.toContain('"Add filter"');
|
||||
expect(source).not.toContain('"Edit filter"');
|
||||
expect(source).not.toContain('name: "Modal"');
|
||||
expect(source).not.toContain('name: "Page"');
|
||||
expect(source).not.toContain(">Sessions</h3>");
|
||||
expect(source).not.toContain("Create onboarding");
|
||||
expect(source).not.toContain("Latest sessions");
|
||||
expect(source).not.toContain("Onboarding sessions");
|
||||
expect(source).not.toContain("Matching filters ");
|
||||
expect(source).not.toContain(">Grid</div>");
|
||||
expect(source).not.toContain("column(s)");
|
||||
expect(source).not.toContain('selectPlaceholder="Columns..."');
|
||||
expect(source).not.toContain('selectPlaceholder="Gap..."');
|
||||
expect(source).not.toContain('t("onboarding.prompts.updateSteps.title", { 0:');
|
||||
expect(source).not.toContain('t("shared.clickHereTo", { 0:');
|
||||
});
|
||||
|
||||
it.each(localeFiles)("defines the semantic onboarding notice keys in %s", (localeFile) => {
|
||||
const translations = JSON.parse(readRepoFile(localeFile)) as Record<string, unknown>;
|
||||
|
||||
for (const key of [
|
||||
"onboarding.notices.cannotDeleteActive",
|
||||
"onboarding.notices.cannotEditActive",
|
||||
"onboarding.notices.activeVisible",
|
||||
"onboarding.notices.inactiveSessions",
|
||||
"onboarding.session.saveCount_one",
|
||||
"onboarding.session.saveCount_other",
|
||||
"onboarding.session.plural",
|
||||
"onboarding.session.count_one",
|
||||
"onboarding.session.count_other",
|
||||
"onboarding.session.statusCount.active_one",
|
||||
"onboarding.session.statusCount.active_other",
|
||||
"onboarding.session.statusCount.started_one",
|
||||
"onboarding.session.statusCount.started_other",
|
||||
"onboarding.session.statusCount.dismissed_one",
|
||||
"onboarding.session.statusCount.dismissed_other",
|
||||
"onboarding.session.statusCount.completed_one",
|
||||
"onboarding.session.statusCount.completed_other",
|
||||
"onboarding.session.stepsCompletedCount",
|
||||
"onboarding.session.description",
|
||||
"onboarding.summary.sessions",
|
||||
"onboarding.summary.latestSessions",
|
||||
"onboarding.actions.create",
|
||||
"onboarding.session.activityDescription",
|
||||
"onboarding.session.activityEvents.started",
|
||||
"onboarding.session.activityEvents.dismissed",
|
||||
"onboarding.session.activityEvents.completed",
|
||||
"onboarding.session.activityEvents.stepSeen",
|
||||
"onboarding.session.activityEvents.stepCompleted",
|
||||
"onboarding.session.activityEvents.descriptionColumn",
|
||||
"onboarding.filter.description",
|
||||
"onboarding.filter.actions.add",
|
||||
"onboarding.filter.actions.edit",
|
||||
"onboarding.filter.realtime.title",
|
||||
"onboarding.filter.realtime.description",
|
||||
"onboarding.object.candidates",
|
||||
"onboarding.object.types.modal",
|
||||
"onboarding.object.types.page",
|
||||
"onboarding.filter.candidates.description",
|
||||
"onboarding.filter.empty.allUsersCandidates",
|
||||
"onboarding.block.grid.title",
|
||||
"onboarding.block.grid.columnsOption_one",
|
||||
"onboarding.block.grid.columnsOption_other",
|
||||
"onboarding.block.grid.columnsPlaceholder",
|
||||
"onboarding.block.grid.gapOption",
|
||||
"onboarding.block.grid.gapPlaceholder",
|
||||
"onboarding.prompts.updateSteps.title_one",
|
||||
"onboarding.prompts.updateSteps.title_other",
|
||||
]) {
|
||||
expect(getNestedValue(translations, key), `${localeFile} is missing ${key}`).toEqual(expect.any(String));
|
||||
}
|
||||
});
|
||||
});
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getOnboardingSessionsWithPagination, OnboardingSessionWithDetails } from "../../db/onboardingSessions.db.server";
|
||||
import { OnboardingFilterMetadataDto } from "../../dtos/OnboardingFilterMetadataDto";
|
||||
import OnboardingService, { OnboardingSummaryDto } from "../../services/OnboardingService";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
export namespace OnboardingSummaryApi {
|
||||
export type LoaderData = {
|
||||
meta: MetaTagsDto;
|
||||
summary: OnboardingSummaryDto;
|
||||
sessions: {
|
||||
items: OnboardingSessionWithDetails[];
|
||||
metadata: OnboardingFilterMetadataDto;
|
||||
};
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.onboarding.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const data: LoaderData = {
|
||||
meta: [{ title: `${t("onboarding.title")} | ${process.env.APP_NAME}` }],
|
||||
summary: await OnboardingService.getSummary(),
|
||||
sessions: {
|
||||
items: (
|
||||
await getOnboardingSessionsWithPagination({
|
||||
pagination: { page: 1, pageSize: 10 },
|
||||
})
|
||||
).items,
|
||||
metadata: await OnboardingService.getMetadata(),
|
||||
},
|
||||
};
|
||||
return data;
|
||||
};
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { createOnboarding, getOnboardings, OnboardingWithDetails } from "../../../db/onboarding.db.server";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export namespace OnboardingIndexApi {
|
||||
export type LoaderData = {
|
||||
meta: MetaTagsDto;
|
||||
items: OnboardingWithDetails[];
|
||||
groupByStatus: { status: string; count: number }[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.onboarding.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
// const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const status = urlSearchParams.get("status");
|
||||
const items = await getOnboardings({
|
||||
active: status === "active" ? true : status === "inactive" ? false : undefined,
|
||||
});
|
||||
const groupByStatus: { status: string; count: number }[] = [];
|
||||
items.forEach((item) => {
|
||||
if (item.active) {
|
||||
const index = groupByStatus.findIndex((item) => item.status === "active");
|
||||
if (index === -1) {
|
||||
groupByStatus.push({ status: "active", count: 1 });
|
||||
} else {
|
||||
groupByStatus[index].count++;
|
||||
}
|
||||
} else if (!item.active) {
|
||||
const index = groupByStatus.findIndex((item) => item.status === "inactive");
|
||||
if (index === -1) {
|
||||
groupByStatus.push({ status: "inactive", count: 1 });
|
||||
} else {
|
||||
groupByStatus[index].count++;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
meta: [{ title: `${t("onboarding.title")} | ${process.env.APP_NAME}` }],
|
||||
items,
|
||||
groupByStatus,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.onboarding.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const userInfo = await getUserInfo(request);
|
||||
const action = form.get("action");
|
||||
if (action === "create") {
|
||||
await verifyUserHasPermission(request, "admin.onboarding.create");
|
||||
const title = form.get("title")?.toString() ?? "";
|
||||
if (!title) {
|
||||
return Response.json({ error: t("onboarding.errors.titleRequired") }, { status: 400 });
|
||||
}
|
||||
const onboarding = await createOnboarding({
|
||||
title,
|
||||
type: "modal",
|
||||
active: false,
|
||||
realtime: false,
|
||||
canBeDismissed: true,
|
||||
height: "xl",
|
||||
filters: [{ type: "user.is", value: userInfo.userId }],
|
||||
steps: [],
|
||||
});
|
||||
return redirect(adminPath(`onboarding/onboardings/${onboarding.id}`, { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect } from "react-router";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
deleteOnboardingSession,
|
||||
getOnboardingSession,
|
||||
OnboardingSessionWithDetails,
|
||||
updateOnboardingSession,
|
||||
} from "~/modules/onboarding/db/onboardingSessions.db.server";
|
||||
import { OnboardingSessionStatus } from "~/modules/onboarding/dtos/OnboardingSessionStatus";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
const onboardingSessionsPath = () => adminPath("onboarding/sessions", { mode: "host-aware" });
|
||||
|
||||
export namespace OnboardingSessionOverviewApi {
|
||||
export type LoaderData = {
|
||||
meta: MetaTagsDto;
|
||||
item: OnboardingSessionWithDetails;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.onboarding.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const item = await getOnboardingSession(params.id!);
|
||||
if (!item) {
|
||||
throw redirect(onboardingSessionsPath());
|
||||
}
|
||||
const data: LoaderData = {
|
||||
meta: [{ title: `${t("onboarding.session.object")} | ${process.env.APP_NAME}` }],
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.onboarding.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
const item = await getOnboardingSession(params.id!);
|
||||
if (!item) {
|
||||
return redirect(onboardingSessionsPath());
|
||||
}
|
||||
if (action === "update") {
|
||||
const status = form.get("status")?.toString();
|
||||
const startedAt = form.get("startedAt")?.toString();
|
||||
const completedAt = form.get("completedAt")?.toString();
|
||||
const dismissedAt = form.get("dismissedAt")?.toString();
|
||||
await updateOnboardingSession(item.id, {
|
||||
status: status !== undefined ? (status as OnboardingSessionStatus) : undefined,
|
||||
startedAt: startedAt !== undefined ? new Date(startedAt) : undefined,
|
||||
completedAt: completedAt !== undefined ? new Date(completedAt) : undefined,
|
||||
dismissedAt: dismissedAt !== undefined ? new Date(dismissedAt) : undefined,
|
||||
});
|
||||
return Response.json({ success: true });
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.onboarding.delete");
|
||||
await deleteOnboardingSession({ id: item.id, onboardingId: item.onboardingId });
|
||||
return redirect(onboardingSessionsPath());
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getOnboardings } from "~/modules/onboarding/db/onboarding.db.server";
|
||||
import { deleteOnboardingSessionStepsInOnboardingSession } from "~/modules/onboarding/db/onboardingSessionSteps.db.server";
|
||||
import { OnboardingFilterMetadataDto } from "~/modules/onboarding/dtos/OnboardingFilterMetadataDto";
|
||||
import OnboardingService from "~/modules/onboarding/services/OnboardingService";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { getUsersById } from "~/utils/db/users.db.server";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import {
|
||||
deleteOnboardingSession,
|
||||
getOnboardingSessionInOnboarding,
|
||||
getOnboardingSessionsWithPagination,
|
||||
groupOnboardingSessionsByUser,
|
||||
OnboardingSessionWithDetails,
|
||||
} from "../../../db/onboardingSessions.db.server";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
export namespace OnboardingSessionsIndexApi {
|
||||
export type LoaderData = {
|
||||
meta: MetaTagsDto;
|
||||
items: OnboardingSessionWithDetails[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
metadata: OnboardingFilterMetadataDto;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.onboarding.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const allOnboardings = await getOnboardings({});
|
||||
const usersInSessions = await groupOnboardingSessionsByUser();
|
||||
const users = await getUsersById(usersInSessions.map((x) => x.userId));
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "onboardingId",
|
||||
title: t("onboarding.title"),
|
||||
options: [
|
||||
...allOnboardings.map((i) => {
|
||||
return { value: i.id, name: i.title };
|
||||
}),
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "userId",
|
||||
title: t("models.user.object"),
|
||||
options: [
|
||||
...users.map((i) => {
|
||||
return { value: i.id, name: i.email + " - " + i.firstName + " " + i.lastName };
|
||||
}),
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "tenantId",
|
||||
title: t("models.tenant.object"),
|
||||
options: [
|
||||
{ name: "{Admin}", value: "null" },
|
||||
...(await adminGetAllTenantsIdsAndNames()).map((i) => {
|
||||
return { value: i.id, name: i.name };
|
||||
}),
|
||||
],
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const tenantId = filters.properties.find((f) => f.name === "tenantId")?.value;
|
||||
const { items, pagination } = await getOnboardingSessionsWithPagination({
|
||||
pagination: currentPagination,
|
||||
where: {
|
||||
onboardingId: params.id,
|
||||
tenantId: tenantId === "null" ? null : tenantId ?? undefined,
|
||||
},
|
||||
});
|
||||
const data: LoaderData = {
|
||||
meta: [{ title: `${t("onboarding.title")} | ${process.env.APP_NAME}` }],
|
||||
items,
|
||||
pagination,
|
||||
filterableProperties,
|
||||
metadata: await OnboardingService.getMetadata(),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.onboarding.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.onboarding.delete");
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
if (!id) {
|
||||
return Response.json({ error: t("onboarding.session.errors.idRequired") }, { status: 400 });
|
||||
}
|
||||
const session = await getOnboardingSessionInOnboarding({ id, onboardingId: params.id! });
|
||||
if (!session) {
|
||||
return Response.json({ error: t("shared.notFound") }, { status: 404 });
|
||||
}
|
||||
await deleteOnboardingSessionStepsInOnboardingSession({ onboardingSessionId: session.id, onboardingId: params.id! });
|
||||
await deleteOnboardingSession({ id, onboardingId: params.id! });
|
||||
return Response.json({ success: t("onboarding.session.deleted") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getOnboardings } from "~/modules/onboarding/db/onboarding.db.server";
|
||||
import {
|
||||
deleteOnboardingSession,
|
||||
getOnboardingSessionInOnboarding,
|
||||
getOnboardingSessionsWithPagination,
|
||||
groupOnboardingSessionsByUser,
|
||||
} from "~/modules/onboarding/db/onboardingSessions.db.server";
|
||||
import { deleteOnboardingSessionStepsInOnboardingSession } from "~/modules/onboarding/db/onboardingSessionSteps.db.server";
|
||||
import OnboardingService from "~/modules/onboarding/services/OnboardingService";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { getUsersById } from "~/utils/db/users.db.server";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { OnboardingSessionsIndexApi } from "./OnboardingSessionsIndexApi.server";
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/modules/onboarding/db/onboarding.db.server", () => ({ getOnboardings: vi.fn() }));
|
||||
vi.mock("~/modules/onboarding/db/onboardingSessionSteps.db.server", () => ({ deleteOnboardingSessionStepsInOnboardingSession: vi.fn() }));
|
||||
vi.mock("~/modules/onboarding/db/onboardingSessions.db.server", () => ({
|
||||
deleteOnboardingSession: vi.fn(),
|
||||
getOnboardingSessionInOnboarding: vi.fn(),
|
||||
getOnboardingSessionsWithPagination: vi.fn(),
|
||||
groupOnboardingSessionsByUser: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/modules/onboarding/services/OnboardingService", () => ({ default: { getMetadata: vi.fn() } }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({ adminGetAllTenantsIdsAndNames: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUsersById: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/RowPaginationHelper", () => ({ getFiltersFromCurrentUrl: vi.fn(), getPaginationFromCurrentUrl: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
|
||||
const mockedGetTranslations = vi.mocked(getTranslations);
|
||||
const mockedGetOnboardings = vi.mocked(getOnboardings);
|
||||
const mockedGroupOnboardingSessionsByUser = vi.mocked(groupOnboardingSessionsByUser);
|
||||
const mockedGetUsersById = vi.mocked(getUsersById);
|
||||
const mockedAdminGetAllTenantsIdsAndNames = vi.mocked(adminGetAllTenantsIdsAndNames);
|
||||
const mockedGetFiltersFromCurrentUrl = vi.mocked(getFiltersFromCurrentUrl);
|
||||
const mockedGetPaginationFromCurrentUrl = vi.mocked(getPaginationFromCurrentUrl);
|
||||
const mockedGetOnboardingSessionsWithPagination = vi.mocked(getOnboardingSessionsWithPagination);
|
||||
const mockedGetOnboardingSessionInOnboarding = vi.mocked(getOnboardingSessionInOnboarding);
|
||||
const mockedDeleteOnboardingSessionStepsInOnboardingSession = vi.mocked(deleteOnboardingSessionStepsInOnboardingSession);
|
||||
const mockedDeleteOnboardingSession = vi.mocked(deleteOnboardingSession);
|
||||
const mockedGetMetadata = vi.mocked(OnboardingService.getMetadata);
|
||||
const mockedVerifyUserHasPermission = vi.mocked(verifyUserHasPermission);
|
||||
const mockedValidateCSRFToken = vi.mocked(validateCSRFToken);
|
||||
|
||||
function requestWithTenantFilter(tenantId?: string) {
|
||||
const url = new URL("https://admin.example.test/onboardings/onboarding-1/sessions");
|
||||
if (tenantId !== undefined) {
|
||||
url.searchParams.set("tenantId", tenantId);
|
||||
}
|
||||
return new Request(url);
|
||||
}
|
||||
|
||||
async function callLoader(tenantFilterValue: string | null) {
|
||||
mockedGetFiltersFromCurrentUrl.mockReturnValue({
|
||||
query: undefined,
|
||||
properties: [
|
||||
{ name: "onboardingId", title: "onboarding.title", options: [], value: null },
|
||||
{ name: "userId", title: "models.user.object", options: [], value: null },
|
||||
{ name: "tenantId", title: "models.tenant.object", options: [], value: tenantFilterValue },
|
||||
],
|
||||
});
|
||||
|
||||
await OnboardingSessionsIndexApi.loader({
|
||||
request: requestWithTenantFilter(tenantFilterValue ?? undefined),
|
||||
params: { id: "onboarding-1" },
|
||||
context: {},
|
||||
} as unknown as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("OnboardingSessionsIndexApi tenant filter composition", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockedVerifyUserHasPermission.mockResolvedValue(undefined as any);
|
||||
mockedGetTranslations.mockResolvedValue({ t: (key: string) => key } as any);
|
||||
mockedGetOnboardings.mockResolvedValue([{ id: "onboarding-1", title: "Tenant onboarding" }] as any);
|
||||
mockedGroupOnboardingSessionsByUser.mockResolvedValue([{ userId: "user-1" }] as any);
|
||||
mockedGetUsersById.mockResolvedValue([{ id: "user-1", email: "user@example.test", firstName: "User", lastName: "One" }] as any);
|
||||
mockedAdminGetAllTenantsIdsAndNames.mockResolvedValue([{ id: "tenant-1", name: "Tenant One" }] as any);
|
||||
mockedGetPaginationFromCurrentUrl.mockReturnValue({ page: 2, pageSize: 25, sortedBy: [], query: "" });
|
||||
mockedGetOnboardingSessionsWithPagination.mockResolvedValue({
|
||||
items: [],
|
||||
pagination: { page: 2, pageSize: 25, totalItems: 0, totalPages: 0 },
|
||||
} as any);
|
||||
mockedValidateCSRFToken.mockResolvedValue(undefined as never);
|
||||
mockedGetMetadata.mockResolvedValue({} as any);
|
||||
});
|
||||
|
||||
it("maps the admin {Admin} tenant filter to null while preserving the onboarding id", async () => {
|
||||
await callLoader("null");
|
||||
|
||||
expect(mockedGetOnboardingSessionsWithPagination).toHaveBeenCalledWith({
|
||||
pagination: { page: 2, pageSize: 25, sortedBy: [], query: "" },
|
||||
where: {
|
||||
onboardingId: "onboarding-1",
|
||||
tenantId: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("passes a concrete tenant filter through while preserving the onboarding id", async () => {
|
||||
await callLoader("tenant-1");
|
||||
|
||||
expect(mockedGetOnboardingSessionsWithPagination).toHaveBeenCalledWith({
|
||||
pagination: { page: 2, pageSize: 25, sortedBy: [], query: "" },
|
||||
where: {
|
||||
onboardingId: "onboarding-1",
|
||||
tenantId: "tenant-1",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves tenantId undefined when no tenant filter is selected", async () => {
|
||||
await callLoader(null);
|
||||
|
||||
expect(mockedGetOnboardingSessionsWithPagination).toHaveBeenCalledWith({
|
||||
pagination: { page: 2, pageSize: 25, sortedBy: [], query: "" },
|
||||
where: {
|
||||
onboardingId: "onboarding-1",
|
||||
tenantId: undefined,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("scopes session deletes to the current onboarding before deleting child steps", async () => {
|
||||
mockedGetOnboardingSessionInOnboarding.mockResolvedValue({ id: "session-1", sessionSteps: [{ id: "step-1" }] } as any);
|
||||
|
||||
const response = await OnboardingSessionsIndexApi.action({
|
||||
request: new Request("https://admin.example.test/onboardings/onboarding-1/sessions", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ action: "delete", id: "session-1" }).toString(),
|
||||
}),
|
||||
params: { id: "onboarding-1" },
|
||||
context: {},
|
||||
} as any);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockedGetOnboardingSessionInOnboarding).toHaveBeenCalledWith({ id: "session-1", onboardingId: "onboarding-1" });
|
||||
expect(mockedDeleteOnboardingSessionStepsInOnboardingSession).toHaveBeenCalledWith({
|
||||
onboardingSessionId: "session-1",
|
||||
onboardingId: "onboarding-1",
|
||||
});
|
||||
expect(mockedDeleteOnboardingSession).toHaveBeenCalledWith({ id: "session-1", onboardingId: "onboarding-1" });
|
||||
});
|
||||
});
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import OnboardingSessionsTable from "../../components/OnboardingSessionsTable";
|
||||
import { OnboardingSummaryApi } from "../api/OnboardingSummaryApi.server";
|
||||
import { useLoaderData } from "react-router";
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<OnboardingSummaryApi.LoaderData>();
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="border-border border-b pb-5">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("shared.overview")}</h3>
|
||||
</div>
|
||||
<dl className="grid gap-2 sm:grid-cols-3">
|
||||
<div className="bg-card border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">
|
||||
<div>{t("onboarding.summary.sessions")}</div>
|
||||
</dt>
|
||||
<dd className="text-foreground mt-1 flex items-baseline space-x-1 truncate text-2xl font-semibold">
|
||||
<div>
|
||||
{formatters.number(data.summary.sessions.active)}/{formatters.number(data.summary.sessions.all)}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-sm font-normal lowercase">{t("shared.active")}</div>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="bg-card border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">
|
||||
<div>{t("onboarding.object.sessions.dismissed")}</div>
|
||||
</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.sessions.dismissed)}</dd>
|
||||
</div>
|
||||
<div className="bg-card border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">
|
||||
<div>{t("onboarding.object.sessions.completed")}</div>
|
||||
</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.sessions.completed)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div className="mt-4 space-y-4">
|
||||
<h3 className="text-foreground leading-4 font-medium">{t("onboarding.summary.latestSessions")}</h3>
|
||||
<OnboardingSessionsTable items={data.sessions.items} metadata={data.sessions.metadata} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import { Form, useLoaderData, useSearchParams } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import TabsWithIcons from "~/components/ui/tabs/TabsWithIcons";
|
||||
import OnboardingsList from "../../../components/OnboardingsList";
|
||||
import { OnboardingIndexApi } from "../../api/onboardings/OnboardingsIndexApi.server";
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<OnboardingIndexApi.LoaderData>();
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
const [adding, setAdding] = useState(false);
|
||||
|
||||
function countStatus(status?: string) {
|
||||
if (!status) {
|
||||
let total = 0;
|
||||
data?.groupByStatus.forEach((item) => {
|
||||
total += item.count;
|
||||
});
|
||||
return total;
|
||||
}
|
||||
const item = data?.groupByStatus.find((item) => item.status === status);
|
||||
return item ? item.count : 0;
|
||||
}
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="grow">
|
||||
<TabsWithIcons
|
||||
tabs={[
|
||||
{
|
||||
name: `${t("shared.all")} ${countStatus() ? `(${countStatus()})` : ""}`,
|
||||
href: "?",
|
||||
current: !searchParams.get("status") || searchParams.get("status") === "all",
|
||||
},
|
||||
{
|
||||
name: `${t("shared.active")} ${countStatus("active") ? `(${countStatus("active")})` : ""}`,
|
||||
href: "?status=active",
|
||||
current: searchParams.get("status") === "active",
|
||||
},
|
||||
{
|
||||
name: `${t("shared.inactive")} ${countStatus("inactive") ? `(${countStatus("inactive")})` : ""}`,
|
||||
href: "?status=inactive",
|
||||
current: searchParams.get("status") === "inactive",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<ButtonPrimary onClick={() => setAdding(true)}>
|
||||
<div>{t("shared.new")}</div>
|
||||
<PlusIcon className="h-5 w-5" />
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<OnboardingsList items={data.items} groupByStatus={data.groupByStatus} />
|
||||
|
||||
<AddOnboardingModal open={adding} onClose={() => setAdding(false)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AddOnboardingModal({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [title, setTitle] = useState("");
|
||||
return (
|
||||
<Modal open={open} setOpen={onClose} size="md">
|
||||
<Form method="post" className="bg-background inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input name="action" type="hidden" value="create" readOnly hidden />
|
||||
<div className="mt-3 text-center sm:mt-5">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("onboarding.actions.create")}</h3>
|
||||
</div>
|
||||
<div className="mt-4 space-y-2">
|
||||
<InputText name="title" title={t("onboarding.object.title")} value={title} setValue={(e) => setTitle(e)} required />
|
||||
</div>
|
||||
<div className="border-border mt-3 grid grid-cols-2 gap-3 border-t pt-3">
|
||||
<ButtonSecondary type="button" onClick={onClose} className="flex w-full justify-center">
|
||||
{t("shared.back")}
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" className="flex w-full justify-center">
|
||||
{t("shared.create")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { OnboardingSessionOverviewApi } from "../../api/sessions/OnboardingSessionOverviewApi.server";
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<OnboardingSessionOverviewApi.LoaderData>();
|
||||
return (
|
||||
<div>
|
||||
<div>
|
||||
{t("models.user.email")}: {data.item.user.email}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import { useActionData, useLoaderData, useSubmit } from "react-router";
|
||||
import { useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import OnboardingSessionsTable from "~/modules/onboarding/components/OnboardingSessionsTable";
|
||||
import { OnboardingSessionWithDetails } from "~/modules/onboarding/db/onboardingSessions.db.server";
|
||||
import { OnboardingSessionsIndexApi } from "../../api/sessions/OnboardingSessionsIndexApi.server";
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<OnboardingSessionsIndexApi.LoaderData>();
|
||||
const actionData = useActionData<OnboardingSessionsIndexApi.ActionData>();
|
||||
const submit = useSubmit();
|
||||
|
||||
const modalConfirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
function onDelete(item: OnboardingSessionWithDetails) {
|
||||
modalConfirmDelete.current?.setValue(item.id);
|
||||
modalConfirmDelete.current?.show(
|
||||
t("onboarding.prompts.deleteSession.title"),
|
||||
t("shared.confirm"),
|
||||
t("shared.back"),
|
||||
t("onboarding.prompts.deleteSession.description")
|
||||
);
|
||||
}
|
||||
function onConfirmDelete(id: string) {
|
||||
const form = new FormData();
|
||||
form.set("action", "delete");
|
||||
form.set("id", id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="md:border-border md:border-b md:py-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("onboarding.session.plural")}</h3>
|
||||
<div className="flex items-center space-x-2">
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<OnboardingSessionsTable items={data.items} metadata={data.metadata} onDelete={onDelete} />
|
||||
<ConfirmModal ref={modalConfirmDelete} onYes={onConfirmDelete} />
|
||||
<ActionResultModal actionData={actionData} showSuccess={false} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@toolctrl/db/api-keys.server", () => ({
|
||||
countLegacyTenantApiKeyLogs: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18n", () => ({
|
||||
i18nConfig: { supportedLngs: ["en"] },
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/api/.server/RowsApi", () => ({
|
||||
RowsApi: { count: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
|
||||
getUserRoles: vi.fn(async () => []),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
getTenantUsers: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/users.db.server", () => ({
|
||||
getUser: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/subscriptionService", () => ({
|
||||
getActiveTenantSubscriptions: vi.fn(),
|
||||
}));
|
||||
|
||||
import { getUserRoles } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import OnboardingFiltersService from "./OnboardingFiltersService";
|
||||
|
||||
describe("OnboardingFiltersService", () => {
|
||||
it("checks user role filters inside the current tenant scope", async () => {
|
||||
vi.mocked(getUserRoles).mockResolvedValueOnce([{ role: { name: "Owner", permissions: [] } }] as never);
|
||||
|
||||
await expect(
|
||||
OnboardingFiltersService.matches({
|
||||
userId: "user_1",
|
||||
tenantId: "tenant_1",
|
||||
filter: { type: "user.roles.contains", value: "Owner" },
|
||||
} as never),
|
||||
).resolves.toBe(true);
|
||||
|
||||
expect(getUserRoles).toHaveBeenCalledWith("user_1", "tenant_1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { countLegacyTenantApiKeyLogs as countTenantApiKeyLogs } from "@toolctrl/db/api-keys.server";
|
||||
import { OnboardingFilter } from "@toolctrl/db/prisma-browser";
|
||||
import { i18nConfig } from "~/locale/i18n";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import { getUserRoles } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getTenantUsers } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getActiveTenantSubscriptions } from "~/utils/services/.server/subscriptionService";
|
||||
import { OnboardingFilterType } from "../dtos/OnboardingFilterTypes";
|
||||
|
||||
async function matches({ userId, tenantId, filter }: { userId: string; tenantId: string | null; filter: OnboardingFilter }) {
|
||||
const type: OnboardingFilterType = filter.type as OnboardingFilterType;
|
||||
const value = filter.value;
|
||||
if (type.startsWith("tenant") && tenantId === null) {
|
||||
return false;
|
||||
}
|
||||
switch (type) {
|
||||
case "admin.portal":
|
||||
return tenantId === null;
|
||||
case "user.is":
|
||||
return userId === value;
|
||||
case "user.language":
|
||||
const locale = (await getUser(userId))?.locale;
|
||||
const found = i18nConfig.supportedLngs.find((f) => f === locale);
|
||||
if (found) {
|
||||
return found === value;
|
||||
}
|
||||
return !locale && (!value || value === "en");
|
||||
case "user.firstName.notSet":
|
||||
return !(await getUser(userId))?.firstName;
|
||||
case "user.lastName.notSet":
|
||||
return !(await getUser(userId))?.lastName;
|
||||
case "user.avatar.notSet":
|
||||
return !(await getUser(userId))?.avatar;
|
||||
case "user.roles.contains":
|
||||
case "user.roles.notContains":
|
||||
const userRoles = await getUserRoles(userId, tenantId);
|
||||
if (type === "user.roles.contains") {
|
||||
return userRoles.find((f) => f.role.name === value) !== undefined;
|
||||
} else if (type === "user.roles.notContains") {
|
||||
return userRoles.find((f) => f.role.name === value) === undefined;
|
||||
} else {
|
||||
throw new Error(`Unknown onboarding filter: ${type}`);
|
||||
}
|
||||
case "tenant.portal":
|
||||
return tenantId !== null;
|
||||
case "tenant.is":
|
||||
return tenantId === value;
|
||||
case "tenant.members.hasOne":
|
||||
return (await getTenantUsers(tenantId)).length === 1;
|
||||
case "tenant.members.hasMany":
|
||||
return (await getTenantUsers(tenantId)).length > 1;
|
||||
case "tenant.subscription.products.has":
|
||||
case "tenant.subscription.active":
|
||||
case "tenant.subscription.inactive":
|
||||
const tenantSubscription = await getActiveTenantSubscriptions(tenantId ?? "");
|
||||
if (type === "tenant.subscription.products.has") {
|
||||
return tenantSubscription?.products.find((f) => f.subscriptionProductId === value) !== undefined;
|
||||
} else if (type === "tenant.subscription.active") {
|
||||
return tenantSubscription?.products && tenantSubscription?.products.length > 0;
|
||||
} else if (type === "tenant.subscription.inactive") {
|
||||
return tenantSubscription === null || tenantSubscription?.products.length === 0;
|
||||
} else {
|
||||
throw new Error(`Unknown onboarding filter: ${type}`);
|
||||
}
|
||||
case "tenant.api.used":
|
||||
case "tenant.api.notUsed":
|
||||
const apiKeyLogs = await countTenantApiKeyLogs(tenantId ?? "");
|
||||
if (type === "tenant.api.used") {
|
||||
return apiKeyLogs > 0;
|
||||
} else {
|
||||
return apiKeyLogs === 0;
|
||||
}
|
||||
case "tenant.user.entity.hasCreated":
|
||||
case "tenant.user.entity.hasNotCreated":
|
||||
try {
|
||||
const rowsCreated = await RowsApi.count({
|
||||
entity: { id: value ?? "" },
|
||||
tenantId: tenantId ?? "",
|
||||
userId,
|
||||
});
|
||||
if (type === "tenant.user.entity.hasCreated") {
|
||||
return rowsCreated > 0;
|
||||
} else if (type === "tenant.user.entity.hasNotCreated") {
|
||||
return rowsCreated === 0;
|
||||
} else {
|
||||
throw new Error(`Unknown onboarding filter: ${type}`);
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unknown onboarding filter: ${type}`);
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
matches,
|
||||
};
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { OnboardingFilter, OnboardingSession } from "@toolctrl/db/prisma-browser";
|
||||
import OnboardingService from "./OnboardingService";
|
||||
import { createOnboardingSession, getOnboardings } from "../db/onboarding.db.server";
|
||||
import { getOnboardingSession, getOnboardingSessionsByUser } from "../db/onboardingSessions.db.server";
|
||||
import OnboardingFiltersService from "./OnboardingFiltersService";
|
||||
import OnboardingSessionService from "./OnboardingSessionService";
|
||||
import { evaluateOnboardingStepGates, getVisibleOnboardingSteps } from "./step-registry/gating.server";
|
||||
|
||||
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
||||
getAppConfiguration: vi.fn(async () => ({ onboarding: { enabled: true } })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/entities/entities.db.server", () => ({
|
||||
getAllEntities: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/permissions/roles.db.server", () => ({
|
||||
getAllRoles: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/subscriptionProducts.db.server", () => ({
|
||||
getAllSubscriptionProducts: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenants: vi.fn(),
|
||||
getAllTenantUsers: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/users.db.server", () => ({
|
||||
adminGetAllUsers: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../db/onboarding.db.server", () => ({
|
||||
createOnboardingSession: vi.fn(),
|
||||
getOnboarding: vi.fn(),
|
||||
getOnboardings: vi.fn(),
|
||||
updateOnboarding: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../db/onboardingSessions.db.server", () => ({
|
||||
getOnboardingSession: vi.fn(),
|
||||
getOnboardingSessionsByUser: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./OnboardingFiltersService", () => ({
|
||||
default: {
|
||||
matches: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("./OnboardingSessionService", () => ({
|
||||
default: {
|
||||
started: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/subscriptionService", () => ({
|
||||
getActiveTenantSubscriptions: vi.fn(async () => null),
|
||||
}));
|
||||
|
||||
vi.mock("./step-registry/gating.server", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("./step-registry/gating.server")>();
|
||||
return {
|
||||
...actual,
|
||||
evaluateOnboardingStepGates: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
const mockedGetOnboardingSessionsByUser = vi.mocked(getOnboardingSessionsByUser);
|
||||
const mockedGetOnboardingSession = vi.mocked(getOnboardingSession);
|
||||
const mockedGetOnboardings = vi.mocked(getOnboardings);
|
||||
const mockedCreateOnboardingSession = vi.mocked(createOnboardingSession);
|
||||
const mockedMatches = vi.mocked(OnboardingFiltersService.matches);
|
||||
const mockedStarted = vi.mocked(OnboardingSessionService.started);
|
||||
const mockedEvaluateOnboardingStepGates = vi.mocked(evaluateOnboardingStepGates);
|
||||
|
||||
const request = new Request("https://app.test/onboarding");
|
||||
const userId = "user-1";
|
||||
|
||||
function filter(id: string, type: string, value: string | null = null): OnboardingFilter {
|
||||
return {
|
||||
id,
|
||||
onboardingId: "onboarding-1",
|
||||
type,
|
||||
value,
|
||||
createdAt: new Date("2025-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2025-01-01T00:00:00.000Z"),
|
||||
} as OnboardingFilter;
|
||||
}
|
||||
|
||||
function session(overrides: Partial<OnboardingSession> & { id: string; tenantId: string | null; status?: string }) {
|
||||
return {
|
||||
id: overrides.id,
|
||||
onboardingId: overrides.onboardingId ?? "onboarding-1",
|
||||
userId: overrides.userId ?? userId,
|
||||
tenantId: overrides.tenantId,
|
||||
status: overrides.status ?? "active",
|
||||
createdRealtime: overrides.createdRealtime ?? true,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
dismissedAt: null,
|
||||
createdAt: new Date("2025-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2025-01-01T00:00:00.000Z"),
|
||||
onboarding: { id: overrides.onboardingId ?? "onboarding-1", active: true, title: "Realtime onboarding" },
|
||||
user: { id: overrides.userId ?? userId, email: "user-1@example.test" },
|
||||
tenant: null,
|
||||
sessionSteps: [],
|
||||
actions: [],
|
||||
matches: [],
|
||||
} as any;
|
||||
}
|
||||
|
||||
function onboarding(filters: OnboardingFilter[], sessions: OnboardingSession[] = []) {
|
||||
return {
|
||||
id: "onboarding-1",
|
||||
title: "Realtime onboarding",
|
||||
type: "modal",
|
||||
active: true,
|
||||
realtime: true,
|
||||
canBeDismissed: true,
|
||||
height: "md",
|
||||
createdAt: new Date("2025-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2025-01-01T00:00:00.000Z"),
|
||||
filters,
|
||||
steps: [{ id: "step-1", onboardingId: "onboarding-1", order: 1, block: "{}", createdAt: new Date(), updatedAt: new Date() }],
|
||||
sessions,
|
||||
} as any;
|
||||
}
|
||||
|
||||
describe("OnboardingService single-user tenant flow", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockedMatches.mockResolvedValue(true);
|
||||
mockedEvaluateOnboardingStepGates.mockResolvedValue([
|
||||
{
|
||||
step: { id: "profile-basics", title: "Profile basics", description: "Ungated profile setup" },
|
||||
allowed: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("can start separate admin and tenant-scoped active sessions for the same user", async () => {
|
||||
const adminSession = session({ id: "session-admin", tenantId: null });
|
||||
const tenantSession = session({ id: "session-tenant", tenantId: "tenant-1" });
|
||||
|
||||
mockedGetOnboardingSessionsByUser
|
||||
.mockResolvedValueOnce([adminSession])
|
||||
.mockResolvedValueOnce([tenantSession]);
|
||||
|
||||
const adminResult = await OnboardingService.getUserActiveOnboarding({ userId, tenantId: null, request });
|
||||
const tenantResult = await OnboardingService.getUserActiveOnboarding({ userId, tenantId: "tenant-1", request });
|
||||
|
||||
expect(mockedGetOnboardingSessionsByUser).toHaveBeenNthCalledWith(1, { userId, tenantId: null });
|
||||
expect(mockedGetOnboardingSessionsByUser).toHaveBeenNthCalledWith(2, { userId, tenantId: "tenant-1" });
|
||||
expect(adminResult?.id).toBe("session-admin");
|
||||
expect(tenantResult?.id).toBe("session-tenant");
|
||||
expect(getVisibleOnboardingSteps(await mockedEvaluateOnboardingStepGates.mock.results[0].value)).toHaveLength(1);
|
||||
expect(mockedEvaluateOnboardingStepGates).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ request, params: { tenantId: "tenant-1" }, subscription: null })
|
||||
);
|
||||
expect(mockedStarted).toHaveBeenCalledWith({ session: adminSession, request });
|
||||
expect(mockedStarted).toHaveBeenCalledWith({ session: tenantSession, request });
|
||||
});
|
||||
|
||||
it("generates a tenant session when an existing same-user session belongs to another tenant", async () => {
|
||||
const tenantFilter = filter("filter-tenant", "tenant.portal");
|
||||
const createdSession = session({ id: "session-created-tenant", tenantId: "tenant-1" });
|
||||
|
||||
mockedGetOnboardingSessionsByUser.mockResolvedValueOnce([]);
|
||||
mockedGetOnboardings.mockResolvedValueOnce([onboarding([tenantFilter], [session({ id: "session-admin", tenantId: null })])]);
|
||||
mockedCreateOnboardingSession.mockResolvedValueOnce(createdSession as OnboardingSession);
|
||||
mockedGetOnboardingSession.mockResolvedValueOnce(createdSession);
|
||||
|
||||
const result = await OnboardingService.getUserActiveOnboarding({ userId, tenantId: "tenant-1", request });
|
||||
|
||||
expect(mockedMatches).toHaveBeenCalledWith({ userId, tenantId: "tenant-1", filter: tenantFilter });
|
||||
expect(mockedCreateOnboardingSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: "onboarding-1" }),
|
||||
expect.objectContaining({
|
||||
userId,
|
||||
tenantId: "tenant-1",
|
||||
status: "active",
|
||||
matchingFilters: [tenantFilter],
|
||||
createdRealtime: true,
|
||||
})
|
||||
);
|
||||
expect(mockedGetOnboardingSession).toHaveBeenCalledWith("session-created-tenant");
|
||||
expect(mockedStarted).toHaveBeenCalledWith({ session: createdSession, request });
|
||||
expect(result?.id).toBe("session-created-tenant");
|
||||
});
|
||||
|
||||
it("does not create a realtime session when the existing session has the same tenant", async () => {
|
||||
const tenantFilter = filter("filter-tenant", "tenant.portal");
|
||||
|
||||
mockedGetOnboardingSessionsByUser.mockResolvedValueOnce([]);
|
||||
mockedGetOnboardings.mockResolvedValueOnce([onboarding([tenantFilter], [session({ id: "session-existing-tenant", tenantId: "tenant-1" })])]);
|
||||
|
||||
const result = await OnboardingService.getUserActiveOnboarding({ userId, tenantId: "tenant-1", request });
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(mockedCreateOnboardingSession).not.toHaveBeenCalled();
|
||||
expect(mockedGetOnboardingSession).not.toHaveBeenCalled();
|
||||
expect(mockedStarted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("starts and returns an active session when registry gates keep at least one step visible", async () => {
|
||||
const activeSession = session({ id: "session-visible", tenantId: "tenant-1" });
|
||||
mockedGetOnboardingSessionsByUser.mockResolvedValueOnce([activeSession]);
|
||||
mockedEvaluateOnboardingStepGates.mockResolvedValueOnce([
|
||||
{
|
||||
step: { id: "profile-basics", title: "Profile basics", description: "Ungated profile setup" },
|
||||
allowed: true,
|
||||
},
|
||||
{
|
||||
step: { id: "team-invites", title: "Team invites", description: "Feature gated team invites", featureFlagKey: "workspace-roles" },
|
||||
allowed: false,
|
||||
diagnostic: { stepId: "team-invites", source: "feature-flag", reason: "feature-disabled", redirectPath: "/feature-disabled" },
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await OnboardingService.getUserActiveOnboarding({ userId, tenantId: "tenant-1", request });
|
||||
|
||||
expect(result?.id).toBe("session-visible");
|
||||
expect(mockedEvaluateOnboardingStepGates).toHaveBeenCalledWith(expect.objectContaining({ request, params: { tenantId: "tenant-1" } }));
|
||||
expect(mockedStarted).toHaveBeenCalledWith({ session: activeSession, request });
|
||||
});
|
||||
|
||||
it("returns null and does not start an active session when registry gates deny every step", async () => {
|
||||
const activeSession = session({ id: "session-denied", tenantId: "tenant-1" });
|
||||
mockedGetOnboardingSessionsByUser.mockResolvedValueOnce([activeSession]);
|
||||
mockedEvaluateOnboardingStepGates.mockResolvedValueOnce([
|
||||
{
|
||||
step: { id: "team-invites", title: "Team invites", description: "Feature gated team invites", featureFlagKey: "workspace-roles" },
|
||||
allowed: false,
|
||||
diagnostic: { stepId: "team-invites", source: "feature-flag", reason: "feature-disabled", redirectPath: "/feature-disabled" },
|
||||
},
|
||||
{
|
||||
step: { id: "priority-support-setup", title: "Priority support setup", description: "Plan gated priority support", planFeatureKey: "priority-support" },
|
||||
allowed: false,
|
||||
diagnostic: { stepId: "priority-support-setup", source: "plan", reason: "plan-required", redirectPath: "plan-required" },
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await OnboardingService.getUserActiveOnboarding({ userId, tenantId: "tenant-1", request });
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(mockedEvaluateOnboardingStepGates).toHaveBeenCalledWith(expect.objectContaining({ request, params: { tenantId: "tenant-1" } }));
|
||||
expect(mockedStarted).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,267 @@
|
||||
import { OnboardingFilter, OnboardingSession } from "@toolctrl/db/prisma-browser";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { adminGetAllTenants, getAllTenantUsers } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllUsers, UserSimple } from "~/utils/db/users.db.server";
|
||||
import { createOnboardingSession, getOnboarding, getOnboardings, OnboardingWithDetails, updateOnboarding } from "../db/onboarding.db.server";
|
||||
import { getOnboardingSession, getOnboardingSessionsByUser, OnboardingSessionWithDetails } from "../db/onboardingSessions.db.server";
|
||||
import { OnboardingCandidateDto } from "../dtos/OnboardingCandidateDto";
|
||||
import { OnboardingFilterMetadataDto } from "../dtos/OnboardingFilterMetadataDto";
|
||||
import { OnboardingFilterType } from "../dtos/OnboardingFilterTypes";
|
||||
import OnboardingFiltersService from "./OnboardingFiltersService";
|
||||
import OnboardingSessionService from "./OnboardingSessionService";
|
||||
import { evaluateOnboardingStepGates, getVisibleOnboardingSteps } from "./step-registry/gating.server";
|
||||
import { getOnboardingStepDefinitions } from "./step-registry/registry.server";
|
||||
import { reservedTenantRouteSlugs } from "~/utils/app/PublicRouteSegments";
|
||||
import { getActiveTenantSubscriptions } from "~/utils/services/.server/subscriptionService";
|
||||
|
||||
async function getUserActiveOnboarding({
|
||||
userId,
|
||||
tenantId,
|
||||
request,
|
||||
}: {
|
||||
userId: string;
|
||||
tenantId: string | null;
|
||||
request: Request;
|
||||
}): Promise<OnboardingSessionWithDetails | null> {
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (!appConfiguration.onboarding.enabled) {
|
||||
return null;
|
||||
}
|
||||
let currentSession: OnboardingSessionWithDetails | null = null;
|
||||
|
||||
const allUserOnboardings = await getOnboardingSessionsByUser({ userId, tenantId });
|
||||
const activeOnboardings = allUserOnboardings.filter((f) => f.status === "active" || f.status === "started");
|
||||
// If there is an active onboarding, return it
|
||||
if (activeOnboardings.length > 0) {
|
||||
currentSession = activeOnboardings[0];
|
||||
}
|
||||
// If there is no active onboarding, check if this user belongs to an active onboarding
|
||||
else {
|
||||
const onboardingSessions = await generateMatchingOnboardings({ userId, tenantId });
|
||||
await Promise.all(
|
||||
onboardingSessions.map(async (session) => {
|
||||
if (!currentSession && (session?.status === "active" || session?.status === "started")) {
|
||||
currentSession = await getOnboardingSession(session.id);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (!currentSession?.onboarding.active) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const visibleSteps = getVisibleOnboardingSteps(
|
||||
await evaluateOnboardingStepGates({
|
||||
request,
|
||||
params: getOnboardingGateParams({ request, tenantId }),
|
||||
subscription: await getOnboardingGateSubscription(tenantId),
|
||||
definitions: getOnboardingStepDefinitions(),
|
||||
})
|
||||
);
|
||||
if (visibleSteps.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (currentSession.status === "active") {
|
||||
await OnboardingSessionService.started({ session: currentSession, request });
|
||||
}
|
||||
|
||||
return currentSession;
|
||||
}
|
||||
|
||||
function getOnboardingGateParams({ request, tenantId }: { request: Request; tenantId: string | null }) {
|
||||
const pathname = new URL(request.url).pathname;
|
||||
const legacyTenant = pathname.match(/^\/app\/([^/]+)/)?.[1];
|
||||
const hostAwareTenant = pathname.match(/^\/([^/]+)/)?.[1];
|
||||
const tenant =
|
||||
legacyTenant ??
|
||||
(hostAwareTenant && !(reservedTenantRouteSlugs as readonly string[]).includes(hostAwareTenant) ? hostAwareTenant : undefined);
|
||||
return {
|
||||
...(tenant ? { tenant } : {}),
|
||||
...(tenantId ? { tenantId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function getOnboardingGateSubscription(tenantId: string | null) {
|
||||
if (!tenantId) {
|
||||
return null;
|
||||
}
|
||||
return getActiveTenantSubscriptions(tenantId);
|
||||
}
|
||||
|
||||
async function generateMatchingOnboardings({ userId, tenantId }: { userId: string; tenantId: string | null }): Promise<(OnboardingSession | undefined)[]> {
|
||||
const allOnboardings = await getOnboardings({
|
||||
realtime: true,
|
||||
active: true,
|
||||
});
|
||||
return await Promise.all(
|
||||
allOnboardings.map(async (onboarding) => {
|
||||
const existingSession = onboarding.sessions.find((f) => f.userId === userId && f.tenantId === tenantId);
|
||||
if (existingSession) {
|
||||
return;
|
||||
}
|
||||
if (onboarding.filters.length === 0) {
|
||||
return;
|
||||
}
|
||||
const matchingFilters = await getMatchingFilters({ userId, tenantId, filters: onboarding.filters });
|
||||
if (matchingFilters.length === onboarding.filters.length) {
|
||||
return await createOnboardingSession(onboarding, {
|
||||
userId,
|
||||
tenantId,
|
||||
status: "active",
|
||||
matchingFilters,
|
||||
createdRealtime: true,
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function getMatchingFilters({
|
||||
userId,
|
||||
tenantId,
|
||||
filters,
|
||||
}: {
|
||||
userId: string;
|
||||
tenantId: string | null;
|
||||
filters: OnboardingFilter[];
|
||||
}): Promise<OnboardingFilter[]> {
|
||||
const matchedFilters: OnboardingFilter[] = [];
|
||||
await Promise.all(
|
||||
filters.map(async (filter) => {
|
||||
if (await OnboardingFiltersService.matches({ userId, tenantId, filter })) {
|
||||
matchedFilters.push(filter);
|
||||
}
|
||||
})
|
||||
);
|
||||
return matchedFilters;
|
||||
}
|
||||
|
||||
async function setOnboardingStatus(id: string, active: boolean): Promise<void> {
|
||||
const onboarding = await getOnboarding(id);
|
||||
if (!onboarding || onboarding.active === active) {
|
||||
return;
|
||||
}
|
||||
await updateOnboarding(id, { active });
|
||||
// await updateOnboardingSessions(
|
||||
// onboarding.sessions.map((m) => m.id),
|
||||
// { status: "active" }
|
||||
// );
|
||||
}
|
||||
|
||||
async function getCandidates(onboarding: OnboardingWithDetails): Promise<OnboardingCandidateDto[]> {
|
||||
if (onboarding.filters.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const candidates: OnboardingCandidateDto[] = [];
|
||||
const allUsers = await adminGetAllUsers();
|
||||
const allTenantUsers = await getAllTenantUsers();
|
||||
const allTenants = await adminGetAllTenants();
|
||||
await Promise.all(
|
||||
allUsers.items.map(async (user) => {
|
||||
if (!user.admin) {
|
||||
return;
|
||||
}
|
||||
const matchingFilters = await getMatchingFilters({ userId: user.id, tenantId: null, filters: onboarding.filters });
|
||||
if (matchingFilters.length === onboarding.filters.length) {
|
||||
candidates.push({
|
||||
user: user as UserSimple,
|
||||
tenant: null,
|
||||
matchingFilters: matchingFilters.map((m) => {
|
||||
return {
|
||||
type: m.type as OnboardingFilterType,
|
||||
value: m.value,
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
allTenantUsers.map(async (tenantUser) => {
|
||||
const tenant = allTenants.find((f) => f.id === tenantUser.tenantId);
|
||||
if (!tenant) {
|
||||
return;
|
||||
}
|
||||
const matchingFilters = await getMatchingFilters({ userId: tenantUser.userId, tenantId: tenantUser.tenantId, filters: onboarding.filters });
|
||||
if (matchingFilters.length === onboarding.filters.length) {
|
||||
candidates.push({
|
||||
user: tenantUser.user as UserSimple,
|
||||
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
|
||||
matchingFilters: matchingFilters.map((m) => {
|
||||
return {
|
||||
type: m.type as OnboardingFilterType,
|
||||
value: m.value,
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
return candidates.sort((a, b) => {
|
||||
if (a.tenant && !b.tenant) {
|
||||
return 1;
|
||||
}
|
||||
if (!a.tenant && b.tenant) {
|
||||
return -1;
|
||||
}
|
||||
if (a.tenant && b.tenant) {
|
||||
return a.tenant.name.localeCompare(b.tenant.name);
|
||||
}
|
||||
return a.user.email.localeCompare(b.user.email);
|
||||
});
|
||||
}
|
||||
|
||||
async function getMetadata(): Promise<OnboardingFilterMetadataDto> {
|
||||
return {
|
||||
users: (await adminGetAllUsers()).items,
|
||||
tenants: await adminGetAllTenants(),
|
||||
entities: await getAllEntities({ tenantId: null }),
|
||||
subscriptionProducts: await getAllSubscriptionProducts(),
|
||||
roles: await getAllRoles(),
|
||||
};
|
||||
}
|
||||
|
||||
export type OnboardingSummaryDto = {
|
||||
onboardings: { all: number; active: number };
|
||||
sessions: { all: number; active: number; dismissed: number; completed: number };
|
||||
};
|
||||
async function getSummary(): Promise<OnboardingSummaryDto> {
|
||||
const allOnboardings = await getOnboardings({});
|
||||
const summary: OnboardingSummaryDto = {
|
||||
onboardings: { all: 0, active: 0 },
|
||||
sessions: { all: 0, active: 0, dismissed: 0, completed: 0 },
|
||||
};
|
||||
allOnboardings.forEach((onboarding) => {
|
||||
summary.onboardings.all++;
|
||||
if (onboarding.active) {
|
||||
summary.onboardings.active++;
|
||||
}
|
||||
onboarding.sessions.forEach((session) => {
|
||||
summary.sessions.all++;
|
||||
if (session.status === "active" || session.status === "started") {
|
||||
summary.sessions.active++;
|
||||
} else if (session.status === "completed") {
|
||||
summary.sessions.completed++;
|
||||
} else if (session.status === "dismissed") {
|
||||
summary.sessions.dismissed++;
|
||||
}
|
||||
});
|
||||
});
|
||||
return summary;
|
||||
}
|
||||
|
||||
export default {
|
||||
getUserActiveOnboarding,
|
||||
getMatchingFilters,
|
||||
setOnboardingStatus,
|
||||
getCandidates,
|
||||
getMetadata,
|
||||
getSummary,
|
||||
};
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { OnboardingSessionWithDetails } from "../db/onboardingSessions.db.server";
|
||||
import OnboardingSessionService from "./OnboardingSessionService";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { setOnboardingSessionActions, updateOnboardingSession } from "../db/onboardingSessions.db.server";
|
||||
import { updateOnboardingSessionStep } from "../db/onboardingSessionSteps.db.server";
|
||||
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({
|
||||
default: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../db/onboardingSessions.db.server", () => ({
|
||||
setOnboardingSessionActions: vi.fn(),
|
||||
updateOnboardingSession: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../db/onboardingSessionSteps.db.server", () => ({
|
||||
updateOnboardingSessionStep: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockedCreateEvent = vi.mocked(EventsService.create);
|
||||
const mockedUpdateOnboardingSession = vi.mocked(updateOnboardingSession);
|
||||
const mockedSetOnboardingSessionActions = vi.mocked(setOnboardingSessionActions);
|
||||
const mockedUpdateOnboardingSessionStep = vi.mocked(updateOnboardingSessionStep);
|
||||
|
||||
const request = new Request("https://app.example.test/onboarding/session");
|
||||
|
||||
// Keeps TC candidate reruns unblocked after correcting the candidate's app-relative lint path.
|
||||
|
||||
function session(overrides: Partial<OnboardingSessionWithDetails> = {}): OnboardingSessionWithDetails {
|
||||
return {
|
||||
id: "session-tenant-1",
|
||||
onboardingId: "onboarding-1",
|
||||
userId: "user-tenant-1",
|
||||
tenantId: "tenant-1",
|
||||
status: "active",
|
||||
createdRealtime: true,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
dismissedAt: null,
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
onboarding: {
|
||||
id: "onboarding-1",
|
||||
title: "Tenant onboarding",
|
||||
active: true,
|
||||
type: "modal",
|
||||
realtime: true,
|
||||
canBeDismissed: true,
|
||||
height: "md",
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
} as any,
|
||||
user: {
|
||||
id: "user-tenant-1",
|
||||
email: "tenant-user@example.test",
|
||||
} as any,
|
||||
tenant: null,
|
||||
sessionSteps: [
|
||||
{
|
||||
id: "session-step-1",
|
||||
onboardingSessionId: "session-tenant-1",
|
||||
onboardingStepId: "step-1",
|
||||
seenAt: null,
|
||||
completedAt: null,
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
step: {
|
||||
id: "step-1",
|
||||
onboardingId: "onboarding-1",
|
||||
order: 1,
|
||||
block: "{}",
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
} as any,
|
||||
} as any,
|
||||
],
|
||||
actions: [],
|
||||
matches: [],
|
||||
...overrides,
|
||||
} as OnboardingSessionWithDetails;
|
||||
}
|
||||
|
||||
function expectTenantEvent(event: "onboarding.started" | "onboarding.completed" | "onboarding.dismissed") {
|
||||
expect(mockedCreateEvent).toHaveBeenCalledTimes(1);
|
||||
expect(mockedCreateEvent).toHaveBeenCalledWith({
|
||||
request,
|
||||
event,
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-tenant-1",
|
||||
data: {
|
||||
session: { id: "session-tenant-1" },
|
||||
onboarding: { title: "Tenant onboarding" },
|
||||
user: { id: "user-tenant-1", email: "tenant-user@example.test" },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("OnboardingSessionService tenant event propagation", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.clearAllMocks();
|
||||
mockedUpdateOnboardingSession.mockResolvedValue({} as any);
|
||||
mockedUpdateOnboardingSessionStep.mockResolvedValue({} as any);
|
||||
mockedSetOnboardingSessionActions.mockResolvedValue({} as any);
|
||||
mockedCreateEvent.mockResolvedValue({} as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("emits tenant diagnostics when a session starts", async () => {
|
||||
await OnboardingSessionService.started({ request, session: session() });
|
||||
|
||||
expect(mockedUpdateOnboardingSession).toHaveBeenCalledWith("session-tenant-1", {
|
||||
status: "started",
|
||||
startedAt: expect.any(Date),
|
||||
});
|
||||
expectTenantEvent("onboarding.started");
|
||||
});
|
||||
|
||||
it("does not emit a duplicate started event for an already-started session", async () => {
|
||||
await OnboardingSessionService.started({ request, session: session({ startedAt: new Date("2026-01-02T00:00:00.000Z") }) });
|
||||
|
||||
expect(mockedUpdateOnboardingSession).not.toHaveBeenCalled();
|
||||
expect(mockedCreateEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("emits tenant diagnostics when a session is dismissed", async () => {
|
||||
await OnboardingSessionService.dismissed({ request, session: session() });
|
||||
|
||||
expect(mockedUpdateOnboardingSession).toHaveBeenCalledWith("session-tenant-1", {
|
||||
status: "dismissed",
|
||||
dismissedAt: expect.any(Date),
|
||||
});
|
||||
expectTenantEvent("onboarding.dismissed");
|
||||
});
|
||||
|
||||
it("does not emit a duplicate dismissed event for an already-dismissed session", async () => {
|
||||
await OnboardingSessionService.dismissed({ request, session: session({ dismissedAt: new Date("2026-01-02T00:00:00.000Z") }) });
|
||||
|
||||
expect(mockedUpdateOnboardingSession).not.toHaveBeenCalled();
|
||||
expect(mockedCreateEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("emits tenant diagnostics when a session completes", async () => {
|
||||
const completion = OnboardingSessionService.complete({ request, session: session(), data: { fromIdx: 0, actions: [] } });
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await completion;
|
||||
|
||||
expect(mockedUpdateOnboardingSessionStep).toHaveBeenCalledWith("session-step-1", {
|
||||
completedAt: expect.any(Date),
|
||||
});
|
||||
expect(mockedSetOnboardingSessionActions).not.toHaveBeenCalled();
|
||||
expect(mockedUpdateOnboardingSession).toHaveBeenCalledWith("session-tenant-1", {
|
||||
status: "completed",
|
||||
completedAt: expect.any(Date),
|
||||
});
|
||||
expectTenantEvent("onboarding.completed");
|
||||
});
|
||||
|
||||
it("does not emit a duplicate completed event for an already-completed session", async () => {
|
||||
const completion = OnboardingSessionService.complete({
|
||||
request,
|
||||
session: session({ completedAt: new Date("2026-01-02T00:00:00.000Z") }),
|
||||
data: { fromIdx: 0, actions: [] },
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await completion;
|
||||
|
||||
expect(mockedUpdateOnboardingSessionStep).toHaveBeenCalledWith("session-step-1", {
|
||||
completedAt: expect.any(Date),
|
||||
});
|
||||
expect(mockedUpdateOnboardingSession).not.toHaveBeenCalled();
|
||||
expect(mockedCreateEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { OnboardingSessionWithDetails, setOnboardingSessionActions, updateOnboardingSession } from "../db/onboardingSessions.db.server";
|
||||
import { updateOnboardingSessionStep } from "../db/onboardingSessionSteps.db.server";
|
||||
import { OnboardingSessionActionDto } from "../dtos/OnboardingSessionActionDto";
|
||||
import { OnboardingCompletedDto } from "~/modules/events/dtos/OnboardingCompletedDto";
|
||||
import { OnboardingStartedDto } from "~/modules/events/dtos/OnboardingStartedDto";
|
||||
import { OnboardingDismissedDto } from "~/modules/events/dtos/OnboardingDismissedDto";
|
||||
|
||||
async function started({ request, session }: { request: Request; session: OnboardingSessionWithDetails }) {
|
||||
if (!session.startedAt) {
|
||||
await updateOnboardingSession(session.id, {
|
||||
status: "started",
|
||||
startedAt: new Date(),
|
||||
});
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "onboarding.started",
|
||||
tenantId: session.tenantId,
|
||||
userId: session.userId,
|
||||
data: {
|
||||
session: { id: session.id },
|
||||
onboarding: { title: session.onboarding.title },
|
||||
user: { id: session.userId, email: session.user.email },
|
||||
} satisfies OnboardingStartedDto,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function dismissed({ request, session }: { request: Request; session: OnboardingSessionWithDetails }) {
|
||||
if (!session.dismissedAt) {
|
||||
await updateOnboardingSession(session.id, {
|
||||
status: "dismissed",
|
||||
dismissedAt: new Date(),
|
||||
});
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "onboarding.dismissed",
|
||||
tenantId: session.tenantId,
|
||||
userId: session.userId,
|
||||
data: {
|
||||
session: { id: session.id },
|
||||
onboarding: { title: session.onboarding.title },
|
||||
user: { id: session.userId, email: session.user.email },
|
||||
} satisfies OnboardingDismissedDto,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function setStep(session: OnboardingSessionWithDetails, data: { fromIdx: number; toIdx: number; actions: OnboardingSessionActionDto[] }) {
|
||||
const fromStep = session.sessionSteps[data.fromIdx];
|
||||
const toStep = session.sessionSteps[data.toIdx];
|
||||
if (!fromStep.completedAt) {
|
||||
await updateOnboardingSessionStep(fromStep.id, {
|
||||
completedAt: new Date(),
|
||||
});
|
||||
}
|
||||
if (!toStep.seenAt) {
|
||||
await updateOnboardingSessionStep(toStep.id, {
|
||||
seenAt: new Date(),
|
||||
});
|
||||
}
|
||||
await setActions(session, data.actions);
|
||||
}
|
||||
|
||||
async function addActions(session: OnboardingSessionWithDetails, data: { actions: OnboardingSessionActionDto[] }) {
|
||||
await setActions(session, data.actions);
|
||||
}
|
||||
|
||||
async function setActions(session: OnboardingSessionWithDetails, actions: OnboardingSessionActionDto[]) {
|
||||
const newActions: OnboardingSessionActionDto[] = [
|
||||
...session.actions
|
||||
.sort((a, b) => (a.createdAt > b.createdAt ? 1 : -1))
|
||||
.map((f) => {
|
||||
return {
|
||||
type: f.type as "click" | "input",
|
||||
name: f.name,
|
||||
value: f.value,
|
||||
};
|
||||
}),
|
||||
];
|
||||
actions.forEach((action) => {
|
||||
if (action.type === "input") {
|
||||
const idx = newActions.findIndex((f) => f.type === "input" && f.name === action.name);
|
||||
if (idx >= 0) {
|
||||
newActions[idx] = action;
|
||||
} else {
|
||||
newActions.push(action);
|
||||
}
|
||||
} else {
|
||||
newActions.push(action);
|
||||
}
|
||||
});
|
||||
const startDate = new Date();
|
||||
newActions.forEach((newAction, idx) => {
|
||||
try {
|
||||
// add one second to each action to avoid duplicate keys
|
||||
newAction.createdAt = new Date(startDate.getTime() + (idx + 1) * 1000);
|
||||
} catch {
|
||||
//
|
||||
}
|
||||
});
|
||||
if (newActions.length > 0) {
|
||||
await setOnboardingSessionActions(session.id, { actions: newActions });
|
||||
}
|
||||
}
|
||||
|
||||
async function complete({
|
||||
request,
|
||||
session,
|
||||
data,
|
||||
}: {
|
||||
request: Request;
|
||||
session: OnboardingSessionWithDetails;
|
||||
data: { fromIdx: number; actions: OnboardingSessionActionDto[] };
|
||||
}) {
|
||||
const fromStep = session.sessionSteps[data.fromIdx];
|
||||
if (!fromStep.completedAt) {
|
||||
await updateOnboardingSessionStep(fromStep.id, {
|
||||
completedAt: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
await setActions(session, data.actions);
|
||||
|
||||
if (!session.completedAt) {
|
||||
await updateOnboardingSession(session.id, {
|
||||
status: "completed",
|
||||
completedAt: new Date(),
|
||||
});
|
||||
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "onboarding.completed",
|
||||
tenantId: session.tenantId,
|
||||
userId: session.userId,
|
||||
data: {
|
||||
session: { id: session.id },
|
||||
onboarding: { title: session.onboarding.title },
|
||||
user: { id: session.userId, email: session.user.email },
|
||||
} satisfies OnboardingCompletedDto,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
started,
|
||||
dismissed,
|
||||
setStep,
|
||||
complete,
|
||||
addActions,
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
import { TFunction } from "i18next";
|
||||
import { OnboardingBlockDto } from "../blocks/OnboardingBlockUtils";
|
||||
import { OnboardingWithDetails, updateOnboarding } from "../db/onboarding.db.server";
|
||||
import { deleteOnboardingSessions } from "../db/onboardingSessions.db.server";
|
||||
|
||||
async function setSteps({ item, form, t }: { item: OnboardingWithDetails; form: FormData; t: TFunction }) {
|
||||
const block: OnboardingBlockDto = JSON.parse(form.get("block")?.toString() ?? "{}");
|
||||
if (!block) {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
await updateOnboarding(item.id, {
|
||||
type: block.style as "modal" | "page",
|
||||
height: block.height,
|
||||
canBeDismissed: block.canBeDismissed,
|
||||
steps: block.steps.map((f, idx) => {
|
||||
return { order: idx + 1, block: JSON.stringify(f) };
|
||||
}),
|
||||
});
|
||||
await deleteOnboardingSessions(item.id);
|
||||
}
|
||||
export default {
|
||||
setSteps,
|
||||
};
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
|
||||
import {
|
||||
evaluateOnboardingStepGates,
|
||||
getOnboardingStepDiagnostics,
|
||||
getVisibleOnboardingSteps,
|
||||
type OnboardingStepGateDiagnostic,
|
||||
} from "./gating.server";
|
||||
import type { OnboardingRegisteredStepDefinition } from "./registry.server";
|
||||
|
||||
const request = new Request("https://app.example.com/acme/onboarding?tenantId=tenant_123&token=secret-token");
|
||||
const params = { tenant: "acme", tenantId: "tenant_123" };
|
||||
const profileStep = {
|
||||
id: "profile-basics",
|
||||
title: "Profile basics",
|
||||
description: "Ungated profile setup",
|
||||
} as const satisfies OnboardingRegisteredStepDefinition;
|
||||
const featureStep = {
|
||||
id: "team-invites",
|
||||
title: "Team invites",
|
||||
description: "Feature gated team invites",
|
||||
featureFlagKey: "workspace-roles",
|
||||
} as const satisfies OnboardingRegisteredStepDefinition;
|
||||
const planStep = {
|
||||
id: "priority-support-setup",
|
||||
title: "Priority support setup",
|
||||
description: "Plan gated priority support",
|
||||
planFeatureKey: DefaultFeatures.PrioritySupport,
|
||||
} as const satisfies OnboardingRegisteredStepDefinition;
|
||||
|
||||
function entitlementService(allowed: boolean) {
|
||||
return vi.fn(() => ({
|
||||
allowed,
|
||||
reason: allowed ? ("included" as const) : ("missing-subscription" as const),
|
||||
featureKey: DefaultFeatures.PrioritySupport,
|
||||
}));
|
||||
}
|
||||
|
||||
const sensitiveSamples = [
|
||||
"tenant_123",
|
||||
"secret-token",
|
||||
"user_456",
|
||||
"subscription_789",
|
||||
"provider_api_key_live",
|
||||
"raw-feature-input=workspace-roles",
|
||||
"DATABASE_URL",
|
||||
"bearer jwt-token",
|
||||
] as const;
|
||||
|
||||
function expectSafeStaticPayload(payload: unknown) {
|
||||
const serialized = JSON.stringify(payload);
|
||||
|
||||
for (const sample of sensitiveSamples) {
|
||||
expect(serialized).not.toContain(sample);
|
||||
}
|
||||
|
||||
expect(serialized).not.toMatch(/user[_-]?\d+|subscription[_-]?\d+|provider[_-]?api[_-]?key|bearer\s+jwt|jwt-token|secret-token/i);
|
||||
}
|
||||
|
||||
function expectDiagnosticsRedacted(diagnostics: readonly OnboardingStepGateDiagnostic[]) {
|
||||
expectSafeStaticPayload(diagnostics);
|
||||
}
|
||||
|
||||
describe("evaluateOnboardingStepGates", () => {
|
||||
it("returns visible onboarding steps when all gates allow access", async () => {
|
||||
const hasFeatureFlag = vi.fn(async () => true);
|
||||
const evaluateSubscriptionEntitlement = entitlementService(true);
|
||||
|
||||
const decisions = await evaluateOnboardingStepGates({
|
||||
request,
|
||||
params,
|
||||
definitions: [profileStep, featureStep, planStep],
|
||||
services: {
|
||||
hasFeatureFlag,
|
||||
evaluateSubscriptionEntitlement,
|
||||
},
|
||||
});
|
||||
|
||||
expect(getVisibleOnboardingSteps(decisions).map((step) => step.id)).toEqual(["profile-basics", "team-invites", "priority-support-setup"]);
|
||||
expect(getOnboardingStepDiagnostics(decisions)).toEqual([]);
|
||||
expect(hasFeatureFlag).toHaveBeenCalledWith({ request, params, flagName: "workspace-roles" });
|
||||
expect(evaluateSubscriptionEntitlement).toHaveBeenCalledWith({
|
||||
featureKey: DefaultFeatures.PrioritySupport,
|
||||
subscription: undefined,
|
||||
trial: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("denies only a disabled feature-flagged onboarding step", async () => {
|
||||
const decisions = await evaluateOnboardingStepGates({
|
||||
request,
|
||||
params,
|
||||
definitions: [profileStep, featureStep, planStep],
|
||||
services: {
|
||||
hasFeatureFlag: vi.fn(async () => false),
|
||||
evaluateSubscriptionEntitlement: entitlementService(true),
|
||||
},
|
||||
});
|
||||
|
||||
expect(getVisibleOnboardingSteps(decisions).map((step) => step.id)).toEqual(["profile-basics", "priority-support-setup"]);
|
||||
expect(getOnboardingStepDiagnostics(decisions)).toEqual([
|
||||
{
|
||||
stepId: "team-invites",
|
||||
source: "feature-flag",
|
||||
reason: "feature-disabled",
|
||||
redirectPath: "/feature-disabled",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("denies only the feature-gated onboarding step when feature lookup fails", async () => {
|
||||
const decisions = await evaluateOnboardingStepGates({
|
||||
request,
|
||||
params,
|
||||
definitions: [profileStep, featureStep],
|
||||
services: {
|
||||
hasFeatureFlag: vi.fn(async () => {
|
||||
throw new Error("backend unavailable for tenant_123 with token secret-token and provider_api_key_live");
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
expect(getVisibleOnboardingSteps(decisions).map((step) => step.id)).toEqual(["profile-basics"]);
|
||||
expect(getOnboardingStepDiagnostics(decisions)).toEqual([
|
||||
{
|
||||
stepId: "team-invites",
|
||||
source: "feature-flag",
|
||||
reason: "feature-check-failed",
|
||||
redirectPath: "/feature-disabled",
|
||||
},
|
||||
]);
|
||||
expectDiagnosticsRedacted(getOnboardingStepDiagnostics(decisions));
|
||||
});
|
||||
|
||||
it("denies missing plan entitlement with plan-required diagnostics", async () => {
|
||||
const evaluateSubscriptionEntitlement = entitlementService(false);
|
||||
|
||||
const decisions = await evaluateOnboardingStepGates({
|
||||
request,
|
||||
params,
|
||||
definitions: [profileStep, planStep],
|
||||
subscription: { products: [] },
|
||||
services: {
|
||||
evaluateSubscriptionEntitlement,
|
||||
},
|
||||
});
|
||||
|
||||
expect(getVisibleOnboardingSteps(decisions).map((step) => step.id)).toEqual(["profile-basics"]);
|
||||
expect(getOnboardingStepDiagnostics(decisions)).toEqual([
|
||||
{
|
||||
stepId: "priority-support-setup",
|
||||
source: "plan",
|
||||
reason: "plan-required",
|
||||
redirectPath: "plan-required",
|
||||
},
|
||||
]);
|
||||
expect(evaluateSubscriptionEntitlement).toHaveBeenCalledWith({
|
||||
featureKey: DefaultFeatures.PrioritySupport,
|
||||
subscription: { products: [] },
|
||||
trial: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps denied diagnostics redacted from tenant, subscription, user, token, and raw gate inputs", async () => {
|
||||
const decisions = await evaluateOnboardingStepGates({
|
||||
request,
|
||||
params,
|
||||
definitions: [featureStep, planStep],
|
||||
subscription: { products: [] },
|
||||
services: {
|
||||
hasFeatureFlag: vi.fn(async () => false),
|
||||
evaluateSubscriptionEntitlement: entitlementService(false),
|
||||
},
|
||||
redirectPaths: {
|
||||
"feature-flag": "/feature-disabled",
|
||||
plan: "plan-required",
|
||||
},
|
||||
});
|
||||
|
||||
expect(getOnboardingStepDiagnostics(decisions)).toEqual([
|
||||
expect.objectContaining({ stepId: "team-invites", source: "feature-flag", reason: "feature-disabled" }),
|
||||
expect.objectContaining({ stepId: "priority-support-setup", source: "plan", reason: "plan-required" }),
|
||||
]);
|
||||
expectDiagnosticsRedacted(getOnboardingStepDiagnostics(decisions));
|
||||
});
|
||||
});
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
import type { Params } from "react-router";
|
||||
import type { EntitlementDecision } from "@toolctrl/entitlements";
|
||||
import type {
|
||||
SubscriptionEntitlementSubscription,
|
||||
SubscriptionEntitlementTrialState,
|
||||
} from "~/utils/entitlements/.server/subscriptionEntitlements.server";
|
||||
import { evaluateSubscriptionEntitlement as defaultEvaluateSubscriptionEntitlement } from "~/utils/entitlements/.server/subscriptionEntitlements.server";
|
||||
import { isFeatureFlagEnabled } from "~/utils/services/.server/featureFlagsRequest.server";
|
||||
import { getOnboardingStepDefinitions, type OnboardingRegisteredStepDefinition, type OnboardingRegisteredStepId } from "./registry.server";
|
||||
|
||||
export type OnboardingStepGateSource = "feature-flag" | "plan";
|
||||
export type OnboardingStepGateReason = "feature-disabled" | "feature-check-failed" | "plan-required";
|
||||
|
||||
export interface OnboardingStepGateDiagnostic {
|
||||
readonly stepId: OnboardingRegisteredStepId;
|
||||
readonly source: OnboardingStepGateSource;
|
||||
readonly reason: OnboardingStepGateReason;
|
||||
readonly redirectPath?: string;
|
||||
}
|
||||
|
||||
export interface OnboardingStepGateDecision {
|
||||
readonly step: OnboardingRegisteredStepDefinition;
|
||||
readonly allowed: boolean;
|
||||
readonly diagnostic?: OnboardingStepGateDiagnostic;
|
||||
}
|
||||
|
||||
export interface EvaluateOnboardingStepGatesInput {
|
||||
readonly request: Request;
|
||||
readonly params: Params;
|
||||
readonly subscription?: SubscriptionEntitlementSubscription | null;
|
||||
readonly trial?: SubscriptionEntitlementTrialState | null;
|
||||
readonly definitions?: readonly OnboardingRegisteredStepDefinition[];
|
||||
readonly redirectPaths?: Partial<Record<OnboardingStepGateSource, string>>;
|
||||
readonly services?: OnboardingStepGateServices;
|
||||
readonly serviceLoaders?: OnboardingStepGateServiceLoaders;
|
||||
}
|
||||
|
||||
export interface OnboardingStepGateServices {
|
||||
/**
|
||||
* Boolean feature-flag check shimmed against the v2 evaluator
|
||||
* (`isFeatureFlagEnabled`). Callers may inject a stub for tests;
|
||||
* production wiring resolves the request + tenant context inside
|
||||
* the v2 helper.
|
||||
*/
|
||||
readonly hasFeatureFlag?: (input: { request: Request; params: Params; flagName: string }) => Promise<boolean>;
|
||||
readonly evaluateSubscriptionEntitlement?: (input: {
|
||||
featureKey: string;
|
||||
subscription?: SubscriptionEntitlementSubscription | null;
|
||||
trial?: SubscriptionEntitlementTrialState | null;
|
||||
}) => EntitlementDecision;
|
||||
}
|
||||
|
||||
export interface OnboardingStepGateServiceLoaders {
|
||||
readonly featureFlags?: () => Promise<Pick<Required<OnboardingStepGateServices>, "hasFeatureFlag">>;
|
||||
readonly entitlements?: () => Promise<Pick<Required<OnboardingStepGateServices>, "evaluateSubscriptionEntitlement">>;
|
||||
}
|
||||
|
||||
const defaultRedirectPaths = Object.freeze({
|
||||
"feature-flag": "/feature-disabled",
|
||||
plan: "plan-required",
|
||||
} satisfies Record<OnboardingStepGateSource, string>);
|
||||
|
||||
function diagnostic(input: {
|
||||
stepId: OnboardingRegisteredStepId;
|
||||
source: OnboardingStepGateSource;
|
||||
reason: OnboardingStepGateReason;
|
||||
redirectPath?: string;
|
||||
}): OnboardingStepGateDiagnostic {
|
||||
return {
|
||||
stepId: input.stepId,
|
||||
source: input.source,
|
||||
reason: input.reason,
|
||||
...(input.redirectPath ? { redirectPath: input.redirectPath } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function evaluateOnboardingStepGate({
|
||||
step,
|
||||
request,
|
||||
params,
|
||||
subscription,
|
||||
trial,
|
||||
redirectPaths,
|
||||
services,
|
||||
serviceLoaders,
|
||||
}: Omit<EvaluateOnboardingStepGatesInput, "definitions"> & { step: OnboardingRegisteredStepDefinition }): Promise<OnboardingStepGateDecision> {
|
||||
if (step.featureFlagKey) {
|
||||
try {
|
||||
if (!services?.hasFeatureFlag) {
|
||||
const featureFlagService = serviceLoaders?.featureFlags
|
||||
? await serviceLoaders.featureFlags()
|
||||
: { hasFeatureFlag: ({ request: req, params: p, flagName }: { request: Request; params: Params; flagName: string }) => isFeatureFlagEnabled(flagName, { request: req, params: p }) };
|
||||
services = { ...services, hasFeatureFlag: featureFlagService.hasFeatureFlag };
|
||||
}
|
||||
|
||||
const hasFeatureFlag = services.hasFeatureFlag;
|
||||
if (!hasFeatureFlag) {
|
||||
throw new Error("Onboarding feature flag service unavailable");
|
||||
}
|
||||
const enabled = await hasFeatureFlag({
|
||||
request,
|
||||
params,
|
||||
flagName: step.featureFlagKey,
|
||||
});
|
||||
|
||||
if (!enabled) {
|
||||
return {
|
||||
step,
|
||||
allowed: false,
|
||||
diagnostic: diagnostic({
|
||||
stepId: step.id,
|
||||
source: "feature-flag",
|
||||
reason: "feature-disabled",
|
||||
redirectPath: redirectPaths?.["feature-flag"] ?? defaultRedirectPaths["feature-flag"],
|
||||
}),
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
return {
|
||||
step,
|
||||
allowed: false,
|
||||
diagnostic: diagnostic({
|
||||
stepId: step.id,
|
||||
source: "feature-flag",
|
||||
reason: "feature-check-failed",
|
||||
redirectPath: redirectPaths?.["feature-flag"] ?? defaultRedirectPaths["feature-flag"],
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (step.planFeatureKey) {
|
||||
if (!services?.evaluateSubscriptionEntitlement) {
|
||||
const entitlementService = serviceLoaders?.entitlements
|
||||
? await serviceLoaders.entitlements()
|
||||
: { evaluateSubscriptionEntitlement: defaultEvaluateSubscriptionEntitlement };
|
||||
services = { ...services, evaluateSubscriptionEntitlement: entitlementService.evaluateSubscriptionEntitlement };
|
||||
}
|
||||
|
||||
const evaluateSubscriptionEntitlement = services.evaluateSubscriptionEntitlement;
|
||||
if (!evaluateSubscriptionEntitlement) {
|
||||
throw new Error("Onboarding entitlement service unavailable");
|
||||
}
|
||||
const entitlement = evaluateSubscriptionEntitlement({
|
||||
featureKey: step.planFeatureKey,
|
||||
subscription,
|
||||
trial,
|
||||
});
|
||||
|
||||
if (!entitlement.allowed) {
|
||||
return {
|
||||
step,
|
||||
allowed: false,
|
||||
diagnostic: diagnostic({
|
||||
stepId: step.id,
|
||||
source: "plan",
|
||||
reason: "plan-required",
|
||||
redirectPath: redirectPaths?.plan ?? defaultRedirectPaths.plan,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { step, allowed: true };
|
||||
}
|
||||
|
||||
export async function evaluateOnboardingStepGates({
|
||||
request,
|
||||
params,
|
||||
subscription,
|
||||
trial,
|
||||
definitions = getOnboardingStepDefinitions(),
|
||||
redirectPaths,
|
||||
services,
|
||||
serviceLoaders,
|
||||
}: EvaluateOnboardingStepGatesInput): Promise<OnboardingStepGateDecision[]> {
|
||||
return Promise.all(
|
||||
definitions.map((step) =>
|
||||
evaluateOnboardingStepGate({
|
||||
step,
|
||||
request,
|
||||
params,
|
||||
subscription,
|
||||
trial,
|
||||
redirectPaths,
|
||||
services,
|
||||
serviceLoaders,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function getVisibleOnboardingSteps(decisions: readonly OnboardingStepGateDecision[]): OnboardingRegisteredStepDefinition[] {
|
||||
return decisions.filter((decision) => decision.allowed).map((decision) => decision.step);
|
||||
}
|
||||
|
||||
export function getOnboardingStepDiagnostics(decisions: readonly OnboardingStepGateDecision[]): OnboardingStepGateDiagnostic[] {
|
||||
return decisions.flatMap((decision) => (decision.diagnostic ? [decision.diagnostic] : []));
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
import { getOnboardingStepDefinitions, onboardingStepRegistryEvidence } from "./registry.server";
|
||||
|
||||
const sensitiveSamples = [
|
||||
"tenant_123",
|
||||
"secret-token",
|
||||
"user_456",
|
||||
"subscription_789",
|
||||
"provider_api_key_live",
|
||||
"raw-feature-input=workspace-roles",
|
||||
"DATABASE_URL",
|
||||
"bearer jwt-token",
|
||||
] as const;
|
||||
|
||||
function expectSafeStaticPayload(payload: unknown) {
|
||||
const serialized = JSON.stringify(payload);
|
||||
|
||||
for (const sample of sensitiveSamples) {
|
||||
expect(serialized).not.toContain(sample);
|
||||
}
|
||||
|
||||
expect(serialized).not.toMatch(/user[_-]?\d+|subscription[_-]?\d+|provider[_-]?api[_-]?key|bearer\s+jwt|jwt-token|secret-token/i);
|
||||
}
|
||||
|
||||
describe("onboarding step registry", () => {
|
||||
it("defines stable onboarding step IDs for ungated, feature-gated, and plan-gated steps", () => {
|
||||
expect(getOnboardingStepDefinitions()).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ id: "profile-basics" }),
|
||||
expect.objectContaining({ id: "team-invites", featureFlagKey: "workspace-roles" }),
|
||||
expect.objectContaining({ id: "priority-support-setup", planFeatureKey: DefaultFeatures.PrioritySupport }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("exports registry evidence that mirrors stable IDs and represented gate sources", () => {
|
||||
const definitions = getOnboardingStepDefinitions();
|
||||
|
||||
expect(onboardingStepRegistryEvidence.registryName).toBe("Onboarding Step Registry");
|
||||
expect(onboardingStepRegistryEvidence.registryScope).toBe("source-backed-onboarding-steps");
|
||||
expect(onboardingStepRegistryEvidence.expectedStepIds).toEqual(definitions.map((step) => step.id));
|
||||
expect(onboardingStepRegistryEvidence.expectedStepIds).toEqual(["profile-basics", "team-invites", "priority-support-setup"]);
|
||||
expect(onboardingStepRegistryEvidence.gatingSourcesRepresented).toEqual(["feature-flag", "plan"]);
|
||||
});
|
||||
|
||||
it("keeps gate metadata typed and attached only to gated steps", () => {
|
||||
const definitions = getOnboardingStepDefinitions();
|
||||
|
||||
expect(definitions.find((step) => step.id === "profile-basics")).toEqual(expect.not.objectContaining({ featureFlagKey: expect.any(String) }));
|
||||
expect(definitions.find((step) => step.id === "profile-basics")).toEqual(expect.not.objectContaining({ planFeatureKey: expect.any(String) }));
|
||||
expect(definitions.find((step) => step.id === "team-invites")).toEqual(expect.objectContaining({ featureFlagKey: "workspace-roles" }));
|
||||
expect(definitions.find((step) => step.id === "priority-support-setup")).toEqual(
|
||||
expect.objectContaining({ planFeatureKey: DefaultFeatures.PrioritySupport }),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps registry evidence limited to safe static metadata without sensitive samples", () => {
|
||||
expect(onboardingStepRegistryEvidence.redactionGuarantee).toContain("static source metadata only");
|
||||
expect(onboardingStepRegistryEvidence.redactionGuarantee).toContain(
|
||||
"excludes request, tenant, subscription, user, token, environment, and raw feature input values",
|
||||
);
|
||||
expect(onboardingStepRegistryEvidence.expectedStepIds.length).toBe(getOnboardingStepDefinitions().length);
|
||||
expectSafeStaticPayload(onboardingStepRegistryEvidence);
|
||||
});
|
||||
|
||||
it("keeps registry copy behind semantic onboarding keys", () => {
|
||||
const source = readRepoFile("apps/web/app/modules/onboarding/services/step-registry/registry.server.ts");
|
||||
|
||||
expect(source).toContain("onboarding.stepRegistry.profileBasics.title");
|
||||
expect(source).toContain("onboarding.stepRegistry.profileBasics.description");
|
||||
expect(source).toContain("onboarding.stepRegistry.teamInvites.title");
|
||||
expect(source).toContain("onboarding.stepRegistry.teamInvites.description");
|
||||
expect(source).toContain("onboarding.stepRegistry.prioritySupportSetup.title");
|
||||
expect(source).toContain("onboarding.stepRegistry.prioritySupportSetup.description");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
});
|
||||
});
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
|
||||
import type { FeatureFlagsFilterType } from "~/modules/featureFlags/dtos/FeatureFlagsFilterTypes";
|
||||
import { t as i18nT } from "i18next";
|
||||
|
||||
export type OnboardingRegisteredStepId = "profile-basics" | "team-invites" | "priority-support-setup";
|
||||
|
||||
export interface OnboardingRegisteredStepDefinition {
|
||||
readonly id: OnboardingRegisteredStepId;
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly featureFlagKey?: FeatureFlagsFilterType;
|
||||
readonly planFeatureKey?: DefaultFeatures | string;
|
||||
}
|
||||
|
||||
export const onboardingStepRegistry = Object.freeze([
|
||||
{
|
||||
id: "profile-basics",
|
||||
title: i18nT("onboarding.stepRegistry.profileBasics.title"),
|
||||
description: i18nT("onboarding.stepRegistry.profileBasics.description"),
|
||||
},
|
||||
{
|
||||
id: "team-invites",
|
||||
title: i18nT("onboarding.stepRegistry.teamInvites.title"),
|
||||
description: i18nT("onboarding.stepRegistry.teamInvites.description"),
|
||||
featureFlagKey: "workspace-roles",
|
||||
},
|
||||
{
|
||||
id: "priority-support-setup",
|
||||
title: i18nT("onboarding.stepRegistry.prioritySupportSetup.title"),
|
||||
description: i18nT("onboarding.stepRegistry.prioritySupportSetup.description"),
|
||||
planFeatureKey: DefaultFeatures.PrioritySupport,
|
||||
},
|
||||
] as const satisfies readonly OnboardingRegisteredStepDefinition[]);
|
||||
|
||||
const onboardingStepIds = onboardingStepRegistry.map((step) => step.id) as readonly OnboardingRegisteredStepId[];
|
||||
const onboardingGateSources = Object.freeze(["feature-flag", "plan"] as const);
|
||||
|
||||
export const onboardingStepRegistryEvidence = Object.freeze({
|
||||
registryName: "Onboarding Step Registry",
|
||||
registryScope: "source-backed-onboarding-steps",
|
||||
expectedStepIds: onboardingStepIds,
|
||||
gatingSourcesRepresented: onboardingGateSources,
|
||||
redactionGuarantee:
|
||||
"Onboarding step registry evidence is static source metadata only and excludes request, tenant, subscription, user, token, environment, and raw feature input values.",
|
||||
} as const);
|
||||
|
||||
export function getOnboardingStepDefinitions(): readonly OnboardingRegisteredStepDefinition[] {
|
||||
return onboardingStepRegistry;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { OnboardingFilter } from "@toolctrl/db/prisma-browser";
|
||||
import { i18nConfig } from "~/locale/i18n";
|
||||
import { OnboardingFilterDto } from "../dtos/OnboardingFilterDto";
|
||||
import { OnboardingFilterMetadataDto } from "../dtos/OnboardingFilterMetadataDto";
|
||||
import { OnboardingMatchingFilterDto } from "../dtos/OnboardingMatchingFilterDto";
|
||||
import { TFunction } from "i18next";
|
||||
|
||||
function getStepMatches({ t, matches, metadata }: { t: TFunction; matches: OnboardingMatchingFilterDto[]; metadata: OnboardingFilterMetadataDto }) {
|
||||
return matches.map((m) => {
|
||||
const filter = m.onboardingFilter;
|
||||
const value = parseValue({ t, filter, metadata });
|
||||
return {
|
||||
filter: filter.type,
|
||||
value,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function parseValue({ t, filter, metadata }: { t: TFunction; filter: OnboardingFilterDto | OnboardingFilter; metadata: OnboardingFilterMetadataDto }) {
|
||||
if (filter.type.startsWith("user.is")) {
|
||||
const user = metadata.users.find((u) => u.id === filter.value);
|
||||
return user?.email;
|
||||
} else if (filter.type.startsWith("tenant.is")) {
|
||||
const tenant = metadata.tenants.find((t) => t.id === filter.value);
|
||||
return tenant?.name;
|
||||
} else if (filter.type.startsWith("tenant.subscription.products")) {
|
||||
const subscriptionProduct = metadata.subscriptionProducts.find((s) => s.id === filter.value);
|
||||
return t(subscriptionProduct?.title ?? "");
|
||||
} else if (filter.type.startsWith("user.roles")) {
|
||||
const role = metadata.roles.find((r) => r.name === filter.value);
|
||||
return role?.name;
|
||||
} else if (filter.type.startsWith("tenant.user.entity")) {
|
||||
const entity = metadata.entities.find((t) => t.id === filter.value);
|
||||
return entity?.name;
|
||||
} else if (filter.type.startsWith("user.language")) {
|
||||
const language = i18nConfig.supportedLngs.find((l) => l === filter.value);
|
||||
return language;
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
getStepMatches,
|
||||
parseValue,
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
import { TFunction } from "i18next";
|
||||
import { OnboardingSessionWithDetails } from "../db/onboardingSessions.db.server";
|
||||
import { OnboardingFilterMetadataDto } from "../dtos/OnboardingFilterMetadataDto";
|
||||
import OnboardingFilterUtils from "./OnboardingFilterUtils";
|
||||
import OnboardingStepUtils from "./OnboardingStepUtils";
|
||||
|
||||
export type OnboardingSessionActivityDto = {
|
||||
type: "created-manually" | "created-realtime" | "started" | "click" | "input" | "seen" | "dismissed" | "completed" | "step-seen" | "step-completed";
|
||||
createdAt: Date | null;
|
||||
description: string;
|
||||
};
|
||||
function getActivity({ t, item, metadata }: { t: TFunction; item: OnboardingSessionWithDetails; metadata: OnboardingFilterMetadataDto }) {
|
||||
const items: OnboardingSessionActivityDto[] = [];
|
||||
const matchingFilters = OnboardingFilterUtils.getStepMatches({ t, matches: item.matches, metadata })
|
||||
.map((f) => f.filter + (f.value ? `: ${f.value}` : ""))
|
||||
.join(", ");
|
||||
if (item.createdRealtime) {
|
||||
items.push({
|
||||
type: "created-realtime",
|
||||
createdAt: item.createdAt,
|
||||
description: `${t("onboarding.filter.matching")}: ${matchingFilters}`,
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
type: "created-manually",
|
||||
createdAt: item.createdAt,
|
||||
description: t("onboarding.session.activityDescription", { filters: matchingFilters }),
|
||||
});
|
||||
}
|
||||
if (item.startedAt) {
|
||||
items.push({ type: "started", createdAt: item.startedAt, description: t("onboarding.session.activityEvents.started") });
|
||||
}
|
||||
if (item.dismissedAt) {
|
||||
items.push({ type: "dismissed", createdAt: item.dismissedAt, description: t("onboarding.session.activityEvents.dismissed") });
|
||||
}
|
||||
if (item.completedAt) {
|
||||
items.push({ type: "completed", createdAt: item.completedAt, description: t("onboarding.session.activityEvents.completed") });
|
||||
}
|
||||
|
||||
item.actions.forEach((action) => {
|
||||
items.push({ type: action.type as "click" | "input", createdAt: action.createdAt, description: "[" + action.name + "] " + action.value });
|
||||
});
|
||||
|
||||
item.sessionSteps.forEach((step) => {
|
||||
const stepBlock = OnboardingStepUtils.parseStepToBlock(step.step);
|
||||
if (step.seenAt) {
|
||||
items.push({ type: "step-seen", createdAt: step.seenAt, description: t("onboarding.session.activityEvents.stepSeen", { order: step.step.order, title: stepBlock.title }) });
|
||||
}
|
||||
if (step.completedAt) {
|
||||
items.push({ type: "step-completed", createdAt: step.completedAt, description: t("onboarding.session.activityEvents.stepCompleted", { order: step.step.order, title: stepBlock.title }) });
|
||||
}
|
||||
});
|
||||
|
||||
return items.sort((a, b) => {
|
||||
if (a.createdAt && b.createdAt) {
|
||||
return b.createdAt > a.createdAt ? 1 : -1;
|
||||
}
|
||||
return 1;
|
||||
});
|
||||
}
|
||||
|
||||
export default {
|
||||
getActivity,
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import { OnboardingStep } from "@toolctrl/db/prisma-browser";
|
||||
import { OnboardingStepBlockDto } from "../blocks/OnboardingBlockUtils";
|
||||
import { t as i18nT } from "i18next";
|
||||
|
||||
function parseStepToBlock(step: OnboardingStep) {
|
||||
try {
|
||||
return JSON.parse(step.block) as OnboardingStepBlockDto;
|
||||
} catch (e) {
|
||||
return {
|
||||
id: "",
|
||||
title: i18nT("shared.notSet"),
|
||||
links: [],
|
||||
gallery: [],
|
||||
input: [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function getStepDescription(block: OnboardingStepBlockDto) {
|
||||
return (
|
||||
<div className="flex items-center space-x-2 truncate text-sm">
|
||||
<div className="text-foreground shrink-0 font-medium">{block.title}</div>
|
||||
{block.description && (
|
||||
<>
|
||||
<div className="text-muted-foreground">•</div>
|
||||
<div className="text-muted-foreground shrink-0">{block.description}</div>
|
||||
</>
|
||||
)}
|
||||
{block.links.length > 0 && (
|
||||
<>
|
||||
<div className="text-muted-foreground">•</div>
|
||||
<div className="text-muted-foreground shrink-0">{i18nT("onboarding.stepSummary.linksCount", { count: block.links.length })}</div>
|
||||
</>
|
||||
)}
|
||||
{block.gallery.length > 0 && (
|
||||
<>
|
||||
<div className="text-muted-foreground">•</div>
|
||||
<div className="text-muted-foreground shrink-0">{i18nT("onboarding.stepSummary.galleryItemsCount", { count: block.gallery.length })}</div>
|
||||
</>
|
||||
)}
|
||||
{block.input.length > 0 && (
|
||||
<>
|
||||
<div className="text-muted-foreground">•</div>
|
||||
<div className="text-muted-foreground shrink-0">{i18nT("onboarding.stepSummary.inputFieldsCount", { count: block.input.length })}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default {
|
||||
parseStepToBlock,
|
||||
getStepDescription,
|
||||
};
|
||||
Reference in new issue
Block a user