Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 69 additions & 1 deletion apps/admin-x-framework/src/api/emails.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,79 @@
import { createMutation } from '../utils/api/hooks';
import { createMutation, createQueryWithId } from '../utils/api/hooks';
import { postsDataType } from './posts';
import type { Email } from './content-types';
import { z } from 'zod';

export interface EmailsResponseType {
emails: Email[];
}

export const EmailBatchStatusSchema = z.enum(['pending', 'submitting', 'submitted', 'failed']);

export const EmailBatchSchema = z.object({
id: z.string(),
status: EmailBatchStatusSchema,
});

export const EmailBatchesResponseSchema = z.object({
batches: z.array(EmailBatchSchema),
});

export const EmailSendingPhaseSchema = z.enum(['preparing', 'submitting']);

export const EmailSendingProgressSchema = z.object({
completed: z.number().int().nonnegative(),
total: z.number().int().nonnegative(),
estimated_seconds_remaining: z.number().int().nonnegative().nullable(),
});

export const EmailSendingStateSchema = z.discriminatedUnion('status', [
z.object({
status: EmailSendingPhaseSchema,
progress: EmailSendingProgressSchema,
}),
z.object({
status: z.literal('submitted'),
progress: EmailSendingProgressSchema,
}),
z.object({
status: z.literal('failed'),
progress: EmailSendingProgressSchema,
failed_during: EmailSendingPhaseSchema,
}),
]);

export const EmailSendingStatusSchema = z.object({
id: z.string(),
sending: EmailSendingStateSchema,
});

export const EmailStatusesResponseSchema = z.object({
email_statuses: z.array(EmailSendingStatusSchema),
});

export type EmailSendingPhase = z.infer<typeof EmailSendingPhaseSchema>;
export type EmailSendingProgress = z.infer<typeof EmailSendingProgressSchema>;
export type EmailSendingState = z.infer<typeof EmailSendingStateSchema>;
export type EmailSendingStatus = z.infer<typeof EmailSendingStatusSchema>;
export type EmailStatusesResponseType = z.infer<typeof EmailStatusesResponseSchema>;
export type EmailBatch = z.infer<typeof EmailBatchSchema>;
export type EmailBatchesResponseType = z.infer<typeof EmailBatchesResponseSchema>;

const emailStatusesDataType = 'EmailStatusesResponseType';
const emailBatchesDataType = 'EmailBatchesResponseType';

export const useBrowseEmailBatches = createQueryWithId<EmailBatchesResponseType>({
dataType: emailBatchesDataType,
path: (id) => `/emails/${id}/batches/`,
parseResponse: (data) => EmailBatchesResponseSchema.parse(data),
});

export const useEmailSendingStatus = createQueryWithId<EmailStatusesResponseType>({
Comment thread
kevinansfield marked this conversation as resolved.
dataType: emailStatusesDataType,
path: (id) => `/emails/${id}/status/`,
parseResponse: (data) => EmailStatusesResponseSchema.parse(data),
});

