feat: Nudge users to become template creators if eligible (#8357)

This commit is contained in:
Tomi Turtiainen 2024-01-17 19:07:34 +02:00 committed by GitHub
parent 3912c5e7ab
commit 99457019f7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 385 additions and 3 deletions

View file

@ -0,0 +1,18 @@
//#region Getters
export const getBecomeTemplateCreatorCta = () => cy.getByTestId('become-template-creator-cta');
export const getCloseBecomeTemplateCreatorCtaButton = () =>
cy.getByTestId('close-become-template-creator-cta');
//#endregion
//#region Actions
export const interceptCtaRequestWithResponse = (becomeCreator: boolean) => {
return cy.intercept('GET', `/rest/cta/become-creator`, {
body: becomeCreator,
});
};
//#endregion

View file

@ -0,0 +1,32 @@
import {
getBecomeTemplateCreatorCta,
getCloseBecomeTemplateCreatorCtaButton,
interceptCtaRequestWithResponse,
} from '../composables/becomeTemplateCreatorCta';
import { WorkflowsPage as WorkflowsPageClass } from '../pages/workflows';
const WorkflowsPage = new WorkflowsPageClass();
describe('Become creator CTA', () => {
it('should not show the CTA if user is not eligible', () => {
interceptCtaRequestWithResponse(false).as('cta');
cy.visit(WorkflowsPage.url);
cy.wait('@cta');
getBecomeTemplateCreatorCta().should('not.exist');
});
it('should show the CTA if the user is eligible', () => {
interceptCtaRequestWithResponse(true).as('cta');
cy.visit(WorkflowsPage.url);
cy.wait('@cta');
getBecomeTemplateCreatorCta().should('be.visible');
getCloseBecomeTemplateCreatorCtaButton().click();
getBecomeTemplateCreatorCta().should('not.exist');
});
});

View file

@ -280,6 +280,11 @@ export class Server extends AbstractServer {
controllers.push(MFAController);
}
if (!config.getEnv('endpoints.disableUi')) {
const { CtaController } = await import('@/controllers/cta.controller');
controllers.push(CtaController);
}
controllers.forEach((controller) => registerController(app, controller));
}

View file

@ -0,0 +1,21 @@
import express from 'express';
import { Authorized, Get, RestController } from '@/decorators';
import { AuthenticatedRequest } from '@/requests';
import { CtaService } from '@/services/cta.service';
/**
* Controller for Call to Action (CTA) endpoints. CTAs are certain
* messages that are shown to users in the UI.
*/
@Authorized()
@RestController('/cta')
export class CtaController {
constructor(private readonly ctaService: CtaService) {}
@Get('/become-creator')
async getCta(req: AuthenticatedRequest, res: express.Response) {
const becomeCreator = await this.ctaService.getBecomeCreatorCta(req.user.id);
res.json(becomeCreator);
}
}

View file

@ -1,8 +1,11 @@
import { Service } from 'typedi';
import { DataSource, QueryFailedError, Repository } from 'typeorm';
import config from '@/config';
import type { StatisticsNames } from '../entities/WorkflowStatistics';
import { WorkflowStatistics } from '../entities/WorkflowStatistics';
import { StatisticsNames, WorkflowStatistics } from '../entities/WorkflowStatistics';
import type { User } from '@/databases/entities/User';
import { WorkflowEntity } from '@/databases/entities/WorkflowEntity';
import { SharedWorkflow } from '@/databases/entities/SharedWorkflow';
import { Role } from '@/databases/entities/Role';
type StatisticsInsertResult = 'insert' | 'failed' | 'alreadyExists';
type StatisticsUpsertResult = StatisticsInsertResult | 'update';
@ -98,4 +101,21 @@ export class WorkflowStatisticsRepository extends Repository<WorkflowStatistics>
throw error;
}
}
async queryNumWorkflowsUserHasWithFiveOrMoreProdExecs(userId: User['id']): Promise<number> {
return await this.createQueryBuilder('workflow_statistics')
.innerJoin(WorkflowEntity, 'workflow', 'workflow.id = workflow_statistics.workflowId')
.innerJoin(
SharedWorkflow,
'shared_workflow',
'shared_workflow.workflowId = workflow_statistics.workflowId',
)
.innerJoin(Role, 'role', 'role.id = shared_workflow.roleId')
.where('shared_workflow.userId = :userId', { userId })
.andWhere('workflow.active = :isActive', { isActive: true })
.andWhere('workflow_statistics.name = :name', { name: StatisticsNames.productionSuccess })
.andWhere('workflow_statistics.count >= 5')
.andWhere('role.name = :roleName', { roleName: 'owner' })
.getCount();
}
}

