Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
Serve Insights thumbnails from our CDN and tidy post type tags (#422)
Paulo Castellanofcfb93927b87
diff --git a/app/Actions/Analytics/BuildPublicationAnalyticsReport.php b/app/Actions/Analytics/BuildPublicationAnalyticsReport.phpindex b882eb5e7..fcb2daf6e 100644--- a/app/Actions/Analytics/BuildPublicationAnalyticsReport.php+++ b/app/Actions/Analytics/BuildPublicationAnalyticsReport.php@@ -15,6 +15,7 @@ use App\Support\Analytics\MetricComparison;use App\Support\Analytics\PeriodBuckets;use Carbon\CarbonImmutable;use Illuminate\Database\Query\Builder;+use Illuminate\Support\Collection;use Illuminate\Support\LazyCollection;class BuildPublicationAnalyticsReport@@ -108,6 +109,8 @@ class BuildPublicationAnalyticsReport}unset($bucket);+ $postMedia = $this->postMedia([...$topReactions, ...$topComments]);+return ['current_totals' => $this->finalizeTotals($currentTotals),'previous_totals' => $this->finalizeTotals($previousTotals),@@ -117,8 +120,8 @@ class BuildPublicationAnalyticsReport'buckets' => $buckets,],'top_posts' => [- 'reactions' => $this->top($topReactions),- 'comments' => $this->top($topComments),+ 'reactions' => $this->top($topReactions, $postMedia),+ 'comments' => $this->top($topComments, $postMedia),],'performance' => $this->performance($currentAccounts, $previousAccounts),];@@ -290,29 +293,47 @@ class BuildPublicationAnalyticsReport}}- /** @return list<array<string, mixed>> */- private function top(array $rows): array+ /**+ * The first image or video of each ranked post, keyed by post id.+ *+ * @param list<object> $rows+ * @return Collection<string, array<string, mixed>>+ */+ private function postMedia(array $rows): Collection{- return array_map(function (object $row): array {- return [- 'id' => $row->id,- 'post_id' => $row->post_id,- 'social_account_key' => $row->social_account_key,- 'platform' => $row->platform,- 'name' => $row->account_display_name,- 'username' => $row->account_username,- 'avatar_url' => $row->account_avatar_url,- 'origin' => $row->origin,- 'content_type' => $row->content_type,- 'availability' => $row->availability,- 'published_at' => $row->provider_published_at,- 'permalink' => $row->permalink,- 'excerpt' => $row->excerpt,- 'preview_metadata' => $row->preview_metadata ? json_decode((string) $row->preview_metadata, true) : null,- 'reactions' => $row->reactions_count === null ? null : (int) $row->reactions_count,- 'comments' => $row->comments_count === null ? null : (int) $row->comments_count,- ];- }, $rows);+ return Post::query()+ ->whereKey(collect($rows)->pluck('post_id')->filter())+ ->get(['id', 'media'])+ ->mapWithKeys(fn (Post $post): array => [$post->id => $post->coverMedia()?->toArray()])+ ->filter();+ }++ /**+ * @param list<object> $rows+ * @param Collection<string, array<string, mixed>> $postMedia+ * @return list<array<string, mixed>>+ */+ private function top(array $rows, Collection $postMedia): array+ {+ return collect($rows)->map(fn (object $row): array => [+ 'id' => $row->id,+ 'post_id' => $row->post_id,+ 'social_account_key' => $row->social_account_key,+ 'platform' => $row->platform,+ 'name' => $row->account_display_name,+ 'username' => $row->account_username,+ 'avatar_url' => $row->account_avatar_url,+ 'origin' => $row->origin,+ 'content_type' => $row->content_type,+ 'availability' => $row->availability,+ 'published_at' => $row->provider_published_at,+ 'permalink' => $row->permalink,+ 'excerpt' => $row->excerpt,+ 'preview_metadata' => $row->preview_metadata ? json_decode((string) $row->preview_metadata, true) : null,+ 'media' => $postMedia->get((string) $row->post_id),+ 'reactions' => $row->reactions_count === null ? null : (int) $row->reactions_count,+ 'comments' => $row->comments_count === null ? null : (int) $row->comments_count,+ ])->all();}/** @return list<array<string, mixed>> */diff --git a/app/Actions/Analytics/ListChannelPublicationPerformance.php b/app/Actions/Analytics/ListChannelPublicationPerformance.phpindex 9ff321b1c..dcd165390 100644--- a/app/Actions/Analytics/ListChannelPublicationPerformance.php+++ b/app/Actions/Analytics/ListChannelPublicationPerformance.php@@ -54,7 +54,7 @@ class ListChannelPublicationPerformance->when($filter !== null, fn (Builder $filtered): Builder => $filter->apply($filtered))->select(['publication.id', 'publication.post_id', 'publication.excerpt', 'publication.preview_metadata', 'publication.permalink',- 'publication.provider_published_at', 'publication.content_type',+ 'publication.provider_published_at', 'publication.content_type', 'destination.media as post_media','metric.reactions_count', 'metric.comments_count', 'metric.views_count', 'metric.shares_count','metric.saves_count', 'metric.reach_count', 'metric.engagement_count', 'metric.exposure_count','metric.impressions_count', 'metric.watch_time_milliseconds', 'metric.average_watch_time_milliseconds', 'metric.metrics',@@ -79,17 +79,19 @@ class ListChannelPublicationPerformance}/**- * @return array{id: string, rank: int, excerpt: ?string, thumbnail_url: ?string, permalink: ?string, published_at: string, content_type: ?string, metrics: array{reactions: ?int, comments: ?int, engagement_rate: ?float, views: ?int, impressions: ?int, shares: ?int, reposts: ?int, quotes: ?int, saves: ?int, clicks: ?int, follows_gained: ?int, reach: ?int, watch_time_minutes: ?float, average_watch_time_seconds: ?float}, post_id: ?string}+ * @return array{id: string, rank: int, excerpt: ?string, thumbnail_url: ?string, media: ?array<string, mixed>, permalink: ?string, published_at: string, content_type: ?string, metrics: array{reactions: ?int, comments: ?int, engagement_rate: ?float, views: ?int, impressions: ?int, shares: ?int, reposts: ?int, quotes: ?int, saves: ?int, clicks: ?int, follows_gained: ?int, reach: ?int, watch_time_minutes: ?float, average_watch_time_seconds: ?float}, post_id: ?string}*/private function row(object $row, int $rank): array{$measured = $row->metrics === null ? [] : (array) json_decode((string) $row->metrics, true);+ $media = (new Post)->newFromBuilder(['media' => $row->post_media])->coverMedia();return ['id' => $row->id,'rank' => $rank,'excerpt' => $row->excerpt,- 'thumbnail_url' => $this->thumbnail($row->preview_metadata),+ 'thumbnail_url' => $media?->isImage() ? $media->url : $this->thumbnail($row->preview_metadata),+ 'media' => $media?->toArray(),'permalink' => $row->permalink,'published_at' => CarbonImmutable::parse($row->provider_published_at, 'UTC')->toIso8601String(),'content_type' => $row->content_type,diff --git a/app/Actions/Analytics/UpsertAnalyticsPublication.php b/app/Actions/Analytics/UpsertAnalyticsPublication.phpindex f9a6ec6a8..06e30ea37 100644--- a/app/Actions/Analytics/UpsertAnalyticsPublication.php+++ b/app/Actions/Analytics/UpsertAnalyticsPublication.php@@ -48,6 +48,7 @@ class UpsertAnalyticsPublicationproviderMetadata: $publication->providerMetadata,providerSyncedAt: now(),liveAccount: $account,+ contentTypeReported: $publication->contentTypeReported,);}@@ -179,6 +180,7 @@ class UpsertAnalyticsPublication?string $postId = null,?DateTimeInterface $providerSyncedAt = null,?SocialAccount $liveAccount = null,+ bool $contentTypeReported = true,): AnalyticsPublication {$excerpt = $excerpt === null ? null : mb_strcut($excerpt, 0, self::EXCERPT_MAX_BYTES, 'UTF-8');@@ -198,6 +200,7 @@ class UpsertAnalyticsPublication$providerSyncedAt,$liveAccount,true,+ $contentTypeReported,);} catch (UniqueConstraintViolationException) {return $this->write(@@ -215,6 +218,7 @@ class UpsertAnalyticsPublication$providerSyncedAt,$liveAccount,false,+ $contentTypeReported,);}}@@ -238,8 +242,9 @@ class UpsertAnalyticsPublication?DateTimeInterface $providerSyncedAt,?SocialAccount $liveAccount,bool $mayCreate,+ bool $contentTypeReported,): AnalyticsPublication {- return DB::transaction(function () use ($contentType, $excerpt, $identity, $liveAccount, $mayCreate, $origin, $permalink, $postId, $previewMetadata, $providerContentType, $providerMetadata, $providerPostId, $providerPublishedAt, $providerSyncedAt): AnalyticsPublication {+ return DB::transaction(function () use ($contentType, $contentTypeReported, $excerpt, $identity, $liveAccount, $mayCreate, $origin, $permalink, $postId, $previewMetadata, $providerContentType, $providerMetadata, $providerPostId, $providerPublishedAt, $providerSyncedAt): AnalyticsPublication {$identityFields = ['workspace_id' => $identity->workspaceId,'social_account_key' => $identity->socialAccountKey,@@ -281,7 +286,7 @@ class UpsertAnalyticsPublication'origin' => $origin === PublicationOrigin::TryPost? PublicationOrigin::TryPost: ($publication->origin ?? PublicationOrigin::External),- 'content_type' => $contentType,+ 'content_type' => $contentTypeReported || ! $publication->exists ? $contentType : $publication->content_type,'availability' => PublicationAvailability::Available,'last_seen_at' => $now,'provider_synced_at' => $providerSyncedAt ?? $publication->provider_synced_at,diff --git a/app/Dto/Analytics/DiscoveredPublication.php b/app/Dto/Analytics/DiscoveredPublication.phpindex 88ccdb701..85d7335d6 100644--- a/app/Dto/Analytics/DiscoveredPublication.php+++ b/app/Dto/Analytics/DiscoveredPublication.php@@ -10,6 +10,7 @@ use Carbon\CarbonImmutable;final readonly class DiscoveredPublication{/**+ * @param bool $contentTypeReported False when the network does not report the type, so $contentType only fills a new publication.* @param array<string, mixed>|null $previewMetadata* @param array<string, mixed>|null $providerMetadata*/@@ -22,5 +23,6 @@ final readonly class DiscoveredPublicationpublic ?string $excerpt = null,public ?array $previewMetadata = null,public ?array $providerMetadata = null,+ public bool $contentTypeReported = true,) {}}diff --git a/app/Http/Resources/Api/ChannelPublicationPerformanceResource.php b/app/Http/Resources/Api/ChannelPublicationPerformanceResource.phpindex fc3f1ae69..f79e62b69 100644--- a/app/Http/Resources/Api/ChannelPublicationPerformanceResource.php+++ b/app/Http/Resources/Api/ChannelPublicationPerformanceResource.php@@ -10,7 +10,7 @@ use Illuminate\Http\Resources\Json\JsonResource;class ChannelPublicationPerformanceResource extends JsonResource{/**- * @return array{id: string, rank: int, post_id: ?string, excerpt: ?string, thumbnail_url: ?string, permalink: ?string, published_at: string, content_type: ?string, metrics: array<string, int|float|null>}+ * @return array{id: string, rank: int, post_id: ?string, excerpt: ?string, thumbnail_url: ?string, media: ?array<string, mixed>, permalink: ?string, published_at: string, content_type: ?string, metrics: array<string, int|float|null>}*/public function toArray(Request $request): array{@@ -20,6 +20,7 @@ class ChannelPublicationPerformanceResource extends JsonResource'post_id' => data_get($this->resource, 'post_id'),'excerpt' => data_get($this->resource, 'excerpt'),'thumbnail_url' => data_get($this->resource, 'thumbnail_url'),+ 'media' => data_get($this->resource, 'media'),'permalink' => data_get($this->resource, 'permalink'),'published_at' => data_get($this->resource, 'published_at'),'content_type' => data_get($this->resource, 'content_type'),diff --git a/app/Models/Post.php b/app/Models/Post.phpindex bee8c9e20..6b71c8674 100644--- a/app/Models/Post.php+++ b/app/Models/Post.php@@ -148,6 +148,14 @@ class Post extends Model);}+ /**+ * The first image or video of the post, the one shown as its thumbnail.+ */+ public function coverMedia(): ?MediaItem+ {+ return $this->media_items->first(fn (MediaItem $item): bool => $item->isImage() || $item->isVideo());+ }+public function workspace(): BelongsTo{return $this->belongsTo(Workspace::class);diff --git a/app/Services/Analytics/Collectors/Publications/TikTokPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/TikTokPublicationCollector.phpindex 405706378..126f2e04b 100644--- a/app/Services/Analytics/Collectors/Publications/TikTokPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/TikTokPublicationCollector.php@@ -82,6 +82,7 @@ class TikTokPublicationCollector extends AbstractPublicationHistoryCollectorproviderPostId: $postId,publishedAt: $publishedAt,contentType: PublicationContentType::Video,+ contentTypeReported: false,providerContentType: 'video',permalink: data_get($row, 'share_url'),excerpt: data_get($row, 'video_description') ?: data_get($row, 'title'),diff --git a/app/Services/Analytics/Collectors/Publications/YouTubePublicationCollector.php b/app/Services/Analytics/Collectors/Publications/YouTubePublicationCollector.phpindex 4b294bfb1..5d3d84377 100644--- a/app/Services/Analytics/Collectors/Publications/YouTubePublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/YouTubePublicationCollector.php@@ -83,6 +83,7 @@ class YouTubePublicationCollector extends AbstractPublicationHistoryCollectorproviderPostId: (string) $videoId,publishedAt: $publishedAt,contentType: PublicationContentType::Video,+ contentTypeReported: false,providerContentType: 'video',permalink: "https://www.youtube.com/watch?v={$videoId}",excerpt: data_get($row, 'snippet.description') ?: data_get($row, 'snippet.title'),diff --git a/resources/js/components/analytics/PublicationTypeBadge.vue b/resources/js/components/analytics/PublicationTypeBadge.vuenew file mode 100644index 000000000..274cf19f4--- /dev/null+++ b/resources/js/components/analytics/PublicationTypeBadge.vue@@ -0,0 +1,46 @@+<script setup lang="ts">+import {+ IconCircleDashedPlus,+ IconCirclePlay,+ IconVideo,+} from '@tabler/icons-vue';+import { computed, type Component } from 'vue';++import { Badge } from '@/components/ui/badge';+import { showsPostTypeTag } from '@/lib/channelInsights';++const props = defineProps<{+ platform: string;+ contentType: string | null;+ testId: string;+}>();++const TYPE_ICONS: Partial<Record<string, Component>> = {+ reel: IconCirclePlay,+ story: IconCircleDashedPlus,+ video: IconVideo,+};++const icon = computed(() =>+ props.contentType && showsPostTypeTag(props.platform)+ ? TYPE_ICONS[props.contentType]+ : undefined,+);+</script>++<template>+ <Badge+ v-if="icon"+ variant="secondary"+ class="h-6 shrink-0 gap-1.5 px-2 [&>svg]:size-4"+ :data-testid="testId"+ >+ <component+ :is="icon"+ class="shrink-0"+ aria-hidden="true"+ :data-testid="`${testId}-icon`"+ />+ {{ $t(`analytics.detail.content_types.${contentType}`) }}+ </Badge>+</template>diff --git a/resources/js/components/analytics/channel/ChannelPublicationTable.vue b/resources/js/components/analytics/channel/ChannelPublicationTable.vueindex b8b85bbd8..654a64b72 100644--- a/resources/js/components/analytics/channel/ChannelPublicationTable.vue+++ b/resources/js/components/analytics/channel/ChannelPublicationTable.vue@@ -5,16 +5,15 @@ import {IconChevronDown,IconChevronLeft,IconChevronRight,- IconCopy,IconDotsVertical,IconExternalLink,IconLayoutColumns,IconLink,IconPhoto,- IconPlayerPlayFilled,} from '@tabler/icons-vue';-import { computed, ref, watch, type Component } from 'vue';+import { computed, ref, watch } from 'vue';+import PublicationTypeBadge from '@/components/analytics/PublicationTypeBadge.vue';import AnalyticsModeToggle from '@/components/analytics/workspace/AnalyticsModeToggle.vue';import AnalyticsSection from '@/components/analytics/workspace/AnalyticsSection.vue';import PostDetailsDialog from '@/components/publish/PostDetailsDialog.vue';@@ -38,11 +37,13 @@ import {} from '@/components/ui/table';import { usePostDetails } from '@/composables/usePostDetails';import date from '@/date';+import { isVideo } from '@/lib/mediaType';import {copyToClipboard,formatNumberCompact,formatPercent,} from '@/lib/utils';+import { videoFrameUrl } from '@/lib/videoFrame';import type {AnalyticsReport,ChannelInsightsFilters,@@ -208,19 +209,6 @@ const pages = computed<PageItem[]>(() => {return items;});-const OVERLAY_ICONS: Partial<Record<string, Component>> = {- video: IconPlayerPlayFilled,- reel: IconPlayerPlayFilled,- short: IconPlayerPlayFilled,- carousel: IconCopy,-};-const BADGED_TYPES = ['video', 'reel', 'story', 'short', 'link', 'poll'];--const overlayIcon = (row: ChannelPublicationRow): Component | undefined =>- row.content_type ? OVERLAY_ICONS[row.content_type] : undefined;--const hasTypeBadge = (row: ChannelPublicationRow): boolean =>- row.content_type !== null && BADGED_TYPES.includes(row.content_type);const isReloading = ref(false);@@ -492,10 +480,23 @@ const display = (row: ChannelPublicationRow, key: SummaryMetric): string => {>#{{ row.rank }}</span><span- class="relative flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground"+ class="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground">+ <video+ v-if="+ row.media &&+ isVideo(row.media)+ "+ :src="videoFrameUrl(row.media)"+ class="size-full object-cover"+ muted+ playsinline+ preload="metadata"+ aria-hidden="true"+ :data-testid="`insights-posts-video-${row.id}`"+ /><img- v-if="row.thumbnail_url"+ v-else-if="row.thumbnail_url":src="row.thumbnail_url"alt=""class="size-full object-cover"@@ -506,17 +507,6 @@ const display = (row: ChannelPublicationRow, key: SummaryMetric): string => {class="size-4"aria-hidden="true"/>- <span- v-if="overlayIcon(row)"- class="absolute right-1 bottom-1 flex size-5 items-center justify-center rounded-md bg-black/60 text-white"- :data-testid="`insights-posts-type-icon-${row.id}`"- >- <component- :is="overlayIcon(row)"- class="size-3"- aria-hidden="true"- />- </span></span><spanclass="flex min-w-0 flex-col gap-0.5 whitespace-normal"@@ -544,16 +534,11 @@ const display = (row: ChannelPublicationRow, key: SummaryMetric): string => {row.published_at,)}}- <span- v-if="hasTypeBadge(row)"- class="inline-flex h-4.5 shrink-0 items-center rounded-full bg-secondary px-1.5 text-xs font-medium text-foreground"- :data-testid="`insights-posts-type-${row.id}`"- >{{- $t(- `analytics.detail.content_types.${row.content_type}`,- )- }}</span- >+ <PublicationTypeBadge+ :platform="platform"+ :content-type="row.content_type"+ :test-id="`insights-posts-type-${row.id}`"+ /></span></span></button>diff --git a/resources/js/components/analytics/channel/PostTypeFilter.vue b/resources/js/components/analytics/channel/PostTypeFilter.vueindex e25b30af2..ac3399910 100644--- a/resources/js/components/analytics/channel/PostTypeFilter.vue+++ b/resources/js/components/analytics/channel/PostTypeFilter.vue@@ -43,6 +43,9 @@ const clear = (): void => {<template #icon><IconLayoutGrid class="size-4" /></template>+ <template #before-options>+ <div class="pt-2" />+ </template><template #footer><divclass="-mx-3 mt-2 flex items-center border-t border-border px-3 pt-2"diff --git a/resources/js/components/analytics/workspace/TopPosts.vue b/resources/js/components/analytics/workspace/TopPosts.vueindex 6f06f36ed..f7bf08d5f 100644--- a/resources/js/components/analytics/workspace/TopPosts.vue+++ b/resources/js/components/analytics/workspace/TopPosts.vue@@ -2,13 +2,16 @@import { IconArrowUpRight } from '@tabler/icons-vue';import { computed, ref } from 'vue';+import PublicationTypeBadge from '@/components/analytics/PublicationTypeBadge.vue';import ChannelAvatar from '@/components/ChannelAvatar.vue';import PostDetailsDialog from '@/components/publish/PostDetailsDialog.vue';import PublicationDetailsDialog from '@/components/publish/PublicationDetailsDialog.vue';import { getPlatformLabel } from '@/composables/usePlatformLogo';import { usePostDetails } from '@/composables/usePostDetails';import date from '@/date';+import { isImage, isVideo } from '@/lib/mediaType';import { formatNumberCompact } from '@/lib/utils';+import { videoFrameUrl } from '@/lib/videoFrame';import type { TopPost, WorkspaceAnalyticsReport } from '@/types/analytics';import AnalyticsModeToggle from './AnalyticsModeToggle.vue';@@ -54,6 +57,10 @@ const openDetails = (post: TopPost): void => {openPublication(post.id);};const thumbnailFor = (post: TopPost): string | null => {+ if (post.media && isImage(post.media)) {+ return post.media.url;+ }+const value = post.preview_metadata?.thumbnail_url;return typeof value === 'string' && /^https:\/\//i.test(value)? value@@ -144,14 +151,11 @@ const thumbnailFor = (post: TopPost): string | null => {date.formatDateShort(post.published_at)}}</span></span>- <span- class="inline-flex h-4.5 shrink-0 items-center rounded-full bg-secondary px-1 text-xs font-medium text-foreground"- >{{- $t(- `analytics.detail.content_types.${post.content_type}`,- )- }}</span- >+ <PublicationTypeBadge+ :platform="post.platform"+ :content-type="post.content_type"+ :test-id="`analytics-top-post-type-${post.id}`"+ /></div><div class="flex min-h-[54px] gap-3"><p@@ -162,8 +166,18 @@ const thumbnailFor = (post: TopPost): string | null => {$t('analytics.dashboard.no_excerpt')}}</p>+ <video+ v-if="post.media && isVideo(post.media)"+ :src="videoFrameUrl(post.media)"+ class="size-11 shrink-0 rounded-md object-cover"+ muted+ playsinline+ preload="metadata"+ aria-hidden="true"+ :data-testid="`analytics-top-post-video-${post.id}`"+ /><img- v-if="thumbnailFor(post)"+ v-else-if="thumbnailFor(post)":src="thumbnailFor(post)!"alt=""loading="lazy"diff --git a/resources/js/lib/channelInsights.ts b/resources/js/lib/channelInsights.tsnew file mode 100644index 000000000..b5654d243--- /dev/null+++ b/resources/js/lib/channelInsights.ts@@ -0,0 +1,31 @@+import { Platform } from '@/types/platform';++/** Whether the channel insights offer the post type filter. */+export const showsPostTypeFilter = (platform: string): boolean => {+ switch (platform) {+ case Platform.Instagram:+ case Platform.InstagramFacebook:+ case Platform.Facebook:+ case Platform.TikTok:+ case Platform.Pinterest:+ return true;+ case Platform.Threads:+ case Platform.X:+ case Platform.YouTube:+ case Platform.Bluesky:+ case Platform.Mastodon:+ default:+ return false;+ }+};++/** Whether the per post table tags each post with its type. */+export const showsPostTypeTag = (platform: string): boolean => {+ switch (platform) {+ case Platform.YouTube:+ case Platform.TikTok:+ return false;+ default:+ return true;+ }+};diff --git a/resources/js/pages/channels/Insights.vue b/resources/js/pages/channels/Insights.vueindex 2685578ce..5e7508cda 100644--- a/resources/js/pages/channels/Insights.vue+++ b/resources/js/pages/channels/Insights.vue@@ -18,6 +18,7 @@ import { useAnalyticsCoveragePoll } from '@/composables/useAnalyticsCoveragePollimport { getPlatformLabel } from '@/composables/usePlatformLogo';import date from '@/date';import AppLayout from '@/layouts/AppLayout.vue';+import { showsPostTypeFilter } from '@/lib/channelInsights';import { insights } from '@/routes/app/channels';import type {AnalyticsReport,@@ -56,6 +57,11 @@ const span = (range: { start: string; end: string }): string =>const selectedLabelIds = ref<string[]>(props.filters?.labels ?? []);const selectedUntagged = ref<boolean>(props.filters?.untagged ?? false);const selectedTypes = ref<string[]>(props.filters?.types ?? []);+const showsTypeFilter = computed(+ () =>+ showsPostTypeFilter(props.channel.platform) ||+ selectedTypes.value.length > 0,+);const publicationFilters = computed((): Record<string, string | string[]> => ({...(selectedLabelIds.value.length@@ -204,6 +210,7 @@ watch(selectedTypes, applyFilters, { deep: true });test-id="insights-label"/><PostTypeFilter+ v-if="showsTypeFilter"v-model="selectedTypes":types="contentTypes ?? []"/>diff --git a/resources/js/types/analytics.ts b/resources/js/types/analytics.tsindex 090f4d74a..0e332b06e 100644--- a/resources/js/types/analytics.ts+++ b/resources/js/types/analytics.ts@@ -1,3 +1,4 @@+import type { MediaItem } from '@/types/media';import type { SocialAccountStatusValue } from '@/types/social-account-status';export interface Comparison {@@ -51,6 +52,7 @@ export interface TopPost {permalink: string | null;excerpt: string | null;preview_metadata: Record<string, unknown> | null;+ media: MediaItem | null;reactions: number | null;comments: number | null;}@@ -231,6 +233,7 @@ export interface ChannelPublicationRow {rank: number;excerpt: string | null;thumbnail_url: string | null;+ media: MediaItem | null;permalink: string | null;published_at: string;content_type: string | null;diff --git a/tests/Browser/ChannelInsightsFiltersTest.php b/tests/Browser/ChannelInsightsFiltersTest.phpindex bb4f6ee6c..85b0d732d 100644--- a/tests/Browser/ChannelInsightsFiltersTest.php+++ b/tests/Browser/ChannelInsightsFiltersTest.php@@ -165,3 +165,75 @@ test('the post type filter search matches each word typed in any order and ignor$page->assertScript('Array.from(document.querySelectorAll("[data-testid^=insights-post-type-option-]")).map((element) => element.dataset.testid.replace("insights-post-type-option-", "")).join(",")', 'instagram_feed')->assertNoJavaScriptErrors();});++test('a YouTube channel shows no post type filter and no type tag', function (Platform $platform, ContentType $contentType, PublicationContentType $publicationType) {+ $channel = SocialAccount::factory()->create(['workspace_id' => $this->instagram->workspace_id, 'platform' => $platform]);+ $publication = insightsFilterPublication($channel, $this->user, CarbonImmutable::today('UTC')->subDays(2)->setTime(10, 0), 10, $contentType, publicationType: $publicationType);++ $page = visit(route('app.channels.insights', $channel));+ waitForInsightsFilterTestId($page, "insights-posts-row-{$publication->id}");++ $page->assertVisible('@insights-label-filter')+ ->assertMissing('@insights-post-type-filter')+ ->assertMissing("@insights-posts-type-{$publication->id}")+ ->assertNoJavaScriptErrors();+})->with([+ 'YouTube' => [Platform::YouTube, ContentType::YouTubeShort, PublicationContentType::Short],+]);++test('a channel without the post type filter keeps the type tag', function (Platform $platform, ContentType $contentType) {+ $channel = SocialAccount::factory()->create(['workspace_id' => $this->instagram->workspace_id, 'platform' => $platform]);+ $publication = insightsFilterPublication($channel, $this->user, CarbonImmutable::today('UTC')->subDays(2)->setTime(10, 0), 10, $contentType, publicationType: PublicationContentType::Video);++ $page = visit(route('app.channels.insights', $channel));+ waitForInsightsFilterTestId($page, "insights-posts-row-{$publication->id}");++ $page->assertVisible('@insights-label-filter')+ ->assertMissing('@insights-post-type-filter')+ ->assertVisible("@insights-posts-type-{$publication->id}")+ ->assertNoJavaScriptErrors();+})->with([+ 'X' => [Platform::X, ContentType::XPost],+ 'Threads' => [Platform::Threads, ContentType::ThreadsPost],+ 'Bluesky' => [Platform::Bluesky, ContentType::BlueskyPost],+ 'Mastodon' => [Platform::Mastodon, ContentType::MastodonPost],+]);++test('a TikTok channel keeps the post type filter but shows no type tag', function () {+ $channel = SocialAccount::factory()->create(['workspace_id' => $this->instagram->workspace_id, 'platform' => Platform::TikTok]);+ $publication = insightsFilterPublication($channel, $this->user, CarbonImmutable::today('UTC')->subDays(2)->setTime(10, 0), 10, ContentType::TikTokPhoto, publicationType: PublicationContentType::Video);++ $page = visit(route('app.channels.insights', $channel));+ waitForInsightsFilterTestId($page, "insights-posts-row-{$publication->id}");++ $page->assertVisible('@insights-post-type-filter')+ ->assertMissing("@insights-posts-type-{$publication->id}")+ ->assertNoJavaScriptErrors();+});++test('the post type filter leaves a gap between the search and the first type', function () {+ $page = visit(route('app.channels.insights', $this->instagram));+ waitForInsightsFilterTestId($page, 'insights-post-type-filter');+ $page->click('@insights-post-type-filter');+ waitForInsightsFilterTestId($page, 'insights-post-type-option-instagram_feed');++ $page->assertScript('document.querySelector("[data-testid=insights-post-type-option-instagram_feed]").getBoundingClientRect().top - document.querySelector("[data-testid=insights-post-type-search]").getBoundingClientRect().bottom >= 8', true)+ ->assertNoJavaScriptErrors();+});++test('a type already in the URL keeps the post type filter on a network without it so it can be cleared', function () {+ $channel = SocialAccount::factory()->create(['workspace_id' => $this->instagram->workspace_id, 'platform' => Platform::Threads]);+ $publication = insightsFilterPublication($channel, $this->user, CarbonImmutable::today('UTC')->subDays(2)->setTime(10, 0), 10, ContentType::ThreadsPost);++ $page = visit(route('app.channels.insights', ['account' => $channel, 'types' => [ContentType::ThreadsGhostPost->value]]));+ waitForInsightsFilterTestId($page, 'insights-post-type-filter');++ $page->click('@insights-post-type-filter');+ waitForInsightsFilterTestId($page, 'insights-post-type-clear');+ $page->click('@insights-post-type-clear');+ waitForInsightsFilterTestId($page, "insights-posts-row-{$publication->id}");++ $page->assertVisible("@insights-posts-row-{$publication->id}")+ ->assertMissing('@insights-post-type-filter')+ ->assertNoJavaScriptErrors();+});diff --git a/tests/Browser/ChannelInsightsTest.php b/tests/Browser/ChannelInsightsTest.phpindex 307ef5cf2..45d504900 100644--- a/tests/Browser/ChannelInsightsTest.php+++ b/tests/Browser/ChannelInsightsTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\Analytics\PublicationContentType;use App\Enums\Analytics\SyncCollector;use App\Enums\Analytics\SyncStatus;use App\Enums\SocialAccount\Platform;@@ -351,3 +352,47 @@ test('the per post table shows ten posts per page with numbered pages kept in th$page->assertAttribute('@insights-posts-page-1', 'aria-current', 'page')->assertNoJavaScriptErrors();});++test('reels, stories and videos show the content type badge with its icon, other types show none', function () {+ $this->mostReactions->update(['content_type' => PublicationContentType::Reel]);+ $this->mostViews->update(['content_type' => PublicationContentType::Story]);+ $this->previous->update(['content_type' => PublicationContentType::Short, 'provider_published_at' => CarbonImmutable::today('UTC')->subDays(4)->setTime(10, 0)]);+ $image = channelInsightsBrowserPublication($this->instagram, CarbonImmutable::today('UTC')->subDays(3)->setTime(10, 0), ['reactions_count' => 20]);+ $image->update(['content_type' => PublicationContentType::Image]);+ $link = channelInsightsBrowserPublication($this->instagram, CarbonImmutable::today('UTC')->subDays(6)->setTime(10, 0), ['reactions_count' => 15]);+ $link->update(['content_type' => PublicationContentType::Link]);+ $video = channelInsightsBrowserPublication($this->instagram, CarbonImmutable::today('UTC')->subDays(7)->setTime(10, 0), ['reactions_count' => 12]);+ $video->update(['content_type' => PublicationContentType::Video]);++ $page = visit(route('app.channels.insights', $this->instagram));+ waitForChannelInsightsTestId($page, "insights-posts-type-{$this->mostReactions->id}");++ $page->assertVisible("@insights-posts-type-{$this->mostReactions->id}-icon")+ ->assertVisible("@insights-posts-type-{$this->mostViews->id}-icon")+ ->assertMissing("@insights-posts-type-{$image->id}")+ ->assertMissing("@insights-posts-type-{$this->previous->id}")+ ->assertMissing("@insights-posts-type-{$link->id}")+ ->assertScript("document.querySelector('[data-testid=\"insights-posts-type-{$video->id}-icon\"]').classList.contains('tabler-icon-video')", true)+ ->assertScript("document.querySelector('[data-testid=\"insights-posts-type-{$this->mostReactions->id}-icon\"]').classList.contains('tabler-icon-circle-play')", true)+ ->assertScript("document.querySelector('[data-testid=\"insights-posts-type-{$this->mostViews->id}-icon\"]').classList.contains('tabler-icon-circle-dashed-plus')", true)+ ->assertNoJavaScriptErrors();+});++test('the per post table shows the post media from our bucket, a video by its cover frame', function () {+ $video = Post::factory()->forAccount($this->instagram)->published()->create(['media' => [+ ['id' => 'video', 'path' => 'medias/reel.mp4', 'url' => 'https://cdn.trypost.test/medias/reel.mp4', 'type' => 'video', 'mime_type' => 'video/mp4', 'meta' => ['cover_offset_ms' => 1500]],+ ]]);+ $image = Post::factory()->forAccount($this->instagram)->published()->create(['media' => [+ ['id' => 'image', 'path' => 'medias/a.jpg', 'url' => 'https://cdn.trypost.test/medias/a.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg'],+ ]]);+ $expired = ['thumbnail_url' => 'https://scontent.cdninstagram.com/expired.jpg?oe=6ACC450F'];+ $this->mostReactions->update(['post_id' => $video->id, 'preview_metadata' => $expired]);+ $this->mostViews->update(['post_id' => $image->id, 'preview_metadata' => $expired]);++ $page = visit(route('app.channels.insights', $this->instagram));+ waitForChannelInsightsTestId($page, "insights-posts-video-{$this->mostReactions->id}");++ $page->assertAttribute("@insights-posts-video-{$this->mostReactions->id}", 'src', 'https://cdn.trypost.test/medias/reel.mp4#t=1.5')+ ->assertScript("document.querySelector('[data-testid=\"insights-posts-row-{$this->mostViews->id}\"] img').getAttribute('src')", 'https://cdn.trypost.test/medias/a.jpg')+ ->assertNoJavaScriptErrors();+});diff --git a/tests/Browser/WorkspaceInsightsTest.php b/tests/Browser/WorkspaceInsightsTest.phpindex 93fd3e20e..52898f619 100644--- a/tests/Browser/WorkspaceInsightsTest.php+++ b/tests/Browser/WorkspaceInsightsTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\Analytics\PublicationContentType;use App\Enums\Analytics\SyncCollector;use App\Enums\Analytics\SyncStatus;use App\Enums\SocialAccount\Platform;@@ -12,6 +13,7 @@ use App\Models\AnalyticsAccountDailySnapshot;use App\Models\AnalyticsPublication;use App\Models\AnalyticsPublicationDailySnapshot;use App\Models\AnalyticsSyncState;+use App\Models\Post;use App\Models\SocialAccount;use App\Models\User;use App\Models\Workspace;@@ -183,6 +185,17 @@ function workspaceInsightsChartWidthsAroundSidebarToggle(mixed $page): arrayJS);}+function workspaceInsightsBrowserUser(): User+{+ $user = User::factory()->create();+ $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);+ $workspace->members()->attach($user->id, membershipPivot('admin'));+ $user->update(['current_workspace_id' => $workspace->id]);+ subscribeAccount($user->account);++ return $user->fresh();+}+test('workspace dashboard separates accounts and switches follower and post chart modes', function () {Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);$user = User::factory()->create();@@ -648,3 +661,71 @@ test('charts keep their width while the sidebar animates and resize once it sett->and($widths['after'])->toBeGreaterThan($widths['before']);$page->assertNoJavaScriptErrors();});++test('top posts tag each post type like the channel table', function () {+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);+ $user = workspaceInsightsBrowserUser();+ $workspace = $user->currentWorkspace;+ $publications = [];++ foreach ([+ 'reel' => [Platform::Instagram, PublicationContentType::Reel],+ 'image' => [Platform::Instagram, PublicationContentType::Image],+ 'tiktok' => [Platform::TikTok, PublicationContentType::Video],+ ] as $key => [$platform, $contentType]) {+ $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => $platform]);+ $publications[$key] = AnalyticsPublication::factory()->create([+ 'workspace_id' => $workspace->id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'platform' => $platform,+ 'network' => $platform->network(),+ 'content_type' => $contentType,+ 'provider_published_at' => now()->subDays(3)->setTime(10, 0),+ ]);+ AnalyticsPublicationDailySnapshot::factory()->create(['publication_id' => $publications[$key]->id, 'reactions_count' => 10]);+ }++ $this->actingAs($user);+ $page = visit(route('app.insights'));+ waitForWorkspaceInsightsTestId($page, "analytics-top-post-type-{$publications['reel']->id}");++ $page->assertScript("document.querySelector('[data-testid=\"analytics-top-post-type-{$publications['reel']->id}-icon\"]').classList.contains('tabler-icon-circle-play')", true)+ ->assertMissing("@analytics-top-post-type-{$publications['image']->id}")+ ->assertMissing("@analytics-top-post-type-{$publications['tiktok']->id}")+ ->assertNoJavaScriptErrors();+});++test('top posts show the post media from our bucket, a video by its cover frame', function () {+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);+ $user = workspaceInsightsBrowserUser();+ $workspace = $user->currentWorkspace;+ $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);+ $publications = [];++ foreach ([+ 'video' => ['id' => 'video', 'path' => 'medias/reel.mp4', 'url' => 'https://cdn.trypost.test/medias/reel.mp4', 'type' => 'video', 'mime_type' => 'video/mp4'],+ 'image' => ['id' => 'image', 'path' => 'medias/a.jpg', 'url' => 'http://trypost.test/storage/medias/a.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg'],+ ] as $key => $media) {+ $post = Post::factory()->forAccount($account)->published()->create(['media' => [$media]]);+ $publications[$key] = AnalyticsPublication::factory()->create([+ 'workspace_id' => $workspace->id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'post_id' => $post->id,+ 'platform' => Platform::Instagram,+ 'network' => Platform::Instagram->network(),+ 'preview_metadata' => ['thumbnail_url' => 'https://scontent.cdninstagram.com/expired.jpg?oe=6ACC450F'],+ 'provider_published_at' => now()->subDays(3)->setTime(10, 0),+ ]);+ AnalyticsPublicationDailySnapshot::factory()->create(['publication_id' => $publications[$key]->id, 'reactions_count' => 10]);+ }++ $this->actingAs($user);+ $page = visit(route('app.insights'));+ waitForWorkspaceInsightsTestId($page, "analytics-top-post-video-{$publications['video']->id}");++ $page->assertAttribute("@analytics-top-post-video-{$publications['video']->id}", 'src', 'https://cdn.trypost.test/medias/reel.mp4#t=0.1')+ ->assertScript("Array.from(document.querySelectorAll('[data-testid=\"analytics-top-post\"] img')).map((image) => image.getAttribute('src')).includes('http://trypost.test/storage/medias/a.jpg')", true)+ ->assertNoJavaScriptErrors();+});diff --git a/tests/Feature/Analytics/ChannelInsightsPageTest.php b/tests/Feature/Analytics/ChannelInsightsPageTest.phpindex 0cf33f53f..7361841d4 100644--- a/tests/Feature/Analytics/ChannelInsightsPageTest.php+++ b/tests/Feature/Analytics/ChannelInsightsPageTest.php@@ -110,6 +110,27 @@ test('the insights page renders the channel report and its publications', functi->etc());});+test('publications show the post media from our bucket instead of the network preview', function () {+ $image = ['id' => 'image', 'path' => 'medias/a.jpg', 'url' => 'https://cdn.trypost.test/medias/a.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg'];+ $video = ['id' => 'video', 'path' => 'medias/reel.mp4', 'url' => 'https://cdn.trypost.test/medias/reel.mp4', 'type' => 'video', 'mime_type' => 'video/mp4', 'meta' => ['cover_offset_ms' => 1500]];+ $imagePost = Post::factory()->forAccount($this->instagram)->published()->create(['media' => [$image]]);+ $videoPost = Post::factory()->forAccount($this->instagram)->published()->create(['media' => [$video]]);+ $expired = ['preview_metadata' => ['thumbnail_url' => 'https://scontent.cdninstagram.com/expired.jpg?oe=6ACC450F']];+ channelInsightsPublication($this->instagram, '2026-09-20 10:00:00', ['reactions_count' => 8], [...$expired, 'post_id' => $imagePost->id]);+ channelInsightsPublication($this->instagram, '2026-09-19 10:00:00', ['reactions_count' => 3], [...$expired, 'post_id' => $videoPost->id]);++ $this->actingAs($this->user)+ ->get(route('app.channels.insights', $this->instagram))+ ->assertOk()+ ->assertInertia(fn (Assert $page) => $page+ ->where('publications.data.0.thumbnail_url', $image['url'])+ ->where('publications.data.0.media.url', $image['url'])+ ->where('publications.data.1.media.url', $video['url'])+ ->where('publications.data.1.media.type', 'video')+ ->where('publications.data.1.media.meta.cover_offset_ms', 1500)+ ->etc());+});+test('publications sort by the chosen metric with nulls last and ties by published date', function () {$older = channelInsightsPublication($this->instagram, '2026-09-10 10:00:00', ['reactions_count' => 5, 'views_count' => 100]);$top = channelInsightsPublication($this->instagram, '2026-09-11 10:00:00', ['reactions_count' => 10, 'views_count' => null]);diff --git a/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php b/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.phpindex b233466d1..8292d2bba 100644--- a/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php+++ b/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php@@ -49,6 +49,7 @@ test('x reads one owned timeline page with only discovery fields', function () {expect($page->publications)->toHaveCount(1)->and($page->publications[0]->contentType)->toBe(PublicationContentType::Image)+ ->and($page->publications[0]->contentTypeReported)->toBeTrue()->and($page->publications[0]->permalink)->toBe('https://x.com/example/status/tweet-1')->and($page->nextCursor)->toBe('x-next')->and($page->providerExhausted)->toBeFalse();@@ -185,6 +186,7 @@ test('youtube pages the uploads playlist and hydrates videos in one batch withouPublicationContentType::Video,PublicationContentType::Video,])+ ->and(array_column($page->publications, 'contentTypeReported'))->toBe([false, false])->and($page->nextCursor)->toBe('youtube-next');Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/playlistItems')&& $request['playlistId'] === 'uploads-1'@@ -291,6 +293,7 @@ test('tiktok reads at most twenty videos and marks expiring covers', function ()expect($page->publications)->toHaveCount(1)->and($page->publications[0]->contentType)->toBe(PublicationContentType::Video)+ ->and($page->publications[0]->contentTypeReported)->toBeFalse()->and($page->publications[0]->previewMetadata)->toMatchArray(['thumbnail_url' => 'https://cdn.example/cover.jpg?x-expires=1790003600','expires_at' => CarbonImmutable::createFromTimestampUTC(1_790_003_600)->toIso8601String(),diff --git a/tests/Feature/Analytics/PublicationReconciliationTest.php b/tests/Feature/Analytics/PublicationReconciliationTest.phpindex e6bd3846f..d2787fb1a 100644--- a/tests/Feature/Analytics/PublicationReconciliationTest.php+++ b/tests/Feature/Analytics/PublicationReconciliationTest.php@@ -265,3 +265,51 @@ test('a less-than sign typed in a TryPost post stays in its analytics excerpt',expect(app(SyncTryPostPublication::class)->handle($post->fresh())->excerpt)->toBe('I <3 TryPost and price < 10');});++test('a network that does not report the type keeps the type TryPost published', function (Platform $platform, ContentType $contentType, PublicationContentType $expected) {+ $account = SocialAccount::factory()->create(['platform' => $platform]);+ $post = Post::factory()->forAccount($account, $contentType)->published()->create(['platform_post_id' => 'remote-1']);+ app(SyncTryPostPublication::class)->handle($post);++ app(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(+ providerPostId: 'remote-1',+ publishedAt: CarbonImmutable::parse('2026-09-20 12:00:00', 'UTC'),+ contentType: PublicationContentType::Video,+ contentTypeReported: false,+ ));++ expect(AnalyticsPublication::sole()->content_type)->toBe($expected);+})->with([+ 'TikTok photo' => [Platform::TikTok, ContentType::TikTokPhoto, PublicationContentType::Carousel],+ 'YouTube Short' => [Platform::YouTube, ContentType::YouTubeShort, PublicationContentType::Short],+]);++test('a network that does not report the type stores its default on a new publication', function () {+ $account = SocialAccount::factory()->create(['platform' => Platform::TikTok]);++ app(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(+ providerPostId: 'remote-1',+ publishedAt: CarbonImmutable::parse('2026-09-20 12:00:00', 'UTC'),+ contentType: PublicationContentType::Video,+ contentTypeReported: false,+ ));++ expect(AnalyticsPublication::sole()->content_type)->toBe(PublicationContentType::Video);+});++test('a network that reports the type still corrects the type TryPost published', function () {+ $account = SocialAccount::factory()->create(['platform' => Platform::Instagram]);+ $post = Post::factory()->forAccount($account, ContentType::InstagramFeed)->published()->create([+ 'platform_post_id' => 'remote-1',+ 'media' => [['id' => 'video', 'path' => 'medias/a.mp4', 'url' => 'https://cdn.trypost.test/medias/a.mp4', 'type' => 'video', 'mime_type' => 'video/mp4']],+ ]);+ app(SyncTryPostPublication::class)->handle($post);++ app(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(+ providerPostId: 'remote-1',+ publishedAt: CarbonImmutable::parse('2026-09-20 12:00:00', 'UTC'),+ contentType: PublicationContentType::Reel,+ ));++ expect(AnalyticsPublication::sole()->content_type)->toBe(PublicationContentType::Reel);+});diff --git a/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php b/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.phpindex 77d8d53af..2e59677fa 100644--- a/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php+++ b/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php@@ -156,6 +156,33 @@ test('top posts include the source post id for TryPost publications', function (expect($report['top_posts']['reactions'][0]['post_id'])->toBe($post->id);});+test('top posts carry the post media from our bucket instead of the network preview', function () {+ $workspace = Workspace::factory()->create();+ $account = analyticsReportAccount($workspace, Platform::Instagram);+ $video = ['id' => 'video', 'path' => 'medias/reel.mp4', 'url' => 'https://cdn.trypost.test/medias/reel.mp4', 'type' => 'video', 'mime_type' => 'video/mp4', 'meta' => ['cover_offset_ms' => 1500]];+ $document = ['id' => 'document', 'path' => 'medias/deck.pdf', 'url' => 'https://cdn.trypost.test/medias/deck.pdf', 'type' => 'document', 'mime_type' => 'application/pdf'];+ $post = Post::factory()->forAccount($account)->published()->create(['media' => [$document, $video]]);+ $other = Post::factory()->forAccount($account)->published()->create(['media' => [$video]]);+ $linked = analyticsReportPublication($account, '2026-09-05 10:00:00', 9, 1, 10, 100);+ $linked->update(['post_id' => $post->id, 'preview_metadata' => ['thumbnail_url' => 'https://scontent.cdninstagram.com/expired.jpg?oe=6ACC450F']]);+ $commented = analyticsReportPublication($account, '2026-09-06 10:00:00', 1, 9, 10, 100);+ $commented->update(['post_id' => $other->id]);+ $external = analyticsReportPublication($account, '2026-09-07 10:00:00', 5, 5, 10, 100);+ $external->update(['preview_metadata' => ['thumbnail_url' => 'https://pbs.twimg.com/media/external.jpg']]);++ $report = app(BuildWorkspaceAnalyticsReport::class)->execute(+ $workspace,+ new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC')),+ );+ $reactions = collect($report['top_posts']['reactions'])->keyBy('id');+ $comments = collect($report['top_posts']['comments'])->keyBy('id');++ expect($reactions[$linked->id]['media'])->toMatchArray(['url' => $video['url'], 'type' => 'video', 'meta' => ['cover_offset_ms' => 1500]])+ ->and($comments[$commented->id]['media'])->toMatchArray(['url' => $video['url'], 'type' => 'video'])+ ->and($reactions[$external->id]['media'])->toBeNull()+ ->and($reactions[$external->id]['preview_metadata']['thumbnail_url'])->toBe('https://pbs.twimg.com/media/external.jpg');+});+test('workspace follower total stays unavailable until every connected account has an observation', function () {$workspace = Workspace::factory()->create();$first = analyticsReportAccount($workspace, Platform::Instagram);diff --git a/tests/Feature/Parity/InsightsParityTest.php b/tests/Feature/Parity/InsightsParityTest.phpindex fc95fa8c3..3fa47b01e 100644--- a/tests/Feature/Parity/InsightsParityTest.php+++ b/tests/Feature/Parity/InsightsParityTest.php@@ -357,7 +357,12 @@ function seedChannelInsightsParity(Workspace $workspace, User $user): array$post = null;if ($type !== null) {- $post = Post::factory()->forAccount($account, $type)->published()->create(['user_id' => $user->id]);+ $post = Post::factory()->forAccount($account, $type)->published()->create([+ 'user_id' => $user->id,+ 'media' => $type === ContentType::InstagramReel+ ? [['id' => 'reel', 'path' => 'medias/reel.mp4', 'url' => 'https://cdn.trypost.test/medias/reel.mp4', 'type' => 'video', 'mime_type' => 'video/mp4']]+ : [],+ ]);if ($labelled) {$post->labels()->attach($label->id);diff --git a/tests/Unit/Models/PostTest.php b/tests/Unit/Models/PostTest.phpindex 92c142406..7e006bb93 100644--- a/tests/Unit/Models/PostTest.php+++ b/tests/Unit/Models/PostTest.php@@ -175,3 +175,20 @@ test('post scope failed returns only failed posts', function () {expect($posts)->toHaveCount(1);expect($posts->first()->id)->toBe($failed->id);});++test('the cover media is the first image or video, skipping documents', function (array $media, ?string $expected) {+ expect((new Post(['media' => $media]))->coverMedia()?->id)->toBe($expected);+})->with([+ 'video after a document' => [[+ ['id' => 'deck', 'path' => 'medias/deck.pdf', 'url' => 'https://cdn.trypost.test/medias/deck.pdf', 'type' => 'document'],+ ['id' => 'reel', 'path' => 'medias/reel.mp4', 'url' => 'https://cdn.trypost.test/medias/reel.mp4', 'type' => 'video'],+ ], 'reel'],+ 'first image' => [[+ ['id' => 'first', 'path' => 'medias/a.jpg', 'url' => 'https://cdn.trypost.test/medias/a.jpg', 'type' => 'image'],+ ['id' => 'second', 'path' => 'medias/b.jpg', 'url' => 'https://cdn.trypost.test/medias/b.jpg', 'type' => 'image'],+ ], 'first'],+ 'only a document' => [[+ ['id' => 'deck', 'path' => 'medias/deck.pdf', 'url' => 'https://cdn.trypost.test/medias/deck.pdf', 'type' => 'document'],+ ], null],+ 'no media' => [[], null],+]);