/**
* Retry a failed email send.
*
Expand Down
4 changes: 2 additions & 2 deletions apps/admin-x-framework/src/api/feedback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ export interface FeedbackResponseType {
feedback: FeedbackItem[];
}

const dataType = 'FeedbackResponseType';
export const feedbackDataType = 'FeedbackResponseType';

export const usePostFeedbackQuery = createQueryWithId<FeedbackResponseType>({
dataType,
dataType: feedbackDataType,
path: (id) => `/feedback/${id}/`,
});
4 changes: 3 additions & 1 deletion apps/admin-x-framework/src/api/links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ export type useBulkEditLinksParameters = {
editedUrl: string;
};

export const linksDataType = 'LinkResponseType';

export const useTopLinks = createQuery<LinkResponseType>({
dataType: 'LinkResponseType',
dataType: linksDataType,
path: '/links/',
});

Expand Down
4 changes: 2 additions & 2 deletions apps/admin-x-framework/src/api/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,8 @@ const memberCountHistoryDataType = 'MemberCountHistoryResponseType';
const topPostsStatsDataType = 'TopPostsStatsResponseType';
const postReferrersDataType = 'PostReferrersResponseType';
const newsletterStatsDataType = 'NewsletterStatsResponseType';
const newsletterBasicStatsDataType = 'NewsletterBasicStatsResponseType';
const newsletterClickStatsDataType = 'NewsletterClickStatsResponseType';
export const newsletterBasicStatsDataType = 'NewsletterBasicStatsResponseType';
export const newsletterClickStatsDataType = 'NewsletterClickStatsResponseType';
const newsletterSubscriberStatsDataType = 'NewsletterSubscriberStatsResponseType';

const postGrowthStatsDataType = 'PostGrowthStatsResponseType';
Expand Down
120 changes: 118 additions & 2 deletions apps/admin-x-framework/test/unit/api/emails.test.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,127 @@
import { act } from '@testing-library/react';
import { act, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { createTestQueryClient, renderHookWithProviders } from '../../../src/test/test-utils';
import { useRetryEmail } from '../../../src/api/emails';
import {
useBrowseEmailBatches,
useEmailSendingStatus,
useRetryEmail,
} from '../../../src/api/emails';
import { postsDataType } from '../../../src/api/posts';
import { withMockFetch } from '../../utils/mock-fetch';

describe('emails api', () => {
it('reads filtered email batches via the batches endpoint', async () => {
await withMockFetch(
{
json: { batches: [{ id: 'batch-1', status: 'submitting' }] },
headers: { 'content-type': 'application/json' },
},
async (mock) => {
const { result } = renderHookWithProviders(() =>
useBrowseEmailBatches('email-1', {
searchParams: { filter: 'status:submitting', fields: 'id,status', limit: '1' },
}),
);

await waitFor(() => expect(result.current.isSuccess).toBe(true));

const batchRequest = (mock.calls as Array<Parameters<typeof globalThis.fetch>>).find(
([url]) => String(url).includes('/emails/email-1/batches/'),
);
expect(batchRequest).toBeDefined();
const [url, options] = batchRequest!;
const requestUrl = new URL(url as string);
expect(requestUrl.pathname).toBe('/ghost/api/admin/emails/email-1/batches/');
expect(requestUrl.searchParams.get('filter')).toBe('status:submitting');
expect(requestUrl.searchParams.get('fields')).toBe('id,status');
expect(requestUrl.searchParams.get('limit')).toBe('1');
expect(options?.method).toBe('GET');
expect(result.current.data?.batches).toEqual([{ id: 'batch-1', status: 'submitting' }]);
},
);
});

it('rejects malformed email batch responses', async () => {
await withMockFetch(
{
json: { batches: [{ id: 'batch-1', status: 'unknown' }] },
headers: { 'content-type': 'application/json' },
},
async () => {
const { result } = renderHookWithProviders(() =>
useBrowseEmailBatches('email-1', { defaultErrorHandler: false }),
);

await waitFor(() => expect(result.current.isError).toBe(true));

expect(result.current.data).toBeUndefined();
},
);
});

it('reads an email sending status via the status endpoint', async () => {
await withMockFetch(
{
json: {
users: [{ id: 'user-1', roles: [] }],
email_statuses: [
{
id: 'email-1',
sending: {
status: 'submitting',
progress: {
completed: 500,
total: 1000,
estimated_seconds_remaining: 30,
},
},
},
],
},
headers: { 'content-type': 'application/json' },
},
async (mock) => {
const { result } = renderHookWithProviders(() => useEmailSendingStatus('email-1'));

await waitFor(() => expect(result.current.isSuccess).toBe(true));

const statusRequest = (mock.calls as Array<Parameters<typeof globalThis.fetch>>).find(
([url]) => String(url).includes('/emails/email-1/status/'),
);
expect(statusRequest).toBeDefined();
const [url, options] = statusRequest!;
expect(new URL(url as string).pathname).toBe('/ghost/api/admin/emails/email-1/status/');
expect(options?.method).toBe('GET');
expect(result.current.data?.email_statuses[0]?.sending).toEqual({
status: 'submitting',
progress: {
completed: 500,
total: 1000,
estimated_seconds_remaining: 30,
},
});
},
);
});

it('rejects malformed email sending status responses', async () => {
await withMockFetch(
{
json: {},
headers: { 'content-type': 'application/json' },
},
async () => {
const { result } = renderHookWithProviders(() =>
useEmailSendingStatus('email-1', { defaultErrorHandler: false }),
);

await waitFor(() => expect(result.current.isError).toBe(true));

expect(result.current.data).toBeUndefined();
},
);
});

it('retries a failed email via the retry endpoint', async () => {
await withMockFetch(
{
Expand Down
11 changes: 11 additions & 0 deletions apps/admin/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@

@custom-variant admin7 (&:where(.admin7, .admin7 *));

@keyframes email-sending-arrow-rise {
from {
transform: translateY(115%);
}

to {
transform: translateY(-115%);
}
}

/* The shell owns rollout eligibility. Admin overlays mount beside #root, so
mirror typography into Shade portals and the three legacy overlay hosts.
Do not set body fonts or change component weights, sizes, or line heights. */
Expand Down Expand Up @@ -93,6 +103,7 @@
must be generated in this Tailwind lane; the font files themselves load with
settings/custom-fonts.css in the settings chunk. */
@theme {
--animate-email-sending-arrow-rise: email-sending-arrow-rise 1200ms linear infinite;
--font-cardo: Cardo;
--font-manrope: Manrope;
--font-merriweather: Merriweather;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import GiftLinkModal from '@/posts/analytics/modals/gift-link-modal';
import PostShareModal from '@/shared/analytics/post-share-modal';
import EmailSendingStatusBanner from '@/posts/analytics/email-sending-status/email-sending-status-banner';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
AlertDialog,
Expand Down Expand Up @@ -40,9 +41,7 @@ import { usePostAnalytics } from '@/posts/analytics/providers/post-analytics-con
import { getSiteTimezone } from '@tryghost/admin-x-framework/utils/get-site-timezone';
import { giftAccessLabel } from '@/posts/analytics/utils/gift-link';
import {
hasBeenEmailed,
isEmailOnly,
isPublishedAndEmailed,
isPublishedOnly,
trackEvent,
useActiveVisitors,
Expand All @@ -55,6 +54,7 @@ import {
import { useCanManageGiftLink } from '@/posts/analytics/hooks/use-can-manage-gift-link';
import { useDeletePost } from '@tryghost/admin-x-framework/api/posts';
import { useHandleError } from '@tryghost/admin-x-framework/hooks';
import { useEmailSendingStatusContext } from '@/posts/analytics/email-sending-status/email-sending-status-context';

interface PostAnalyticsHeaderProps {
currentTab?: string;
Expand All @@ -72,12 +72,17 @@ const PostAnalyticsHeader: React.FC<PostAnalyticsHeaderProps> = ({ currentTab, c
const [isGiftLinkOpen, setIsGiftLinkOpen] = useState(false);
const { settings, site, statsConfig } = useAnalyticsData();
const { post, isPostLoading, postId } = usePostAnalytics();
const { hasNewsletterAnalytics, status: emailSendingStatus } = useEmailSendingStatusContext();
const canManageGiftLink = useCanManageGiftLink(post);
const editorPath = `/editor/post/${postId}`;
// Whether the editor needs a hash navigation depends on the `editorReact` flag.
const editorIsEmberOwned = useIsEmberOwnedRoute(editorPath);

const siteTimezone = getSiteTimezone(settings);
const isPublishedPost = post?.status === 'published';
const hasFailedEmail = emailSendingStatus?.sending.status === 'failed';
const showPublishedOnSite = isPublishedPost && (!hasNewsletterAnalytics || hasFailedEmail);
const showPublishedAndSent = isPublishedPost && hasNewsletterAnalytics && !hasFailedEmail;

// Track once per open — canManageGiftLink can flip while the modal is open
// (current-user query resolving), which must not re-fire the event.
Expand Down Expand Up @@ -119,7 +124,7 @@ const PostAnalyticsHeader: React.FC<PostAnalyticsHeaderProps> = ({ currentTab, c
tabs.push('Web');
}
}
if (hasBeenEmailed(post)) {
if (hasNewsletterAnalytics) {
tabs.push('Newsletter');
}
// Only show Growth tab if member source tracking is enabled
Expand All @@ -128,7 +133,7 @@ const PostAnalyticsHeader: React.FC<PostAnalyticsHeaderProps> = ({ currentTab, c
}

return tabs;
}, [post, webAnalyticsEnabled, membersTrackSources]);
}, [post, webAnalyticsEnabled, membersTrackSources, hasNewsletterAnalytics]);

const handleDeletePost = () => {
if (!post) {
Expand Down Expand Up @@ -287,15 +292,16 @@ const PostAnalyticsHeader: React.FC<PostAnalyticsHeaderProps> = ({ currentTab, c
<div className="mt-0.5 flex items-center justify-start leading-[1.65em] text-muted-foreground">
{isEmailOnly(post) &&
`Sent on ${formatDisplayDate(post.published_at, siteTimezone)} at ${formatDisplayTime(post.published_at, siteTimezone)}`}
{isPublishedOnly(post) &&
{showPublishedOnSite &&
`Published on your site on ${formatDisplayDate(post.published_at, siteTimezone)} at ${formatDisplayTime(post.published_at, siteTimezone)}`}
{isPublishedAndEmailed(post) &&
{showPublishedAndSent &&
`Published and sent on ${formatDisplayDate(post.published_at, siteTimezone)} at ${formatDisplayTime(post.published_at, siteTimezone)}`}
</div>
)}
</div>
</div>
)}
<EmailSendingStatusBanner />
</div>
</div>
</header>
Expand Down
Loading
Loading