View file

@ -0,0 +1,18 @@
import { Service } from 'typedi';
import { WorkflowStatisticsRepository } from '@/databases/repositories/workflowStatistics.repository';
import type { User } from '@/databases/entities/User';
@Service()
export class CtaService {
constructor(private readonly workflowStatisticsRepository: WorkflowStatisticsRepository) {}
async getBecomeCreatorCta(userId: User['id']) {
// There need to be at least 3 workflows with at least 5 executions
const numWfsWithOver5ProdExecutions =
await this.workflowStatisticsRepository.queryNumWorkflowsUserHasWithFiveOrMoreProdExecs(
userId,
);
return numWfsWithOver5ProdExecutions >= 3;
}
}

View file

@ -0,0 +1,54 @@
import Container from 'typedi';
import * as testDb from './shared/testDb';
import { CtaService } from '@/services/cta.service';
import { createUser } from './shared/db/users';
import { createManyWorkflows } from './shared/db/workflows';
import type { User } from '@/databases/entities/User';
import { createWorkflowStatisticsItem } from './shared/db/workflowStatistics';
import { StatisticsNames } from '@/databases/entities/WorkflowStatistics';
describe('CtaService', () => {
let ctaService: CtaService;
let user: User;
beforeAll(async () => {
await testDb.init();
ctaService = Container.get(CtaService);
user = await createUser();
});
afterAll(async () => {
await testDb.terminate();
});
describe('getBecomeCreatorCta()', () => {
afterEach(async () => {
await testDb.truncate(['Workflow', 'SharedWorkflow']);
});
test.each([
[false, 0, 0],
[false, 2, 5],
[false, 3, 4],
[true, 3, 5],
])(
'should return %p if user has %d active workflows with %d successful production executions',
async (expected, numWorkflows, numExecutions) => {
const workflows = await createManyWorkflows(numWorkflows, { active: true }, user);
await Promise.all(
workflows.map(
async (workflow) =>
await createWorkflowStatisticsItem(workflow.id, {
count: numExecutions,
name: StatisticsNames.productionSuccess,
}),
),
);
expect(await ctaService.getBecomeCreatorCta(user.id)).toBe(expected);
},
);
});
});

View file

@ -0,0 +1,21 @@
import Container from 'typedi';
import { StatisticsNames, type WorkflowStatistics } from '@/databases/entities/WorkflowStatistics';
import type { Workflow } from 'n8n-workflow';
import { WorkflowStatisticsRepository } from '@/databases/repositories/workflowStatistics.repository';
export async function createWorkflowStatisticsItem(
workflowId: Workflow['id'],
data?: Partial<WorkflowStatistics>,
) {
const entity = Container.get(WorkflowStatisticsRepository).create({
count: 0,
latestEvent: new Date().toISOString(),
name: StatisticsNames.manualSuccess,
...(data ?? {}),
workflowId,
});
await Container.get(WorkflowStatisticsRepository).insert(entity);
return entity;
}

View file

@ -0,0 +1,8 @@
import type { IRestApiContext } from '@/Interface';
import { get } from '@/utils/apiUtils';
export async function getBecomeCreatorCta(context: IRestApiContext): Promise<boolean> {
const response = await get(context.baseUrl, '/cta/become-creator');
return response;
}

View file

@ -0,0 +1,78 @@
<script setup lang="ts">
import { useBecomeTemplateCreatorStore } from './becomeTemplateCreatorStore';
import { useI18n } from '@/composables/useI18n';
const i18n = useI18n();
const store = useBecomeTemplateCreatorStore();
</script>
<template>
<div
v-if="store.showBecomeCreatorCta"
:class="$style.container"
data-test-id="become-template-creator-cta"
>
<div :class="$style.textAndCloseButton">
<p :class="$style.text">
{{ i18n.baseText('becomeCreator.text') }}
</p>
<button
:class="$style.closeButton"
data-test-id="close-become-template-creator-cta"
@click="store.dismissCta()"
>
<n8n-icon icon="times" size="xsmall" :title="i18n.baseText('generic.close')" />
</button>
</div>
<n8n-button
:class="$style.becomeCreatorButton"
:label="i18n.baseText('becomeCreator.buttonText')"
size="xmini"
type="secondary"
element="a"
href="https://creators.n8n.io/hub"
target="_blank"
/>
</div>
</template>
<style module lang="scss">
.container {
display: flex;
flex-direction: column;
background-color: var(--color-background-light);
border: var(--border-base);
border-right: 0;
}
.textAndCloseButton {
display: flex;
margin-top: var(--spacing-xs);
margin-left: var(--spacing-s);
margin-right: var(--spacing-2xs);
}
.text {
flex: 1;
font-size: var(--font-size-3xs);
line-height: var(--font-line-height-compact);
}
.closeButton {
flex: 0;
display: flex;
align-items: center;
justify-content: center;
width: var(--spacing-2xs);
height: var(--spacing-2xs);
border: none;
color: var(--color-text-light);
background-color: transparent;
}
.becomeCreatorButton {
margin: var(--spacing-s);
}
</style>

View file

@ -0,0 +1,94 @@
import { DateTime } from 'luxon';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { STORES } from '@/constants';
import { useCloudPlanStore } from '@/stores/cloudPlan.store';
import { useStorage } from '@/composables/useStorage';
import { useRootStore } from '@/stores/n8nRoot.store';
import { getBecomeCreatorCta } from '@/api/ctas';
const LOCAL_STORAGE_KEY = 'N8N_BECOME_TEMPLATE_CREATOR_CTA_DISMISSED_AT';
const RESHOW_DISMISSED_AFTER_DAYS = 30;
const POLL_INTERVAL_IN_MS = 15 * 60 * 1000; // 15 minutes
export const useBecomeTemplateCreatorStore = defineStore(STORES.BECOME_TEMPLATE_CREATOR, () => {
const cloudPlanStore = useCloudPlanStore();
const rootStore = useRootStore();
//#region State
const dismissedAt = useStorage(LOCAL_STORAGE_KEY);
const ctaMeetsCriteria = ref(false);
const monitorCtasTimer = ref<ReturnType<typeof setInterval> | null>(null);
//#endregion State
//#region Computed
const isDismissed = computed(() => {
return dismissedAt.value ? !hasEnoughTimePassedSinceDismissal(dismissedAt.value) : false;
});
const showBecomeCreatorCta = computed(() => {
return ctaMeetsCriteria.value && !cloudPlanStore.userIsTrialing && !isDismissed.value;
});
//#endregion Computed
//#region Actions
const dismissCta = () => {
dismissedAt.value = DateTime.now().toISO();
};
const fetchBecomeCreatorCta = async () => {
const becomeCreatorCta = await getBecomeCreatorCta(rootStore.getRestApiContext);
ctaMeetsCriteria.value = becomeCreatorCta;
};
const fetchUserCtasIfNeeded = async () => {
if (isDismissed.value || cloudPlanStore.userIsTrialing || ctaMeetsCriteria.value) {
return;
}
await fetchBecomeCreatorCta();
};
const startMonitoringCta = () => {
if (monitorCtasTimer.value) {
return;
}
// Initial check after 1s so we don't bombard the API immediately during startup
setTimeout(fetchUserCtasIfNeeded, 1000);
monitorCtasTimer.value = setInterval(fetchUserCtasIfNeeded, POLL_INTERVAL_IN_MS);
};
const stopMonitoringCta = () => {
if (!monitorCtasTimer.value) {
return;
}
clearInterval(monitorCtasTimer.value);
monitorCtasTimer.value = null;
};
//#endregion Actions
return {
showBecomeCreatorCta,
dismissCta,
startMonitoringCta,
stopMonitoringCta,
};
});
function hasEnoughTimePassedSinceDismissal(dismissedAt: string) {
const reshowAtTime = DateTime.fromISO(dismissedAt).plus({
days: RESHOW_DISMISSED_AFTER_DAYS,
});
return reshowAtTime <= DateTime.now();
}

View file

@ -23,6 +23,7 @@
</template>
<template #beforeLowerMenu>
<BecomeTemplateCreatorCta v-if="fullyExpanded && !userIsTrialing" />
<ExecutionsUsage
v-if="fullyExpanded && userIsTrialing"
:cloud-plan-data="currentPlanAndUsageData"
@ -119,10 +120,12 @@ import { useVersionsStore } from '@/stores/versions.store';
import { useWorkflowsStore } from '@/stores/workflows.store';
import { isNavigationFailure } from 'vue-router';
import ExecutionsUsage from '@/components/ExecutionsUsage.vue';
import BecomeTemplateCreatorCta from '@/components/BecomeTemplateCreatorCta/BecomeTemplateCreatorCta.vue';
import MainSidebarSourceControl from '@/components/MainSidebarSourceControl.vue';
import { hasPermission } from '@/rbac/permissions';
import { useExternalHooks } from '@/composables/useExternalHooks';
import { useDebounce } from '@/composables/useDebounce';
import { useBecomeTemplateCreatorStore } from '@/components/BecomeTemplateCreatorCta/becomeTemplateCreatorStore';
export default defineComponent({
name: 'MainSidebar',
@ -130,6 +133,7 @@ export default defineComponent({
GiftNotificationIcon,
ExecutionsUsage,
MainSidebarSourceControl,
BecomeTemplateCreatorCta,
},
mixins: [userHelpers],
setup(props, ctx) {
@ -158,6 +162,7 @@ export default defineComponent({
useWorkflowsStore,
useCloudPlanStore,
useSourceControlStore,
useBecomeTemplateCreatorStore,
),
logoPath(): string {
if (this.isCollapsed) return this.basePath + 'n8n-logo-collapsed.svg';
@ -368,11 +373,14 @@ export default defineComponent({
this.fullyExpanded = !this.isCollapsed;
});
this.becomeTemplateCreatorStore.startMonitoringCta();
},
created() {
window.addEventListener('resize', this.onResize);
},
beforeUnmount() {
this.becomeTemplateCreatorStore.stopMonitoringCta();
window.removeEventListener('resize', this.onResize);
},
methods: {

View file

@ -603,6 +603,7 @@ export const enum STORES {
RBAC = 'rbac',
COLLABORATION = 'collaboration',
PUSH = 'push',
BECOME_TEMPLATE_CREATOR = 'becomeTemplateCreator',
}
export const enum SignInType {

View file

@ -30,6 +30,7 @@
},
"generic.any": "Any",
"generic.cancel": "Cancel",
"generic.close": "Close",
"generic.confirm": "Confirm",
"generic.deleteWorkflowError": "Problem deleting workflow",
"generic.filtersApplied": "Filters are currently applied.",
@ -2371,5 +2372,8 @@
"templateSetup.continue.button": "Continue",
"templateSetup.credential.description": "The credential you select will be used in the {0} node of the workflow template. | The credential you select will be used in the {0} nodes of the workflow template.",
"templateSetup.continue.button.fillRemaining": "Fill remaining credentials to continue",
"setupCredentialsModal.title": "Set up template"
"setupCredentialsModal.title": "Set up template",
"becomeCreator.text": "Share your workflows with 40k+ users, unlock perks, and shine as a featured template creator!",
"becomeCreator.buttonText": "Become a creator",
"becomeCreator.closeButtonTitle": "Close"
}