From 7388313f5c37d0992e44409bd28c3f352b407a15 Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Wed, 24 Jun 2026 16:32:27 -0300 Subject: [PATCH 01/22] feat(linkedin): support PDF document (carousel) posts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add LinkedIn document posts — the swipeable PDF carousel — for both personal profiles and company pages. This is the format every major competitor exposes via native PDF upload, and the reason a trial user churned. - New 'document' media type (application/pdf) across the upload pipeline (Type enum, HasMedia, FormRequests incl. chunked, Platform media types) - New LinkedInDocument / LinkedInPageDocument content types: PDF-only, single-file, with a supportsDocument() flag - Publisher flow: documents initializeUpload -> PUT -> poll AVAILABLE -> post with content.media.{id,title}; optional document_title meta (falls back to file name) - PDF is mutually exclusive with image/video, enforced in ContentTypeCompatibleWithMedia - Frontend: 'Document (PDF)' variant, media rules (100MB cap), composer/gallery/detail PDF cards, real PDF embed in the LinkedIn editor preview, i18n in en/es/pt-BR - Tests: publishers (personal + page, incl. processing-failure path), enums, compatibility rule, chunked PDF upload, API + MCP document_title round-trip LinkedIn caps documents at 100MB / 300 pages (Documents API). The page limit is enforced by LinkedIn at publish, not validated client-side. --- app/DataTransferObjects/MediaItem.php | 10 + app/Enums/Media/Type.php | 9 + app/Enums/PostPlatform/ContentType.php | 23 +- app/Enums/SocialAccount/Platform.php | 2 +- .../Requests/Api/Post/StoreMediaRequest.php | 1 + app/Http/Requests/Api/StoreUploadRequest.php | 1 + .../Requests/App/Asset/StoreAssetRequest.php | 2 +- .../App/Asset/StoreChunkedAssetRequest.php | 2 +- app/Mcp/Tools/Post/AttachMediaFromUrlTool.php | 4 +- app/Mcp/Tools/Post/RequestMediaUploadTool.php | 2 +- app/Models/Media.php | 9 + app/Models/Traits/HasMedia.php | 4 + app/Rules/ContentTypeCompatibleWithMedia.php | 17 ++ app/Services/Social/LinkedInPagePublisher.php | 165 +++++++++++++++ app/Services/Social/LinkedInPublisher.php | 161 ++++++++++++++ app/Support/PostPlatformMetaRules.php | 3 + config/trypost.php | 2 + lang/en/posts.php | 11 + lang/es/posts.php | 11 + lang/pt-BR/posts.php | 11 + .../js/components/assets/GalleryBrowser.vue | 21 +- .../posts/editor/LinkedInSettings.vue | 2 + .../posts/editor/PostEditorComposer.vue | 22 +- .../posts/previews/LinkedInPreview.vue | 9 +- resources/js/composables/useMedia.ts | 31 ++- resources/js/composables/useMediaRules.ts | 23 ++ resources/js/composables/usePlatformLogo.ts | 4 +- resources/js/composables/usePostCompliance.ts | 4 +- resources/js/pages/posts/Show.vue | 25 ++- resources/js/types/content-type.ts | 2 + tests/Feature/Api/PostApiPlatformMetaTest.php | 17 ++ tests/Feature/AssetControllerTest.php | 23 ++ .../Feature/Mcp/PostPlatformMetaToolTest.php | 18 ++ .../Social/LinkedInPagePublisherTest.php | 63 ++++++ .../Services/Social/LinkedInPublisherTest.php | 198 ++++++++++++++++++ tests/Unit/Enums/ContentTypeTest.php | 26 +++ tests/Unit/Enums/MediaTypeTest.php | 15 +- .../ContentTypeCompatibleWithMediaTest.php | 33 +++ tests/Unit/Traits/HasMediaTest.php | 11 +- 39 files changed, 971 insertions(+), 26 deletions(-) diff --git a/app/DataTransferObjects/MediaItem.php b/app/DataTransferObjects/MediaItem.php index 64f9c98b..1e3fd111 100644 --- a/app/DataTransferObjects/MediaItem.php +++ b/app/DataTransferObjects/MediaItem.php @@ -43,6 +43,15 @@ public function isImage(): bool return in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'heic', 'heif']); } + public function isDocument(): bool + { + if ($this->mime_type) { + return $this->mime_type === 'application/pdf'; + } + + return strtolower(pathinfo($this->path, PATHINFO_EXTENSION)) === 'pdf'; + } + /** * @param array $data */ @@ -63,6 +72,7 @@ public static function fromArray(array $data): self 'webp' => 'image/webp', 'mp4' => 'video/mp4', 'mov' => 'video/quicktime', + 'pdf' => 'application/pdf', default => null, }; } diff --git a/app/Enums/Media/Type.php b/app/Enums/Media/Type.php index 935da839..9eb95433 100644 --- a/app/Enums/Media/Type.php +++ b/app/Enums/Media/Type.php @@ -8,12 +8,14 @@ enum Type: string { case Image = 'image'; case Video = 'video'; + case Document = 'document'; public function label(): string { return match ($this) { self::Image => 'Imagem', self::Video => 'Vídeo', + self::Document => 'Documento', }; } @@ -31,6 +33,11 @@ public function label(): string * server-side transcoding, accepting WebM would just produce * platform-specific publish failures down the line. * + * Document accepts PDF only — the swipeable LinkedIn document + * (carousel) format. PPTX/DOCX are also valid LinkedIn documents + * but are converted server-side by LinkedIn and lose fonts, so we + * keep the surface to PDF. + * * @return array */ public function allowedMimeTypes(): array @@ -38,6 +45,7 @@ public function allowedMimeTypes(): array return match ($this) { self::Image => ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], self::Video => ['video/mp4', 'video/quicktime'], + self::Document => ['application/pdf'], }; } @@ -52,6 +60,7 @@ public function extensions(): array return match ($this) { self::Image => ['jpg', 'jpeg', 'png', 'gif', 'webp'], self::Video => ['mp4', 'mov'], + self::Document => ['pdf'], }; } diff --git a/app/Enums/PostPlatform/ContentType.php b/app/Enums/PostPlatform/ContentType.php index 02a27e9b..985fa647 100644 --- a/app/Enums/PostPlatform/ContentType.php +++ b/app/Enums/PostPlatform/ContentType.php @@ -16,10 +16,12 @@ enum ContentType: string // LinkedIn case LinkedInPost = 'linkedin_post'; case LinkedInCarousel = 'linkedin_carousel'; + case LinkedInDocument = 'linkedin_document'; // LinkedIn Page case LinkedInPagePost = 'linkedin_page_post'; case LinkedInPageCarousel = 'linkedin_page_carousel'; + case LinkedInPageDocument = 'linkedin_page_document'; // Facebook case FacebookPost = 'facebook_post'; @@ -70,6 +72,7 @@ public function label(): string self::InstagramStory => 'Story', self::LinkedInPost, self::LinkedInPagePost => 'Post', self::LinkedInCarousel, self::LinkedInPageCarousel => 'Carousel', + self::LinkedInDocument, self::LinkedInPageDocument => 'Document', self::FacebookPost => 'Post', self::FacebookReel => 'Reel', self::FacebookStory => 'Story', @@ -97,8 +100,8 @@ public function platform(): SocialPlatform { return match ($this) { self::InstagramFeed, self::InstagramReel, self::InstagramStory => SocialPlatform::Instagram, - self::LinkedInPost, self::LinkedInCarousel => SocialPlatform::LinkedIn, - self::LinkedInPagePost, self::LinkedInPageCarousel => SocialPlatform::LinkedInPage, + self::LinkedInPost, self::LinkedInCarousel, self::LinkedInDocument => SocialPlatform::LinkedIn, + self::LinkedInPagePost, self::LinkedInPageCarousel, self::LinkedInPageDocument => SocialPlatform::LinkedInPage, self::FacebookPost, self::FacebookReel, self::FacebookStory => SocialPlatform::Facebook, self::TikTokVideo, self::TikTokPhoto => SocialPlatform::TikTok, self::YouTubeShort => SocialPlatform::YouTube, @@ -166,6 +169,7 @@ public function maxMediaCount(): int self::InstagramReel, self::InstagramStory => 1, self::LinkedInPost, self::LinkedInPagePost => 1, self::LinkedInCarousel, self::LinkedInPageCarousel => 20, + self::LinkedInDocument, self::LinkedInPageDocument => 1, self::FacebookPost => 10, self::FacebookReel, self::FacebookStory => 1, self::TikTokVideo => 1, @@ -188,6 +192,7 @@ public function supportsVideo(): bool self::InstagramFeed, self::InstagramReel, self::InstagramStory => true, self::LinkedInPost, self::LinkedInPagePost => true, self::LinkedInCarousel, self::LinkedInPageCarousel => false, + self::LinkedInDocument, self::LinkedInPageDocument => false, self::FacebookPost, self::FacebookReel, self::FacebookStory => true, self::TikTokVideo => true, self::TikTokPhoto => false, @@ -212,10 +217,24 @@ public function supportsImage(): bool self::TikTokPhoto => true, self::YouTubeShort => false, self::PinterestVideoPin => false, + self::LinkedInDocument, self::LinkedInPageDocument => false, default => true, }; } + /** + * Whether this content type carries a document (PDF) attachment instead of + * images/videos — currently the LinkedIn swipeable document ("carousel"). + * A document post is PDF-only: it never combines with images or videos. + */ + public function supportsDocument(): bool + { + return match ($this) { + self::LinkedInDocument, self::LinkedInPageDocument => true, + default => false, + }; + } + /** * Whether a single post may carry images and a video together. Most * targets accept only one or the other; this is conservative and lists diff --git a/app/Enums/SocialAccount/Platform.php b/app/Enums/SocialAccount/Platform.php index d2e18c43..e6d94f09 100644 --- a/app/Enums/SocialAccount/Platform.php +++ b/app/Enums/SocialAccount/Platform.php @@ -94,7 +94,7 @@ public function color(): string public function allowedMediaTypes(): array { return match ($this) { - self::LinkedIn, self::LinkedInPage => [MediaType::Image, MediaType::Video], + self::LinkedIn, self::LinkedInPage => [MediaType::Image, MediaType::Video, MediaType::Document], self::X => [MediaType::Image, MediaType::Video], self::TikTok => [MediaType::Video], self::YouTube => [MediaType::Video], diff --git a/app/Http/Requests/Api/Post/StoreMediaRequest.php b/app/Http/Requests/Api/Post/StoreMediaRequest.php index d31a265b..77075a7c 100644 --- a/app/Http/Requests/Api/Post/StoreMediaRequest.php +++ b/app/Http/Requests/Api/Post/StoreMediaRequest.php @@ -22,6 +22,7 @@ public function rules(): array $allowedMimes = [ ...MediaType::Image->allowedMimeTypes(), ...MediaType::Video->allowedMimeTypes(), + ...MediaType::Document->allowedMimeTypes(), ]; return [ diff --git a/app/Http/Requests/Api/StoreUploadRequest.php b/app/Http/Requests/Api/StoreUploadRequest.php index 812c8ac9..f07237ed 100644 --- a/app/Http/Requests/Api/StoreUploadRequest.php +++ b/app/Http/Requests/Api/StoreUploadRequest.php @@ -22,6 +22,7 @@ public function rules(): array $allowed = implode(',', array_merge( MediaType::Image->allowedMimeTypes(), MediaType::Video->allowedMimeTypes(), + MediaType::Document->allowedMimeTypes(), )); $maxKb = (int) config('ai.mcp.upload.max_size_mb') * 1024; diff --git a/app/Http/Requests/App/Asset/StoreAssetRequest.php b/app/Http/Requests/App/Asset/StoreAssetRequest.php index 7f649b0c..ddc07b10 100644 --- a/app/Http/Requests/App/Asset/StoreAssetRequest.php +++ b/app/Http/Requests/App/Asset/StoreAssetRequest.php @@ -16,7 +16,7 @@ public function authorize(): bool public function rules(): array { - $allowedMimes = [...MediaType::Image->allowedMimeTypes(), ...MediaType::Video->allowedMimeTypes()]; + $allowedMimes = [...MediaType::Image->allowedMimeTypes(), ...MediaType::Video->allowedMimeTypes(), ...MediaType::Document->allowedMimeTypes()]; return [ // Use the largest per-type cap as the upper bound; per-type diff --git a/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.php b/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.php index 84ebf16f..3244d682 100644 --- a/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.php +++ b/app/Http/Requests/App/Asset/StoreChunkedAssetRequest.php @@ -39,7 +39,7 @@ protected function prepareForValidation(): void */ public function rules(): array { - $allowedSuffixes = collect([MediaType::Image, MediaType::Video]) + $allowedSuffixes = collect([MediaType::Image, MediaType::Video, MediaType::Document]) ->flatMap(fn (MediaType $type) => $type->extensions()) ->map(fn (string $ext) => '.'.$ext) ->all(); diff --git a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php index 97a00463..faab44f5 100644 --- a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php +++ b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php @@ -14,7 +14,7 @@ use Laravel\Mcp\Server\Attributes\Description; use Laravel\Mcp\Server\Tool; -#[Description('Download images or videos from public URLs and attach them to a post. Each URL is fetched, stored, and registered as a Media record on the workspace. Allowed types are intersected with the platforms enabled on the post (e.g. nothing accepted if no platform supports the media type).')] +#[Description('Download images, videos, or PDF documents from public URLs and attach them to a post. Each URL is fetched, stored, and registered as a Media record on the workspace. Allowed types are intersected with the platforms enabled on the post (e.g. nothing accepted if no platform supports the media type).')] class AttachMediaFromUrlTool extends Tool { public function handle(Request $request): Response|ResponseFactory @@ -53,7 +53,7 @@ public function schema(JsonSchema $schema): array 'urls' => $schema->array() ->items($schema->string()) ->required() - ->description('Public HTTP/HTTPS URLs of images or videos. Max 10 URLs per call, 50MB per file. Allowed types: image/jpeg, image/png, image/gif, image/webp, video/mp4, video/quicktime, video/webm.'), + ->description('Public HTTP/HTTPS URLs of images, videos, or PDFs. Max 10 URLs per call, 50MB per file. Allowed types: image/jpeg, image/png, image/gif, image/webp, video/mp4, video/quicktime, application/pdf.'), ]; } } diff --git a/app/Mcp/Tools/Post/RequestMediaUploadTool.php b/app/Mcp/Tools/Post/RequestMediaUploadTool.php index fb17667b..2b380e50 100644 --- a/app/Mcp/Tools/Post/RequestMediaUploadTool.php +++ b/app/Mcp/Tools/Post/RequestMediaUploadTool.php @@ -14,7 +14,7 @@ use Laravel\Mcp\Server\Attributes\Description; use Laravel\Mcp\Server\Tool; -#[Description('Issue a one-shot signed POST URL that lets the user upload a local file (image or video, up to the workspace upload cap — 50 MB by default) directly to this workspace. Returns an upload_token and upload_url. Hand the URL to the user (e.g. as a curl command with `-F media=@path/to/file`) or to the MCP client. After upload, call AttachMediaFromUploadTool(post_id, upload_token) to attach the result to a post.')] +#[Description('Issue a one-shot signed POST URL that lets the user upload a local file (image, video, or PDF document, up to the workspace upload cap — 50 MB by default) directly to this workspace. Returns an upload_token and upload_url. Hand the URL to the user (e.g. as a curl command with `-F media=@path/to/file`) or to the MCP client. After upload, call AttachMediaFromUploadTool(post_id, upload_token) to attach the result to a post.')] class RequestMediaUploadTool extends Tool { public function handle(Request $request): Response|ResponseFactory diff --git a/app/Models/Media.php b/app/Models/Media.php index f60f24fb..8a379037 100644 --- a/app/Models/Media.php +++ b/app/Models/Media.php @@ -81,6 +81,15 @@ public function isImage(): bool return in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'heic', 'heif']); } + public function isDocument(): bool + { + if ($this->mime_type) { + return $this->mime_type === 'application/pdf'; + } + + return strtolower(pathinfo($this->path, PATHINFO_EXTENSION)) === 'pdf'; + } + public function getTemporaryUrl(int $expirationMinutes = 60): string { return Storage::temporaryUrl( diff --git a/app/Models/Traits/HasMedia.php b/app/Models/Traits/HasMedia.php index c1b9cb5e..81316edc 100644 --- a/app/Models/Traits/HasMedia.php +++ b/app/Models/Traits/HasMedia.php @@ -164,6 +164,10 @@ private function getMediaType(string $mimeType): string return 'video'; } + if ($mimeType === 'application/pdf') { + return 'document'; + } + throw new \InvalidArgumentException("Unsupported media MIME type: {$mimeType}"); } diff --git a/app/Rules/ContentTypeCompatibleWithMedia.php b/app/Rules/ContentTypeCompatibleWithMedia.php index 2fd2e5f1..1c3e0313 100644 --- a/app/Rules/ContentTypeCompatibleWithMedia.php +++ b/app/Rules/ContentTypeCompatibleWithMedia.php @@ -53,6 +53,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void $hasImage = collect($media)->contains(fn ($item) => $this->isImage((array) $item)); $hasVideo = collect($media)->contains(fn ($item) => $this->isVideo((array) $item)); + $hasDocument = collect($media)->contains(fn ($item) => $this->isDocument((array) $item)); if ($hasImage && ! $contentType->supportsImage()) { $fail("{$contentType->label()} does not support images."); @@ -62,6 +63,10 @@ public function validate(string $attribute, mixed $value, Closure $fail): void $fail("{$contentType->label()} does not support videos."); } + if ($hasDocument && ! $contentType->supportsDocument()) { + $fail("{$contentType->label()} does not support PDF documents."); + } + if ($hasImage && $hasVideo && ! $contentType->supportsMixedMedia()) { $fail("{$contentType->label()} can't combine an image and a video in the same post."); } @@ -90,4 +95,16 @@ private function isVideo(array $item): bool return str_starts_with((string) data_get($item, 'mime_type', ''), 'video/'); } + + /** + * @param array $item + */ + private function isDocument(array $item): bool + { + if (data_get($item, 'type') === MediaType::Document->value) { + return true; + } + + return data_get($item, 'mime_type') === 'application/pdf'; + } } diff --git a/app/Services/Social/LinkedInPagePublisher.php b/app/Services/Social/LinkedInPagePublisher.php index c1a186f6..9adb038c 100644 --- a/app/Services/Social/LinkedInPagePublisher.php +++ b/app/Services/Social/LinkedInPagePublisher.php @@ -63,6 +63,7 @@ public function publish(PostPlatform $postPlatform): array try { return match ($contentType) { ContentType::LinkedInPageCarousel => $this->publishCarousel($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account), + ContentType::LinkedInPageDocument => $this->publishDocument($organizationUrn, $content, $postPlatform->post->mediaItems, $this->resolveDocumentTitle($postPlatform), $this->account), ContentType::LinkedInPagePost => $this->publishPost($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account), default => throw new \Exception("Unsupported LinkedIn Page content type: {$contentType?->value}"), }; @@ -89,6 +90,7 @@ private function retryWithRefresh(PostPlatform $postPlatform, ?string $content, return match ($contentType) { ContentType::LinkedInPageCarousel => $this->publishCarousel($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account), + ContentType::LinkedInPageDocument => $this->publishDocument($organizationUrn, $content, $postPlatform->post->mediaItems, $this->resolveDocumentTitle($postPlatform), $this->account), ContentType::LinkedInPagePost => $this->publishPost($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account), default => throw new \Exception("Unsupported LinkedIn Page content type: {$contentType?->value}"), }; @@ -219,6 +221,77 @@ private function publishCarousel(string $organizationUrn, ?string $content, $med ]; } + /** + * The title shown on a LinkedIn document (PDF carousel) post. Falls back + * to the uploaded file name, then a generic label, so it's never empty. + */ + private function resolveDocumentTitle(PostPlatform $postPlatform): string + { + $title = data_get($postPlatform->meta, 'document_title'); + + if (filled($title)) { + return (string) $title; + } + + return $postPlatform->post->mediaItems->first()?->original_filename ?? 'Document'; + } + + private function publishDocument(string $organizationUrn, ?string $content, $mediaCollection, string $title, $account): array + { + $document = $mediaCollection->first(fn ($media) => $media->isDocument()); + + if (! $document) { + throw new \Exception('No PDF document for LinkedIn Page document post'); + } + + $documentUrn = $this->uploadDocument($document, $organizationUrn); + + if (! $documentUrn) { + throw new \Exception('LinkedIn Page document upload failed'); + } + + $payload = [ + 'author' => $organizationUrn, + 'commentary' => $content ?? '', + 'visibility' => 'PUBLIC', + 'distribution' => [ + 'feedDistribution' => 'MAIN_FEED', + 'targetEntities' => [], + 'thirdPartyDistributionChannels' => [], + ], + 'lifecycleState' => 'PUBLISHED', + 'content' => [ + 'media' => [ + 'id' => $documentUrn, + 'title' => $title, + ], + ], + ]; + + $response = $this->getHttpClient() + ->post("{$this->baseUrl}/rest/posts", $payload); + + if ($response->failed()) { + Log::error('LinkedIn Page document post creation failed', [ + 'status' => $response->status(), + 'body' => $this->redactResponseBody($response->body()), + ]); + $this->handleApiError($response); + } + + $postId = $response->header('x-restli-id'); + + $username = $account->username; + $postUrl = $username + ? "https://www.linkedin.com/company/{$username}/posts/" + : "https://www.linkedin.com/feed/update/{$postId}"; + + return [ + 'id' => $postId ?? 'unknown', + 'url' => $postId ? $postUrl : null, + ]; + } + private function getHttpClient(): PendingRequest { return $this->socialHttp()->withToken($this->accessToken) @@ -450,6 +523,98 @@ private function waitForVideoProcessing(string $videoUrn, int $maxAttempts = 30) Log::warning('LinkedIn Page video processing timeout, proceeding anyway'); } + private function uploadDocument($mediaItem, string $ownerUrn): ?string + { + // Step 1: Initialize upload + $initResponse = $this->getHttpClient() + ->post("{$this->baseUrl}/rest/documents?action=initializeUpload", [ + 'initializeUploadRequest' => [ + 'owner' => $ownerUrn, + ], + ]); + + if ($initResponse->failed()) { + Log::error('LinkedIn Page document init failed', ['body' => $this->redactResponseBody($initResponse->body())]); + $this->handleApiError($initResponse); + } + + $initData = $initResponse->json(); + $uploadUrl = $initData['value']['uploadUrl'] ?? null; + $documentUrn = $initData['value']['document'] ?? null; + + if (! $uploadUrl || ! $documentUrn) { + throw new \Exception('LinkedIn Page document upload init missing uploadUrl or document URN'); + } + + // Step 2: Upload the PDF in a single request (Documents API is not chunked) + $tempFile = tempnam(sys_get_temp_dir(), 'lip_document_'); + + try { + $downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url); + + if ($downloadResponse->failed()) { + throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status()); + } + + $stream = fopen($tempFile, 'r'); + + $uploadResponse = Http::withToken($this->accessToken) + ->withHeaders([ + 'Content-Type' => 'application/pdf', + ]) + ->timeout(600) + ->withBody($stream, 'application/pdf') + ->put($uploadUrl); + + if (is_resource($stream)) { + fclose($stream); + } + + if ($uploadResponse->failed()) { + Log::error('LinkedIn Page document upload failed', ['body' => $this->redactResponseBody($uploadResponse->body())]); + $this->handleApiError($uploadResponse); + } + } finally { + @unlink($tempFile); + } + + // Step 3: Wait for processing (SYNCHRONOUS_UPLOAD is not supported) + $this->waitForDocumentProcessing($documentUrn); + + return $documentUrn; + } + + private function waitForDocumentProcessing(string $documentUrn, int $maxAttempts = 30): void + { + $encodedUrn = urlencode($documentUrn); + + for ($i = 0; $i < $maxAttempts; $i++) { + $response = $this->getHttpClient() + ->get("{$this->baseUrl}/rest/documents/{$encodedUrn}"); + + if ($response->failed()) { + Log::warning('LinkedIn Page document status check failed', ['attempt' => $i]); + sleep(5); + + continue; + } + + $status = data_get($response->json(), 'status', 'UNKNOWN'); + + if ($status === 'AVAILABLE') { + return; + } + + if ($status === 'PROCESSING_FAILED') { + throw new \Exception('LinkedIn Page document processing failed'); + } + + sleep(5); + } + + Log::warning('LinkedIn Page document processing timeout, proceeding anyway'); + } + private function handleApiError(Response $response): never { throw LinkedInPublishException::fromApiResponse($response); diff --git a/app/Services/Social/LinkedInPublisher.php b/app/Services/Social/LinkedInPublisher.php index 8053d458..dee69839 100644 --- a/app/Services/Social/LinkedInPublisher.php +++ b/app/Services/Social/LinkedInPublisher.php @@ -57,6 +57,7 @@ public function publish(PostPlatform $postPlatform): array try { return match ($contentType) { ContentType::LinkedInCarousel => $this->publishCarousel($personUrn, $content, $postPlatform->post->mediaItems), + ContentType::LinkedInDocument => $this->publishDocument($personUrn, $content, $postPlatform->post->mediaItems, $this->resolveDocumentTitle($postPlatform)), ContentType::LinkedInPost => $this->publishPost($personUrn, $content, $postPlatform->post->mediaItems), default => throw new \Exception("Unsupported LinkedIn content type: {$contentType?->value}"), }; @@ -82,6 +83,7 @@ private function retryWithRefresh(PostPlatform $postPlatform, ?string $content, return match ($contentType) { ContentType::LinkedInCarousel => $this->publishCarousel($personUrn, $content, $postPlatform->post->mediaItems), + ContentType::LinkedInDocument => $this->publishDocument($personUrn, $content, $postPlatform->post->mediaItems, $this->resolveDocumentTitle($postPlatform)), ContentType::LinkedInPost => $this->publishPost($personUrn, $content, $postPlatform->post->mediaItems), default => throw new \Exception("Unsupported LinkedIn content type: {$contentType?->value}"), }; @@ -200,6 +202,73 @@ private function publishCarousel(string $personUrn, ?string $content, $mediaColl ]; } + /** + * The title shown on a LinkedIn document (PDF carousel) post. Falls back + * to the uploaded file name, then a generic label, so it's never empty — + * LinkedIn renders the title beneath the document. + */ + private function resolveDocumentTitle(PostPlatform $postPlatform): string + { + $title = data_get($postPlatform->meta, 'document_title'); + + if (filled($title)) { + return (string) $title; + } + + return $postPlatform->post->mediaItems->first()?->original_filename ?? 'Document'; + } + + private function publishDocument(string $personUrn, ?string $content, $mediaCollection, string $title): array + { + $document = $mediaCollection->first(fn ($media) => $media->isDocument()); + + if (! $document) { + throw new \Exception('No PDF document for LinkedIn document post'); + } + + $documentUrn = $this->uploadDocument($document, $personUrn); + + if (! $documentUrn) { + throw new \Exception('LinkedIn document upload failed'); + } + + $payload = [ + 'author' => $personUrn, + 'commentary' => $content ?? '', + 'visibility' => 'PUBLIC', + 'distribution' => [ + 'feedDistribution' => 'MAIN_FEED', + 'targetEntities' => [], + 'thirdPartyDistributionChannels' => [], + ], + 'lifecycleState' => 'PUBLISHED', + 'content' => [ + 'media' => [ + 'id' => $documentUrn, + 'title' => $title, + ], + ], + ]; + + $response = $this->getHttpClient() + ->post("{$this->baseUrl}/rest/posts", $payload); + + if ($response->failed()) { + Log::error('LinkedIn document post creation failed', [ + 'status' => $response->status(), + 'body' => $this->redactResponseBody($response->body()), + ]); + $this->handleApiError($response); + } + + $postId = $response->header('x-restli-id'); + + return [ + 'id' => $postId ?? 'unknown', + 'url' => $postId ? "https://www.linkedin.com/feed/update/{$postId}" : null, + ]; + } + private function getHttpClient(): PendingRequest { return $this->socialHttp()->withToken($this->accessToken) @@ -431,6 +500,98 @@ private function waitForVideoProcessing(string $videoUrn, int $maxAttempts = 30) Log::warning('LinkedIn video processing timeout, proceeding anyway'); } + private function uploadDocument($mediaItem, string $ownerUrn): ?string + { + // Step 1: Initialize upload + $initResponse = $this->getHttpClient() + ->post("{$this->baseUrl}/rest/documents?action=initializeUpload", [ + 'initializeUploadRequest' => [ + 'owner' => $ownerUrn, + ], + ]); + + if ($initResponse->failed()) { + Log::error('LinkedIn document init failed', ['body' => $this->redactResponseBody($initResponse->body())]); + $this->handleApiError($initResponse); + } + + $initData = $initResponse->json(); + $uploadUrl = $initData['value']['uploadUrl'] ?? null; + $documentUrn = $initData['value']['document'] ?? null; + + if (! $uploadUrl || ! $documentUrn) { + throw new \Exception('LinkedIn document upload init missing uploadUrl or document URN'); + } + + // Step 2: Upload the PDF in a single request (Documents API is not chunked) + $tempFile = tempnam(sys_get_temp_dir(), 'li_document_'); + + try { + $downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url); + + if ($downloadResponse->failed()) { + throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status()); + } + + $stream = fopen($tempFile, 'r'); + + $uploadResponse = Http::withToken($this->accessToken) + ->withHeaders([ + 'Content-Type' => 'application/pdf', + ]) + ->timeout(600) + ->withBody($stream, 'application/pdf') + ->put($uploadUrl); + + if (is_resource($stream)) { + fclose($stream); + } + + if ($uploadResponse->failed()) { + Log::error('LinkedIn document upload failed', ['body' => $this->redactResponseBody($uploadResponse->body())]); + $this->handleApiError($uploadResponse); + } + } finally { + @unlink($tempFile); + } + + // Step 3: Wait for processing (SYNCHRONOUS_UPLOAD is not supported) + $this->waitForDocumentProcessing($documentUrn); + + return $documentUrn; + } + + private function waitForDocumentProcessing(string $documentUrn, int $maxAttempts = 30): void + { + $encodedUrn = urlencode($documentUrn); + + for ($i = 0; $i < $maxAttempts; $i++) { + $response = $this->getHttpClient() + ->get("{$this->baseUrl}/rest/documents/{$encodedUrn}"); + + if ($response->failed()) { + Log::warning('LinkedIn document status check failed', ['attempt' => $i]); + sleep(5); + + continue; + } + + $status = data_get($response->json(), 'status', 'UNKNOWN'); + + if ($status === 'AVAILABLE') { + return; + } + + if ($status === 'PROCESSING_FAILED') { + throw new \Exception('LinkedIn document processing failed'); + } + + sleep(5); + } + + Log::warning('LinkedIn document processing timeout, proceeding anyway'); + } + private function handleApiError(Response $response): never { throw LinkedInPublishException::fromApiResponse($response); diff --git a/app/Support/PostPlatformMetaRules.php b/app/Support/PostPlatformMetaRules.php index d7a12682..00f6d7b2 100644 --- a/app/Support/PostPlatformMetaRules.php +++ b/app/Support/PostPlatformMetaRules.php @@ -45,6 +45,9 @@ public static function rules(): array // Instagram / Facebook 'platforms.*.meta.aspect_ratio' => ['sometimes', 'nullable', 'string', Rule::enum(AspectRatio::class)], + // LinkedIn — title shown on a document (PDF carousel) post + 'platforms.*.meta.document_title' => ['sometimes', 'nullable', 'string', 'max:300'], + // TikTok 'platforms.*.meta.privacy_level' => ['sometimes', 'nullable', 'string', Rule::in(self::TIKTOK_PRIVACY_LEVELS)], 'platforms.*.meta.auto_add_music' => ['sometimes', 'boolean'], diff --git a/config/trypost.php b/config/trypost.php index 761be98f..1b204b7e 100644 --- a/config/trypost.php +++ b/config/trypost.php @@ -46,6 +46,8 @@ 'max_size_mb' => [ 'image' => (int) env('MEDIA_IMAGE_MAX_SIZE_MB', 10), 'video' => (int) env('MEDIA_VIDEO_MAX_SIZE_MB', 1024), + // LinkedIn caps document (PDF carousel) uploads at 100MB. + 'document' => (int) env('MEDIA_DOCUMENT_MAX_SIZE_MB', 100), ], ], diff --git a/lang/en/posts.php b/lang/en/posts.php index d3f3f7dd..29b1c5fb 100644 --- a/lang/en/posts.php +++ b/lang/en/posts.php @@ -143,6 +143,7 @@ 'variant' => [ 'post' => 'Post', 'carousel' => 'Carousel', + 'document' => 'Document', ], ], 'pinterest' => [ @@ -188,9 +189,11 @@ 'min_files_required' => 'This post type requires at least :min media files (you have :current).', 'no_video_allowed' => 'This post type does not accept videos.', 'no_image_allowed' => 'This post type accepts only videos.', + 'no_document_allowed' => 'This post type does not accept PDF documents.', 'gif_not_allowed' => 'This platform does not accept GIF. Remove the GIF or choose a different network.', 'image_too_large' => 'Image exceeds the :max limit for this post type (yours is :current).', 'video_too_large' => 'Video exceeds the :max limit for this post type (yours is :current).', + 'document_too_large' => 'PDF exceeds the :max limit for this post type (yours is :current).', 'video_too_long' => 'Video is :current long, but this post type allows up to :max.', 'aspect_ratio_too_narrow' => 'Aspect ratio :current is too tall for this post type (min :min).', 'aspect_ratio_too_wide' => 'Aspect ratio :current is too wide for this post type (max :max).', @@ -472,6 +475,14 @@ 'label' => 'Carousel', 'description' => 'Swipeable images', ], + 'linkedin_document' => [ + 'label' => 'Document', + 'description' => 'Swipeable PDF carousel', + ], + 'linkedin_page_document' => [ + 'label' => 'Document', + 'description' => 'Swipeable PDF carousel', + ], 'facebook_post' => [ 'label' => 'Post', 'description' => 'Standard post on your page', diff --git a/lang/es/posts.php b/lang/es/posts.php index c52e8895..4a8d3096 100644 --- a/lang/es/posts.php +++ b/lang/es/posts.php @@ -143,6 +143,7 @@ 'variant' => [ 'post' => 'Publicación', 'carousel' => 'Carrusel', + 'document' => 'Documento', ], ], 'pinterest' => [ @@ -188,9 +189,11 @@ 'min_files_required' => 'Este tipo requiere al menos :min archivos (tienes :current).', 'no_video_allowed' => 'Este tipo no acepta videos.', 'no_image_allowed' => 'Este tipo acepta solo videos.', + 'no_document_allowed' => 'Este tipo no acepta documentos PDF.', 'gif_not_allowed' => 'Esta red no acepta GIF. Elimínalo o selecciona otra red.', 'image_too_large' => 'La imagen supera el límite de :max (la tuya es :current).', 'video_too_large' => 'El video supera el límite de :max (el tuyo es :current).', + 'document_too_large' => 'El PDF supera el límite de :max (el tuyo es :current).', 'video_too_long' => 'El video dura :current, pero este tipo permite hasta :max.', 'aspect_ratio_too_narrow' => 'La proporción :current es demasiado alta (mínimo :min).', 'aspect_ratio_too_wide' => 'La proporción :current es demasiado ancha (máximo :max).', @@ -472,6 +475,14 @@ 'label' => 'Carrusel', 'description' => 'Imágenes deslizables', ], + 'linkedin_document' => [ + 'label' => 'Documento', + 'description' => 'Carrusel PDF deslizable', + ], + 'linkedin_page_document' => [ + 'label' => 'Documento', + 'description' => 'Carrusel PDF deslizable', + ], 'facebook_post' => [ 'label' => 'Post', 'description' => 'Post estándar en tu página', diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.php index 3b580dcb..71630476 100644 --- a/lang/pt-BR/posts.php +++ b/lang/pt-BR/posts.php @@ -143,6 +143,7 @@ 'variant' => [ 'post' => 'Post', 'carousel' => 'Carrossel', + 'document' => 'Documento', ], ], 'pinterest' => [ @@ -188,9 +189,11 @@ 'min_files_required' => 'Este tipo exige pelo menos :min arquivos (você tem :current).', 'no_video_allowed' => 'Este tipo não aceita vídeos.', 'no_image_allowed' => 'Este tipo aceita apenas vídeos.', + 'no_document_allowed' => 'Este tipo não aceita documentos PDF.', 'gif_not_allowed' => 'Esta rede não aceita GIF. Remova o GIF ou escolha outra rede.', 'image_too_large' => 'A imagem passa do limite de :max (a sua tem :current).', 'video_too_large' => 'O vídeo passa do limite de :max (o seu tem :current).', + 'document_too_large' => 'O PDF passa do limite de :max (o seu tem :current).', 'video_too_long' => 'O vídeo dura :current, mas este tipo permite no máximo :max.', 'aspect_ratio_too_narrow' => 'A proporção :current está muito alta (mínimo :min).', 'aspect_ratio_too_wide' => 'A proporção :current está muito larga (máximo :max).', @@ -472,6 +475,14 @@ 'label' => 'Carrossel', 'description' => 'Imagens deslizáveis', ], + 'linkedin_document' => [ + 'label' => 'Documento', + 'description' => 'Carrossel PDF deslizável', + ], + 'linkedin_page_document' => [ + 'label' => 'Documento', + 'description' => 'Carrossel PDF deslizável', + ], 'facebook_post' => [ 'label' => 'Post', 'description' => 'Post padrão na sua página', diff --git a/resources/js/components/assets/GalleryBrowser.vue b/resources/js/components/assets/GalleryBrowser.vue index 6095ac50..3ef9f68e 100644 --- a/resources/js/components/assets/GalleryBrowser.vue +++ b/resources/js/components/assets/GalleryBrowser.vue @@ -1,6 +1,6 @@ @@ -94,23 +87,14 @@ const warning = computed(() => getMediaValidationWarning(props.contentType, prop -
-

{{ $t('posts.form.linkedin.variant_label') }}

-
- -
+
+

{{ $t('posts.form.linkedin.document_title') }}

+

0) { return { key: 'no_document_allowed', params: {} }; } + if (rules.forbidsMixedMedia && videos.length > 0 && images.length > 0) { + return { key: 'no_mixed_media', params: {} }; + } + if (rules.acceptDocuments && documents.length > 0 && total > 1) { + return { key: 'document_not_alone', params: {} }; + } if (! rules.acceptsGif && gifs.length > 0) { return { key: 'gif_not_allowed', params: {} }; } diff --git a/resources/js/composables/useMediaRules.ts b/resources/js/composables/useMediaRules.ts index 24bdbdfc..6840f6f3 100644 --- a/resources/js/composables/useMediaRules.ts +++ b/resources/js/composables/useMediaRules.ts @@ -60,39 +60,18 @@ const CONTENT_TYPE_RULES: Record = { aspectRatioMin: 0.5, aspectRatioMax: 0.6, }, - // LinkedIn + // LinkedIn — one type per account kind; the publish format (single image, + // multi-image, video, or PDF document) is inferred from the attached media. + // Images (up to 20) XOR one video XOR one PDF, never mixed. linkedin_post: { - maxFiles: 1, acceptImages: true, acceptVideos: true, requiresMedia: false, - acceptsGif: false, - maxImageBytes: 5 * MB, maxVideoBytes: 5 * GB, maxVideoDurationSec: 10 * 60, - }, - linkedin_carousel: { - maxFiles: 20, acceptImages: true, acceptVideos: false, requiresMedia: true, - acceptsGif: false, - maxImageBytes: 5 * MB, - aspectRatioMin: 0.5, aspectRatioMax: 1, + maxFiles: 20, acceptImages: true, acceptVideos: true, acceptDocuments: true, + requiresMedia: false, acceptsGif: false, forbidsMixedMedia: true, + maxImageBytes: 5 * MB, maxVideoBytes: 5 * GB, maxVideoDurationSec: 10 * 60, maxDocumentBytes: 100 * MB, }, linkedin_page_post: { - maxFiles: 1, acceptImages: true, acceptVideos: true, requiresMedia: false, - acceptsGif: false, - maxImageBytes: 5 * MB, maxVideoBytes: 5 * GB, maxVideoDurationSec: 10 * 60, - }, - linkedin_page_carousel: { - maxFiles: 20, acceptImages: true, acceptVideos: false, requiresMedia: true, - acceptsGif: false, - maxImageBytes: 5 * MB, - aspectRatioMin: 0.5, aspectRatioMax: 1, - }, - // Document (PDF) posts — the swipeable LinkedIn carousel. One PDF, up to 100MB. - linkedin_document: { - maxFiles: 1, acceptImages: false, acceptVideos: false, acceptDocuments: true, requiresMedia: true, - acceptsGif: false, - maxDocumentBytes: 100 * MB, - }, - linkedin_page_document: { - maxFiles: 1, acceptImages: false, acceptVideos: false, acceptDocuments: true, requiresMedia: true, - acceptsGif: false, - maxDocumentBytes: 100 * MB, + maxFiles: 20, acceptImages: true, acceptVideos: true, acceptDocuments: true, + requiresMedia: false, acceptsGif: false, forbidsMixedMedia: true, + maxImageBytes: 5 * MB, maxVideoBytes: 5 * GB, maxVideoDurationSec: 10 * 60, maxDocumentBytes: 100 * MB, }, // TikTok diff --git a/resources/js/composables/usePlatformLogo.ts b/resources/js/composables/usePlatformLogo.ts index 112e3cc0..4b0baf68 100644 --- a/resources/js/composables/usePlatformLogo.ts +++ b/resources/js/composables/usePlatformLogo.ts @@ -39,8 +39,8 @@ const PLATFORM_CONTENT_TYPES: Record = { 'instagram_reel', 'instagram_story', ], - linkedin: ['linkedin_post', 'linkedin_carousel', 'linkedin_document'], - 'linkedin-page': ['linkedin_page_post', 'linkedin_page_carousel', 'linkedin_page_document'], + linkedin: ['linkedin_post'], + 'linkedin-page': ['linkedin_page_post'], facebook: ['facebook_post', 'facebook_reel', 'facebook_story'], tiktok: ['tiktok_video'], youtube: ['youtube_short'], diff --git a/resources/js/composables/usePostCompliance.ts b/resources/js/composables/usePostCompliance.ts index 1390a817..6f24118d 100644 --- a/resources/js/composables/usePostCompliance.ts +++ b/resources/js/composables/usePostCompliance.ts @@ -24,8 +24,8 @@ export const PLATFORM_VARIANTS: Record = { [Platform.Facebook]: [ContentType.FacebookPost, ContentType.FacebookReel, ContentType.FacebookStory], [Platform.Instagram]: [ContentType.InstagramFeed, ContentType.InstagramReel, ContentType.InstagramStory], [Platform.InstagramFacebook]: [ContentType.InstagramFeed, ContentType.InstagramReel, ContentType.InstagramStory], - [Platform.LinkedIn]: [ContentType.LinkedInPost, ContentType.LinkedInCarousel, ContentType.LinkedInDocument], - [Platform.LinkedInPage]: [ContentType.LinkedInPagePost, ContentType.LinkedInPageCarousel, ContentType.LinkedInPageDocument], + [Platform.LinkedIn]: [ContentType.LinkedInPost], + [Platform.LinkedInPage]: [ContentType.LinkedInPagePost], [Platform.TikTok]: [ContentType.TikTokVideo, ContentType.TikTokPhoto], [Platform.Pinterest]: [ContentType.PinterestPin, ContentType.PinterestVideoPin, ContentType.PinterestCarousel], }; @@ -101,6 +101,7 @@ export const getMediaIncompatibilityReason = ( if (!rules.acceptVideos && videos.length > 0) return trans('posts.edit.compliance.no_videos'); if (!rules.acceptImages && images.length > 0) return trans('posts.edit.compliance.no_images'); if (!rules.acceptDocuments && documents.length > 0) return trans('posts.edit.compliance.no_documents'); + if (rules.acceptDocuments && documents.length > 0 && total > 1) return trans('posts.edit.compliance.document_not_alone'); if (rules.forbidsMixedMedia && videos.length > 0 && images.length > 0) return trans('posts.edit.compliance.no_mixed_media'); if (!rules.acceptsGif && gifs.length > 0) return trans('posts.edit.compliance.no_gifs'); if (total > rules.maxFiles) return trans('posts.edit.compliance.too_many_files', { max: String(rules.maxFiles) }); diff --git a/resources/js/pages/accounts/LinkedInPageSelect.vue b/resources/js/pages/accounts/LinkedInPageSelect.vue deleted file mode 100644 index b79c1d07..00000000 --- a/resources/js/pages/accounts/LinkedInPageSelect.vue +++ /dev/null @@ -1,111 +0,0 @@ - - - diff --git a/resources/js/pages/accounts/LinkedInSelect.vue b/resources/js/pages/accounts/LinkedInSelect.vue new file mode 100644 index 00000000..c728986e --- /dev/null +++ b/resources/js/pages/accounts/LinkedInSelect.vue @@ -0,0 +1,186 @@ + + + diff --git a/resources/js/types/content-type.ts b/resources/js/types/content-type.ts index a6c2b9e8..22462b69 100644 --- a/resources/js/types/content-type.ts +++ b/resources/js/types/content-type.ts @@ -3,11 +3,7 @@ export const ContentType = { InstagramStory: 'instagram_story', InstagramReel: 'instagram_reel', LinkedInPost: 'linkedin_post', - LinkedInCarousel: 'linkedin_carousel', - LinkedInDocument: 'linkedin_document', LinkedInPagePost: 'linkedin_page_post', - LinkedInPageCarousel: 'linkedin_page_carousel', - LinkedInPageDocument: 'linkedin_page_document', FacebookPost: 'facebook_post', FacebookReel: 'facebook_reel', FacebookStory: 'facebook_story', diff --git a/routes/app.php b/routes/app.php index 01253dc2..fff701d0 100644 --- a/routes/app.php +++ b/routes/app.php @@ -36,7 +36,6 @@ use App\Http\Controllers\Auth\InstagramController; use App\Http\Controllers\Auth\InstagramFacebookController; use App\Http\Controllers\Auth\LinkedInController; -use App\Http\Controllers\Auth\LinkedInPageController; use App\Http\Controllers\Auth\MastodonController; use App\Http\Controllers\Auth\PinterestController; use App\Http\Controllers\Auth\SocialController; @@ -80,11 +79,8 @@ Route::middleware(['auth'])->group(function () { Route::get('connect/linkedin', [LinkedInController::class, 'connect'])->name('app.social.linkedin.connect'); Route::get('accounts/linkedin/callback', [LinkedInController::class, 'callback'])->name('app.social.linkedin.callback'); - - Route::get('connect/linkedin-page', [LinkedInPageController::class, 'connect'])->name('app.social.linkedin-page.connect'); - Route::get('accounts/linkedin-page/callback', [LinkedInPageController::class, 'callback'])->name('app.social.linkedin-page.callback'); - Route::get('accounts/linkedin-page/select', [LinkedInPageController::class, 'selectPage'])->name('app.social.linkedin-page.select-page'); - Route::post('accounts/linkedin-page/select', [LinkedInPageController::class, 'select'])->name('app.social.linkedin-page.select'); + Route::get('accounts/linkedin/select', [LinkedInController::class, 'selectIdentity'])->name('app.social.linkedin.select-identity'); + Route::post('accounts/linkedin/select', [LinkedInController::class, 'select'])->name('app.social.linkedin.select'); Route::get('connect/x', [XController::class, 'connect'])->name('app.social.x.connect'); Route::get('accounts/x/callback', [XController::class, 'callback'])->name('app.social.x.callback'); diff --git a/tests/Feature/Api/PostApiPlatformMetaTest.php b/tests/Feature/Api/PostApiPlatformMetaTest.php index dd16ca79..b41aaef4 100644 --- a/tests/Feature/Api/PostApiPlatformMetaTest.php +++ b/tests/Feature/Api/PostApiPlatformMetaTest.php @@ -59,7 +59,7 @@ 'content' => 'Check our latest deck', 'platforms' => [[ 'social_account_id' => $linkedin->id, - 'content_type' => ContentType::LinkedInDocument->value, + 'content_type' => ContentType::LinkedInPost->value, 'meta' => ['document_title' => 'Q2 Report'], ]], ]) @@ -83,52 +83,28 @@ ]); $platform = PostPlatform::factory()->create([ 'post_id' => $post->id, 'social_account_id' => $linkedin->id, - 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInDocument, 'enabled' => true, + 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true, ]); $this->withHeaders($this->headers) ->putJson(route('api.posts.update', $post), [ 'status' => PostStatus::Publishing->value, - 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::LinkedInDocument->value]], + 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::LinkedInPost->value]], ]) ->assertOk(); Queue::assertPushed(PublishPost::class); }); -it('rejects publishing a LinkedIn document post whose media is an image, not a PDF', function () { +it('rejects publishing a LinkedIn post that mixes a PDF with an image', function () { $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]); $post = Post::factory()->create([ 'workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, - 'media' => [[ - 'id' => 'img-1', 'path' => 'medias/slide.jpg', 'url' => 'https://example.com/slide.jpg', - 'type' => 'image', 'mime_type' => 'image/jpeg', 'original_filename' => 'slide.jpg', - ]], - ]); - $platform = PostPlatform::factory()->create([ - 'post_id' => $post->id, 'social_account_id' => $linkedin->id, - 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInDocument, 'enabled' => true, - ]); - - $this->withHeaders($this->headers) - ->putJson(route('api.posts.update', $post), [ - 'status' => PostStatus::Publishing->value, - 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::LinkedInDocument->value]], - ]) - ->assertUnprocessable() - ->assertJsonValidationErrors(['platforms.0.content_type']); -}); - -it('rejects publishing a regular LinkedIn post that has a PDF attached', function () { - $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]); - $post = Post::factory()->create([ - 'workspace_id' => $this->workspace->id, - 'user_id' => $this->user->id, - 'media' => [[ - 'id' => 'doc-1', 'path' => 'medias/deck.pdf', 'url' => 'https://example.com/deck.pdf', - 'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf', - ]], + 'media' => [ + ['id' => 'doc-1', 'path' => 'medias/deck.pdf', 'url' => 'https://example.com/deck.pdf', 'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf'], + ['id' => 'img-1', 'path' => 'medias/slide.jpg', 'url' => 'https://example.com/slide.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg', 'original_filename' => 'slide.jpg'], + ], ]); $platform = PostPlatform::factory()->create([ 'post_id' => $post->id, 'social_account_id' => $linkedin->id, @@ -159,7 +135,7 @@ ]); $platform = PostPlatform::factory()->create([ 'post_id' => $post->id, 'social_account_id' => $linkedin->id, - 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInDocument, 'enabled' => true, + 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true, ]); $this->withHeaders($this->headers) @@ -172,31 +148,6 @@ Queue::assertPushed(PublishPost::class); }); -it('rejects publishing a misconfigured post even when content_type is not resubmitted', function () { - $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]); - $post = Post::factory()->create([ - 'workspace_id' => $this->workspace->id, - 'user_id' => $this->user->id, - 'media' => [[ - 'id' => 'doc-1', 'path' => 'medias/deck.pdf', 'url' => 'https://example.com/deck.pdf', - 'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf', - ]], - ]); - // Stored as a regular post but carrying a PDF — the client publishes without resubmitting content_type. - $platform = PostPlatform::factory()->create([ - 'post_id' => $post->id, 'social_account_id' => $linkedin->id, - 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true, - ]); - - $this->withHeaders($this->headers) - ->putJson(route('api.posts.update', $post), [ - 'status' => PostStatus::Publishing->value, - 'platforms' => [['id' => $platform->id]], - ]) - ->assertUnprocessable() - ->assertJsonValidationErrors(['platforms.0.content_type']); -}); - it('rejects only the platform that cannot take a PDF in a multi-platform post', function () { $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]); $x = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::X]); @@ -212,7 +163,7 @@ ]); $linkedinPlatform = PostPlatform::factory()->create([ 'post_id' => $post->id, 'social_account_id' => $linkedin->id, - 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInDocument, 'enabled' => true, + 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true, ]); $xPlatform = PostPlatform::factory()->create([ 'post_id' => $post->id, 'social_account_id' => $x->id, @@ -223,7 +174,7 @@ ->putJson(route('api.posts.update', $post), [ 'status' => PostStatus::Publishing->value, 'platforms' => [ - ['id' => $linkedinPlatform->id, 'content_type' => ContentType::LinkedInDocument->value], + ['id' => $linkedinPlatform->id, 'content_type' => ContentType::LinkedInPost->value], ['id' => $xPlatform->id, 'content_type' => ContentType::XPost->value], ], ]) diff --git a/tests/Feature/Automation/Node/GenerateNodeTest.php b/tests/Feature/Automation/Node/GenerateNodeTest.php index 93e37e44..f8fa5673 100644 --- a/tests/Feature/Automation/Node/GenerateNodeTest.php +++ b/tests/Feature/Automation/Node/GenerateNodeTest.php @@ -285,7 +285,7 @@ $action = app(RunGenerateNode::class); $accountsConfig = [ - ['social_account_id' => '1', 'content_type' => ContentType::LinkedInPost->value, 'meta' => []], + ['social_account_id' => '1', 'content_type' => ContentType::PinterestPin->value, 'meta' => []], ['social_account_id' => '2', 'content_type' => ContentType::InstagramReel->value, 'meta' => []], ]; diff --git a/tests/Feature/Jobs/PublishToSocialPlatformTest.php b/tests/Feature/Jobs/PublishToSocialPlatformTest.php index 31c96aff..cb3ff6d6 100644 --- a/tests/Feature/Jobs/PublishToSocialPlatformTest.php +++ b/tests/Feature/Jobs/PublishToSocialPlatformTest.php @@ -5,6 +5,7 @@ use App\Enums\Post\Status as PostStatus; use App\Enums\PostPlatform\ContentType; use App\Enums\PostPlatform\Status as PlatformStatus; +use App\Enums\SocialAccount\Platform; use App\Enums\SocialAccount\Status as AccountStatus; use App\Enums\UserWorkspace\Role; use App\Events\PostPlatformStatusUpdated; @@ -20,6 +21,7 @@ use App\Models\User; use App\Models\Workspace; use App\Services\Social\ConnectionVerifier; +use App\Services\Social\LinkedInPagePublisher; use App\Services\Social\LinkedInPublisher; use Carbon\Carbon; use Illuminate\Support\Facades\Bus; @@ -81,6 +83,37 @@ expect($this->postPlatform->platform_url)->toBe('https://linkedin.com/post/123'); }); +test('publish job dispatches a linkedin-page post to the page publisher', function () { + Event::fake(); + + $workspace = Workspace::factory()->create(['user_id' => $this->user->id]); + $pageAccount = SocialAccount::factory()->linkedinPage()->create(['workspace_id' => $workspace->id]); + $post = Post::factory()->scheduled()->create([ + 'workspace_id' => $workspace->id, + 'user_id' => $this->user->id, + ]); + $pagePostPlatform = PostPlatform::factory()->create([ + 'post_id' => $post->id, + 'social_account_id' => $pageAccount->id, + 'platform' => Platform::LinkedInPage, + 'content_type' => ContentType::LinkedInPagePost, + 'enabled' => true, + ]); + + $publisher = Mockery::mock(LinkedInPagePublisher::class); + $publisher->shouldReceive('publish')->once()->andReturn([ + 'id' => 'org-post-1', + 'url' => 'https://linkedin.com/company/post/1', + ]); + $this->app->instance(LinkedInPagePublisher::class, $publisher); + + (new PublishToSocialPlatform($pagePostPlatform))->handle(); + + $pagePostPlatform->refresh(); + expect($pagePostPlatform->status)->toBe(PlatformStatus::Published); + expect($pagePostPlatform->platform_post_id)->toBe('org-post-1'); +}); + test('publish job runs the real document flow end-to-end for a LinkedIn PDF post', function () { Event::fake(); @@ -89,7 +122,7 @@ 'platform_user_id' => 'person-xyz', 'token_expires_at' => now()->addDays(60), ]); - $this->postPlatform->update(['content_type' => ContentType::LinkedInDocument]); + $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]); $this->post->update([ 'content' => 'Our deck', 'media' => [[ diff --git a/tests/Feature/Mcp/AttachMediaFromUrlToolTest.php b/tests/Feature/Mcp/AttachMediaFromUrlToolTest.php index 46a36e7e..1b54bcc0 100644 --- a/tests/Feature/Mcp/AttachMediaFromUrlToolTest.php +++ b/tests/Feature/Mcp/AttachMediaFromUrlToolTest.php @@ -106,7 +106,7 @@ $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]); PostPlatform::factory()->create([ 'post_id' => $this->post->id, 'social_account_id' => $linkedin->id, - 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInDocument, 'enabled' => true, + 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true, ]); $response = TryPostServer::actingAs($this->user) diff --git a/tests/Feature/Mcp/PostPlatformMetaToolTest.php b/tests/Feature/Mcp/PostPlatformMetaToolTest.php index 154f38f7..e4681c7f 100644 --- a/tests/Feature/Mcp/PostPlatformMetaToolTest.php +++ b/tests/Feature/Mcp/PostPlatformMetaToolTest.php @@ -62,7 +62,7 @@ 'content' => 'Check our latest deck', 'platforms' => [[ 'social_account_id' => $linkedin->id, - 'content_type' => ContentType::LinkedInDocument->value, + 'content_type' => ContentType::LinkedInPost->value, 'meta' => ['document_title' => 'Q2 Report'], ]], ]); @@ -187,7 +187,7 @@ ]); PostPlatform::factory()->create([ 'post_id' => $post->id, 'social_account_id' => $linkedin->id, - 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInDocument, 'enabled' => true, + 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true, ]); $uploadToken = (string) Str::uuid(); @@ -233,7 +233,7 @@ ]); PostPlatform::factory()->create([ 'post_id' => $post->id, 'social_account_id' => $linkedin->id, - 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInDocument, 'enabled' => true, + 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true, ]); $response = TryPostServer::actingAs($this->user) @@ -243,55 +243,27 @@ Queue::assertPushed(PublishPost::class); }); -test('publish post rejects a LinkedIn document whose media is an image, not a PDF', function () { +test('publish post rejects a LinkedIn post that mixes a PDF with an image', function () { $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]); $post = Post::factory()->create([ 'workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'status' => PostStatus::Draft, - 'media' => [[ - 'id' => 'img-1', 'path' => 'medias/slide.jpg', 'url' => 'https://example.com/slide.jpg', - 'type' => 'image', 'mime_type' => 'image/jpeg', 'original_filename' => 'slide.jpg', - ]], + 'media' => [ + ['id' => 'doc-1', 'path' => 'medias/deck.pdf', 'url' => 'https://example.com/deck.pdf', 'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf'], + ['id' => 'img-1', 'path' => 'medias/slide.jpg', 'url' => 'https://example.com/slide.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg', 'original_filename' => 'slide.jpg'], + ], ]); PostPlatform::factory()->create([ - 'post_id' => $post->id, 'social_account_id' => $linkedin->id, - 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInDocument, 'enabled' => true, - ]); - - $response = TryPostServer::actingAs($this->user) - ->tool(PublishPostTool::class, ['post_id' => $post->id]); - - $response->assertHasErrors(['Document does not support images.']); -}); - -test('update post rejects scheduling a misconfigured LinkedIn post without resubmitting content_type', function () { - $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]); - - $post = Post::factory()->create([ - 'workspace_id' => $this->workspace->id, - 'user_id' => $this->user->id, - 'status' => PostStatus::Draft, - 'media' => [[ - 'id' => 'doc-1', 'path' => 'medias/deck.pdf', 'url' => 'https://example.com/deck.pdf', - 'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf', - ]], - ]); - $platform = PostPlatform::factory()->create([ 'post_id' => $post->id, 'social_account_id' => $linkedin->id, 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true, ]); $response = TryPostServer::actingAs($this->user) - ->tool(UpdatePostTool::class, [ - 'post_id' => $post->id, - 'status' => PostStatus::Scheduled->value, - 'scheduled_at' => now()->addDay()->toIso8601String(), - 'platforms' => [['id' => $platform->id]], - ]); + ->tool(PublishPostTool::class, ['post_id' => $post->id]); - $response->assertHasErrors(['Post does not support PDF documents.']); + $response->assertHasErrors(['A PDF document must be the only attachment.']); }); test('publish post succeeds for a Discord platform with a channel', function () { diff --git a/tests/Feature/Migrations/CollapseLinkedInContentTypesTest.php b/tests/Feature/Migrations/CollapseLinkedInContentTypesTest.php new file mode 100644 index 00000000..c2afd201 --- /dev/null +++ b/tests/Feature/Migrations/CollapseLinkedInContentTypesTest.php @@ -0,0 +1,51 @@ +create(['content_type' => ContentType::LinkedInPost]); + + foreach (['linkedin_carousel', 'linkedin_document'] as $legacy) { + DB::table('post_platforms')->where('id', $platform->id)->update(['content_type' => $legacy]); + + collapseLinkedInContentTypesMigration()->up(); + + expect(DB::table('post_platforms')->where('id', $platform->id)->value('content_type')) + ->toBe('linkedin_post'); + } +}); + +test('the migration collapses retired linkedin page content types onto linkedin_page_post', function () { + $platform = PostPlatform::factory()->create(['content_type' => ContentType::LinkedInPagePost]); + + foreach (['linkedin_page_carousel', 'linkedin_page_document'] as $legacy) { + DB::table('post_platforms')->where('id', $platform->id)->update(['content_type' => $legacy]); + + collapseLinkedInContentTypesMigration()->up(); + + expect(DB::table('post_platforms')->where('id', $platform->id)->value('content_type')) + ->toBe('linkedin_page_post'); + } +}); + +test('the migration leaves other platforms content types untouched', function () { + $xPost = PostPlatform::factory()->create(['content_type' => ContentType::XPost]); + + collapseLinkedInContentTypesMigration()->up(); + + expect(DB::table('post_platforms')->where('id', $xPost->id)->value('content_type')) + ->toBe(ContentType::XPost->value); +}); diff --git a/tests/Feature/Services/LinkedInPublisherTest.php b/tests/Feature/Services/LinkedInPublisherTest.php deleted file mode 100644 index 7f096426..00000000 --- a/tests/Feature/Services/LinkedInPublisherTest.php +++ /dev/null @@ -1,219 +0,0 @@ -workspace = Workspace::factory()->create(); - $this->socialAccount = SocialAccount::factory()->create([ - 'workspace_id' => $this->workspace->id, - 'platform' => Platform::LinkedIn, - 'platform_user_id' => 'linkedin-123', - 'access_token' => 'test-token', - 'token_expires_at' => now()->addDays(30), - ]); - $this->post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'content' => 'Test LinkedIn post']); - $this->postPlatform = PostPlatform::factory()->create([ - 'post_id' => $this->post->id, - 'social_account_id' => $this->socialAccount->id, - 'content_type' => ContentType::LinkedInPost, - ]); -}); - -test('linkedin publisher publishes text only post', function () { - Http::fake([ - '*/rest/posts' => Http::response(null, 201, ['x-restli-id' => 'urn:li:share:123456']), - ]); - - $publisher = new LinkedInPublisher; - $result = $publisher->publish($this->postPlatform); - - expect($result['id'])->toBe('urn:li:share:123456'); - expect($result['url'])->toBe('https://www.linkedin.com/feed/update/urn:li:share:123456'); -}); - -test('linkedin publisher throws exception for carousel without images', function () { - $this->postPlatform->update(['content_type' => ContentType::LinkedInCarousel]); - - $publisher = new LinkedInPublisher; - - expect(fn () => $publisher->publish($this->postPlatform)) - ->toThrow(Exception::class, 'No valid images for LinkedIn carousel'); -}); - -test('linkedin publisher throws token expired exception on oauth error', function () { - Http::fake([ - '*' => Http::response([ - 'code' => 'REVOKED_ACCESS_TOKEN', - 'message' => 'Token has been revoked', - ], 401), - ]); - - $publisher = new LinkedInPublisher; - - expect(fn () => $publisher->publish($this->postPlatform)) - ->toThrow(TokenExpiredException::class); -}); - -test('linkedin publisher throws token expired exception on expired token', function () { - Http::fake([ - '*' => Http::response([ - 'code' => 'EXPIRED_ACCESS_TOKEN', - 'message' => 'Token has expired', - ], 401), - ]); - - $publisher = new LinkedInPublisher; - - expect(fn () => $publisher->publish($this->postPlatform)) - ->toThrow(TokenExpiredException::class); -}); - -test('linkedin publisher throws token expired exception on invalid token', function () { - Http::fake([ - '*' => Http::response([ - 'code' => 'INVALID_ACCESS_TOKEN', - 'message' => 'Token is invalid', - ], 401), - ]); - - $publisher = new LinkedInPublisher; - - expect(fn () => $publisher->publish($this->postPlatform)) - ->toThrow(TokenExpiredException::class); -}); - -test('linkedin publisher refreshes token when expired', function () { - $this->socialAccount->update([ - 'token_expires_at' => now()->subHour(), - 'refresh_token' => 'refresh-token-123', - ]); - - Http::fake([ - 'https://www.linkedin.com/oauth/v2/accessToken' => Http::response([ - 'access_token' => 'new-access-token', - 'refresh_token' => 'new-refresh-token', - 'expires_in' => 3600, - ], 200), - '*/rest/posts' => Http::response(null, 201, ['x-restli-id' => 'urn:li:share:123456']), - ]); - - $publisher = new LinkedInPublisher; - $result = $publisher->publish($this->postPlatform); - - expect($result['id'])->toBe('urn:li:share:123456'); - $this->socialAccount->refresh(); - expect($this->socialAccount->access_token)->toBe('new-access-token'); -}); - -test('linkedin publisher throws exception when no refresh token', function () { - $this->socialAccount->update([ - 'token_expires_at' => now()->subHour(), - 'refresh_token' => null, - ]); - - $publisher = new LinkedInPublisher; - - expect(fn () => $publisher->publish($this->postPlatform)) - ->toThrow(TokenExpiredException::class, 'No refresh token available'); -}); - -test('linkedin publisher throws exception on api error', function () { - Http::fake([ - '*' => Http::response([ - 'code' => 'INVALID_REQUEST', - 'message' => 'Invalid request parameters', - ], 400), - ]); - - $publisher = new LinkedInPublisher; - - expect(fn () => $publisher->publish($this->postPlatform)) - ->toThrow(Exception::class); -}); - -test('linkedin publisher throws exception for unsupported content type', function () { - $this->postPlatform->update(['content_type' => ContentType::InstagramReel]); - - $publisher = new LinkedInPublisher; - - expect(fn () => $publisher->publish($this->postPlatform)) - ->toThrow(Exception::class, 'Unsupported LinkedIn content type'); -}); - -test('linkedin publisher handles 401 status as token error', function () { - Http::fake([ - '*' => Http::response([ - 'message' => 'Unauthorized', - ], 401), - ]); - - $publisher = new LinkedInPublisher; - - expect(fn () => $publisher->publish($this->postPlatform)) - ->toThrow(TokenExpiredException::class); -}); - -test('linkedin publisher handles token refresh failure', function () { - $this->socialAccount->update([ - 'token_expires_at' => now()->subHour(), - 'refresh_token' => 'refresh-token-123', - ]); - - Http::fake([ - 'https://www.linkedin.com/oauth/v2/accessToken' => Http::response([ - 'code' => 'INVALID_REFRESH_TOKEN', - 'message' => 'Invalid refresh token', - ], 400), - ]); - - $publisher = new LinkedInPublisher; - - expect(fn () => $publisher->publish($this->postPlatform)) - ->toThrow(Exception::class); -}); - -test('linkedin publisher refreshes token when expiring soon', function () { - $this->socialAccount->update([ - 'token_expires_at' => now()->addMinutes(5), - 'refresh_token' => 'refresh-token-123', - ]); - - Http::fake([ - 'https://www.linkedin.com/oauth/v2/accessToken' => Http::response([ - 'access_token' => 'new-access-token', - 'refresh_token' => 'new-refresh-token', - 'expires_in' => 3600, - ], 200), - '*/rest/posts' => Http::response(null, 201, ['x-restli-id' => 'urn:li:share:123456']), - ]); - - $publisher = new LinkedInPublisher; - $result = $publisher->publish($this->postPlatform); - - expect($result['id'])->toBe('urn:li:share:123456'); - $this->socialAccount->refresh(); - expect($this->socialAccount->access_token)->toBe('new-access-token'); -}); - -test('linkedin publisher handles empty post id header', function () { - Http::fake([ - '*/rest/posts' => Http::response(null, 201), - ]); - - $publisher = new LinkedInPublisher; - $result = $publisher->publish($this->postPlatform); - - // When header is empty, id will be empty string or 'unknown' - expect($result)->toHaveKey('id'); - expect($result)->toHaveKey('url'); -}); diff --git a/tests/Feature/Services/Social/LinkedInPagePublisherTest.php b/tests/Feature/Services/Social/LinkedInPagePublisherTest.php index 9f7313f5..c1b5df6e 100644 --- a/tests/Feature/Services/Social/LinkedInPagePublisherTest.php +++ b/tests/Feature/Services/Social/LinkedInPagePublisherTest.php @@ -47,7 +47,7 @@ test('linkedin page publisher can publish text-only post', function () { Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response(null, 201, [ + config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response(null, 201, [ 'x-restli-id' => 'urn:li:share:1234567890', ]), ]); @@ -69,7 +69,7 @@ test('linkedin page publisher uses organization urn', function () { Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response(null, 201, [ + config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response(null, 201, [ 'x-restli-id' => 'urn:li:share:1234567890', ]), ]); @@ -90,7 +90,7 @@ test('linkedin page publisher uses correct headers', function () { Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response(null, 201, [ + config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response(null, 201, [ 'x-restli-id' => 'urn:li:share:1234567890', ]), ]); @@ -107,7 +107,7 @@ test('linkedin page publisher throws exception on api error', function () { Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response([ + config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response([ 'message' => 'Invalid request', 'status' => 400, ], 400), @@ -119,11 +119,11 @@ test('linkedin page publisher throws token expired exception on auth error after retry', function () { Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response([ + config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response([ 'code' => 'EXPIRED_ACCESS_TOKEN', 'message' => 'The token used in the request has expired', ], 401), - 'https://www.linkedin.com/oauth/v2/accessToken' => Http::response([ + config('trypost.platforms.linkedin.oauth_api').'/oauth/v2/accessToken' => Http::response([ 'error' => 'invalid_grant', 'error_description' => 'The refresh token is invalid', ], 400), @@ -137,12 +137,12 @@ $this->socialAccount->update(['token_expires_at' => now()->subHour()]); Http::fake([ - 'https://www.linkedin.com/oauth/v2/accessToken' => Http::response([ + config('trypost.platforms.linkedin.oauth_api').'/oauth/v2/accessToken' => Http::response([ 'access_token' => 'new-access-token', 'refresh_token' => 'new-refresh-token', 'expires_in' => 5184000, ], 200), - 'https://api.linkedin.com/rest/posts' => Http::response(null, 201, [ + config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response(null, 201, [ 'x-restli-id' => 'urn:li:share:1234567890', ]), ]); @@ -171,7 +171,7 @@ $this->socialAccount->update(['token_expires_at' => now()->subHour()]); Http::fake([ - 'https://www.linkedin.com/oauth/v2/accessToken' => Http::response([ + config('trypost.platforms.linkedin.oauth_api').'/oauth/v2/accessToken' => Http::response([ 'error' => 'invalid_grant', 'error_description' => 'The refresh token is invalid', ], 400), @@ -185,7 +185,7 @@ $this->post->update(['content' => '']); Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response(null, 201, [ + config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response(null, 201, [ 'x-restli-id' => 'urn:li:share:1234567890', ]), ]); @@ -199,16 +199,9 @@ }); }); -test('linkedin page publisher throws exception for unsupported content type', function () { - $this->postPlatform->update(['content_type' => ContentType::InstagramFeed]); - - expect(fn () => $this->publisher->publish($this->postPlatform)) - ->toThrow(Exception::class, 'Unsupported LinkedIn Page content type'); -}); - test('linkedin page publisher builds correct company url when username present', function () { Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response(null, 201, [ + config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response(null, 201, [ 'x-restli-id' => 'urn:li:share:1234567890', ]), ]); @@ -222,7 +215,7 @@ $this->socialAccount->update(['username' => null]); Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response(null, 201, [ + config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response(null, 201, [ 'x-restli-id' => 'urn:li:share:1234567890', ]), ]); @@ -286,7 +279,7 @@ test('linkedin page publisher can publish a document (pdf carousel) using organization urn', function () { $this->postPlatform->update([ - 'content_type' => ContentType::LinkedInPageDocument, + 'content_type' => ContentType::LinkedInPagePost, 'meta' => ['document_title' => 'Company Deck'], ]); $this->post->update([ @@ -348,7 +341,7 @@ }); test('linkedin page publisher throws and does not post when document processing fails', function () { - $this->postPlatform->update(['content_type' => ContentType::LinkedInPageDocument]); + $this->postPlatform->update(['content_type' => ContentType::LinkedInPagePost]); $this->post->update([ 'media' => [[ 'id' => 'doc-media-1', 'path' => 'media/2026-01/company-deck.pdf', diff --git a/tests/Feature/Services/Social/LinkedInPublisherTest.php b/tests/Feature/Services/Social/LinkedInPublisherTest.php index a1ee47e7..bf089ffb 100644 --- a/tests/Feature/Services/Social/LinkedInPublisherTest.php +++ b/tests/Feature/Services/Social/LinkedInPublisherTest.php @@ -42,7 +42,7 @@ test('linkedin publisher can publish text-only post', function () { Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response(null, 201, [ + config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, [ 'x-restli-id' => 'urn:li:share:1234567890', ]), ]); @@ -64,7 +64,7 @@ test('linkedin publisher uses correct headers', function () { Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response(null, 201, [ + config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, [ 'x-restli-id' => 'urn:li:share:1234567890', ]), ]); @@ -81,7 +81,7 @@ test('linkedin publisher throws exception on api error', function () { Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response([ + config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response([ 'message' => 'Invalid request', 'status' => 400, ], 400), @@ -93,11 +93,11 @@ test('linkedin publisher throws token expired exception on auth error after retry', function () { Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response([ + config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response([ 'code' => 'EXPIRED_ACCESS_TOKEN', 'message' => 'The token used in the request has expired', ], 401), - 'https://www.linkedin.com/oauth/v2/accessToken' => Http::response([ + config('trypost.platforms.linkedin.oauth_api').'/oauth/v2/accessToken' => Http::response([ 'error' => 'invalid_grant', 'error_description' => 'The refresh token is invalid', ], 400), @@ -111,12 +111,12 @@ $this->socialAccount->update(['token_expires_at' => now()->subHour()]); Http::fake([ - 'https://www.linkedin.com/oauth/v2/accessToken' => Http::response([ + config('trypost.platforms.linkedin.oauth_api').'/oauth/v2/accessToken' => Http::response([ 'access_token' => 'new-access-token', 'refresh_token' => 'new-refresh-token', 'expires_in' => 5184000, ], 200), - 'https://api.linkedin.com/rest/posts' => Http::response(null, 201, [ + config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, [ 'x-restli-id' => 'urn:li:share:1234567890', ]), ]); @@ -145,7 +145,7 @@ $this->socialAccount->update(['token_expires_at' => now()->subHour()]); Http::fake([ - 'https://www.linkedin.com/oauth/v2/accessToken' => Http::response([ + config('trypost.platforms.linkedin.oauth_api').'/oauth/v2/accessToken' => Http::response([ 'error' => 'invalid_grant', 'error_description' => 'The refresh token is invalid', ], 400), @@ -159,7 +159,7 @@ $this->post->update(['content' => '']); Http::fake([ - 'https://api.linkedin.com/rest/posts' => Http::response(null, 201, [ + config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, [ 'x-restli-id' => 'urn:li:share:1234567890', ]), ]); @@ -173,13 +173,6 @@ }); }); -test('linkedin publisher throws exception for unsupported content type', function () { - $this->postPlatform->update(['content_type' => ContentType::InstagramFeed]); - - expect(fn () => $this->publisher->publish($this->postPlatform)) - ->toThrow(Exception::class, 'Unsupported LinkedIn content type'); -}); - test('linkedin publisher can publish post with image', function () { $this->post->update([ 'media' => [ @@ -231,7 +224,7 @@ }); test('linkedin publisher can publish carousel with multiple images', function () { - $this->postPlatform->update(['content_type' => ContentType::LinkedInCarousel]); + $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]); $this->post->update([ 'media' => [ [ @@ -383,7 +376,7 @@ test('linkedin publisher can publish a document (pdf carousel) with a title', function () { $this->postPlatform->update([ - 'content_type' => ContentType::LinkedInDocument, + 'content_type' => ContentType::LinkedInPost, 'meta' => ['document_title' => 'My Slides'], ]); $this->post->update([ @@ -448,7 +441,7 @@ }); test('linkedin publisher document title falls back to the file name', function () { - $this->postPlatform->update(['content_type' => ContentType::LinkedInDocument]); + $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]); $this->post->update([ 'media' => [ [ @@ -497,7 +490,7 @@ }); test('linkedin publisher waits for document processing before posting', function () { - $this->postPlatform->update(['content_type' => ContentType::LinkedInDocument]); + $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]); $this->post->update([ 'media' => [ [ @@ -540,7 +533,7 @@ }); test('linkedin publisher throws and does not post when document processing fails', function () { - $this->postPlatform->update(['content_type' => ContentType::LinkedInDocument]); + $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]); $this->post->update([ 'media' => [ [ @@ -580,7 +573,7 @@ }); test('linkedin publisher throws and does not post when document init fails', function () { - $this->postPlatform->update(['content_type' => ContentType::LinkedInDocument]); + $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]); $this->post->update([ 'media' => [[ 'id' => 'doc-media-1', 'path' => 'media/2026-01/deck.pdf', @@ -603,7 +596,7 @@ }); test('linkedin publisher throws when document init response is missing the urn', function () { - $this->postPlatform->update(['content_type' => ContentType::LinkedInDocument]); + $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]); $this->post->update([ 'media' => [[ 'id' => 'doc-media-1', 'path' => 'media/2026-01/deck.pdf', @@ -625,3 +618,45 @@ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts')); }); + +test('linkedin publisher treats a 401 response without an error code as a token error', function () { + Http::fake([ + config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(['message' => 'Unauthorized'], 401), + ]); + + expect(fn () => $this->publisher->publish($this->postPlatform)) + ->toThrow(TokenExpiredException::class); +}); + +test('linkedin publisher refreshes the token when it is expiring soon', function () { + $this->socialAccount->update([ + 'token_expires_at' => now()->addMinutes(5), + 'refresh_token' => 'refresh-token-123', + ]); + + Http::fake([ + config('trypost.platforms.linkedin.oauth_api').'/oauth/v2/accessToken' => Http::response([ + 'access_token' => 'new-access-token', + 'refresh_token' => 'new-refresh-token', + 'expires_in' => 3600, + ], 200), + config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, ['x-restli-id' => 'urn:li:share:soon']), + ]); + + $result = $this->publisher->publish($this->postPlatform); + + expect($result['id'])->toBe('urn:li:share:soon'); + $this->socialAccount->refresh(); + expect($this->socialAccount->access_token)->toBe('new-access-token'); +}); + +test('linkedin publisher falls back to an empty id and null url when the post id header is missing', function () { + Http::fake([ + config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201), + ]); + + $result = $this->publisher->publish($this->postPlatform); + + expect($result['id'])->toBe(''); + expect($result['url'])->toBeNull(); +}); diff --git a/tests/Feature/Services/Social/LinkedInTokenSynchronizerTest.php b/tests/Feature/Services/Social/LinkedInTokenSynchronizerTest.php deleted file mode 100644 index 85868af4..00000000 --- a/tests/Feature/Services/Social/LinkedInTokenSynchronizerTest.php +++ /dev/null @@ -1,270 +0,0 @@ -user = User::factory()->create(); - $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]); - $this->synchronizer = new LinkedInTokenSynchronizer; -}); - -test('syncs tokens from linkedin personal to linkedin page', function () { - $linkedInUserId = 'linkedin-user-123'; - - $personalAccount = SocialAccount::factory()->linkedin()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => $linkedInUserId, - 'access_token' => 'new-access-token', - 'refresh_token' => 'new-refresh-token', - 'token_expires_at' => now()->addDays(60), - ]); - - $pageAccount = SocialAccount::factory()->linkedinPage()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => 'org-123', - 'access_token' => 'old-access-token', - 'refresh_token' => 'old-refresh-token', - 'token_expires_at' => now()->subDay(), - 'meta' => [ - 'organization_id' => 'org-123', - 'admin_user_id' => $linkedInUserId, - 'admin_name' => 'Test User', - ], - ]); - - $this->synchronizer->syncTokens($personalAccount); - - $pageAccount->refresh(); - expect($pageAccount->access_token)->toBe('new-access-token'); - expect($pageAccount->refresh_token)->toBe('new-refresh-token'); - expect($pageAccount->token_expires_at->toDateString())->toBe(now()->addDays(60)->toDateString()); -}); - -test('syncs tokens from linkedin page to linkedin personal', function () { - $linkedInUserId = 'linkedin-user-456'; - - $personalAccount = SocialAccount::factory()->linkedin()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => $linkedInUserId, - 'access_token' => 'old-access-token', - 'refresh_token' => 'old-refresh-token', - 'token_expires_at' => now()->subDay(), - ]); - - $pageAccount = SocialAccount::factory()->linkedinPage()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => 'org-456', - 'access_token' => 'new-access-token', - 'refresh_token' => 'new-refresh-token', - 'token_expires_at' => now()->addDays(60), - 'meta' => [ - 'organization_id' => 'org-456', - 'admin_user_id' => $linkedInUserId, - 'admin_name' => 'Test User', - ], - ]); - - $this->synchronizer->syncTokens($pageAccount); - - $personalAccount->refresh(); - expect($personalAccount->access_token)->toBe('new-access-token'); - expect($personalAccount->refresh_token)->toBe('new-refresh-token'); - expect($personalAccount->token_expires_at->toDateString())->toBe(now()->addDays(60)->toDateString()); -}); - -test('marks disconnected account as connected after sync', function () { - $linkedInUserId = 'linkedin-user-789'; - - $personalAccount = SocialAccount::factory()->linkedin()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => $linkedInUserId, - 'access_token' => 'new-access-token', - 'refresh_token' => 'new-refresh-token', - 'token_expires_at' => now()->addDays(60), - ]); - - $pageAccount = SocialAccount::factory()->linkedinPage()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => 'org-789', - 'access_token' => 'old-access-token', - 'refresh_token' => 'old-refresh-token', - 'status' => Status::Disconnected, - 'meta' => [ - 'organization_id' => 'org-789', - 'admin_user_id' => $linkedInUserId, - 'admin_name' => 'Test User', - ], - ]); - - $this->synchronizer->syncTokens($personalAccount); - - $pageAccount->refresh(); - expect($pageAccount->status)->toBe(Status::Connected); -}); - -test('does not sync when no linked account exists', function () { - $personalAccount = SocialAccount::factory()->linkedin()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => 'linkedin-user-solo', - 'access_token' => 'access-token', - 'refresh_token' => 'refresh-token', - ]); - - // This should not throw any errors - $this->synchronizer->syncTokens($personalAccount); - - // Just verify the account still has its original tokens - expect($personalAccount->access_token)->toBe('access-token'); -}); - -test('syncs tokens to every linked page admin\'d by the same user', function () { - $linkedInUserId = 'linkedin-user-multi'; - - $personalAccount = SocialAccount::factory()->linkedin()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => $linkedInUserId, - 'access_token' => 'new-access-token', - 'refresh_token' => 'new-refresh-token', - 'token_expires_at' => now()->addDays(60), - ]); - - $pageOne = SocialAccount::factory()->linkedinPage()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => 'org-one', - 'access_token' => 'old-token-1', - 'refresh_token' => 'old-refresh-1', - 'meta' => [ - 'organization_id' => 'org-one', - 'admin_user_id' => $linkedInUserId, - 'admin_name' => 'Test User', - ], - ]); - - $pageTwo = SocialAccount::factory()->linkedinPage()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => 'org-two', - 'access_token' => 'old-token-2', - 'refresh_token' => 'old-refresh-2', - 'meta' => [ - 'organization_id' => 'org-two', - 'admin_user_id' => $linkedInUserId, - 'admin_name' => 'Test User', - ], - ]); - - $unrelatedPage = SocialAccount::factory()->linkedinPage()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => 'org-other-admin', - 'access_token' => 'untouched-token', - 'refresh_token' => 'untouched-refresh', - 'meta' => [ - 'organization_id' => 'org-other-admin', - 'admin_user_id' => 'someone-else', - 'admin_name' => 'Other User', - ], - ]); - - $this->synchronizer->syncTokens($personalAccount); - - $pageOne->refresh(); - $pageTwo->refresh(); - $unrelatedPage->refresh(); - - expect($pageOne->access_token)->toBe('new-access-token'); - expect($pageOne->refresh_token)->toBe('new-refresh-token'); - expect($pageTwo->access_token)->toBe('new-access-token'); - expect($pageTwo->refresh_token)->toBe('new-refresh-token'); - expect($unrelatedPage->access_token)->toBe('untouched-token'); -}); - -test('does not sync across different workspaces', function () { - $linkedInUserId = 'linkedin-user-cross'; - $otherWorkspace = Workspace::factory()->create(['user_id' => $this->user->id]); - - $personalAccount = SocialAccount::factory()->linkedin()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => $linkedInUserId, - 'access_token' => 'new-access-token', - 'refresh_token' => 'new-refresh-token', - ]); - - $pageAccountOtherWorkspace = SocialAccount::factory()->linkedinPage()->create([ - 'workspace_id' => $otherWorkspace->id, - 'platform_user_id' => 'org-other', - 'access_token' => 'old-access-token', - 'refresh_token' => 'old-refresh-token', - 'meta' => [ - 'organization_id' => 'org-other', - 'admin_user_id' => $linkedInUserId, - 'admin_name' => 'Test User', - ], - ]); - - $this->synchronizer->syncTokens($personalAccount); - - $pageAccountOtherWorkspace->refresh(); - // Should NOT have been synced because it's in a different workspace - expect($pageAccountOtherWorkspace->access_token)->toBe('old-access-token'); -}); - -test('does not sync across different LinkedIn admins inside the same workspace', function () { - // Scenario: multi-user workspace. Owner connects their own LinkedIn - // (personal + page they admin); a teammate later connects their - // company's LinkedIn Page that they admin. Two distinct LinkedIn - // user identities coexist in the same workspace and must NOT share - // tokens — each token belongs to whoever authorized it at LinkedIn. - - $ownerLinkedInId = 'linkedin-user-owner'; - $clientLinkedInId = 'linkedin-user-client'; - - $ownerPersonal = SocialAccount::factory()->linkedin()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => $ownerLinkedInId, - 'access_token' => 'owner-new-access-token', - 'refresh_token' => 'owner-new-refresh-token', - 'token_expires_at' => now()->addDays(60), - ]); - - $ownerPage = SocialAccount::factory()->linkedinPage()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => 'org-owner', - 'access_token' => 'owner-old-access-token', - 'refresh_token' => 'owner-old-refresh-token', - 'meta' => [ - 'organization_id' => 'org-owner', - 'admin_user_id' => $ownerLinkedInId, - 'admin_name' => 'Owner', - ], - ]); - - $clientPage = SocialAccount::factory()->linkedinPage()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => 'org-client', - 'access_token' => 'client-untouched-access-token', - 'refresh_token' => 'client-untouched-refresh-token', - 'meta' => [ - 'organization_id' => 'org-client', - 'admin_user_id' => $clientLinkedInId, - 'admin_name' => 'Client', - ], - ]); - - $this->synchronizer->syncTokens($ownerPersonal); - - // Owner's own page got the new token. - $ownerPage->refresh(); - expect($ownerPage->access_token)->toBe('owner-new-access-token'); - expect($ownerPage->refresh_token)->toBe('owner-new-refresh-token'); - - // Client's page (different admin_user_id) was NOT touched even - // though it lives in the same workspace. - $clientPage->refresh(); - expect($clientPage->access_token)->toBe('client-untouched-access-token'); - expect($clientPage->refresh_token)->toBe('client-untouched-refresh-token'); -}); diff --git a/tests/Feature/Social/LinkedInControllerTest.php b/tests/Feature/Social/LinkedInControllerTest.php index 953f7ad1..c33fe998 100644 --- a/tests/Feature/Social/LinkedInControllerTest.php +++ b/tests/Feature/Social/LinkedInControllerTest.php @@ -9,6 +9,8 @@ use App\Models\User; use App\Models\Workspace; use Illuminate\Support\Facades\Http; +use Illuminate\Support\Facades\Storage; +use Inertia\Testing\AssertableInertia as Assert; use Laravel\Socialite\Facades\Socialite; use Laravel\Socialite\Two\User as SocialiteUser; @@ -19,7 +21,24 @@ $this->workspace->members()->attach($this->user->id, ['role' => Role::Member->value]); }); -test('linkedin connect redirects to oauth provider', function () { +/** + * Build a Socialite user for the LinkedIn person behind the OAuth grant. + */ +function linkedInSocialiteUser(string $id = 'person-123'): SocialiteUser +{ + $socialiteUser = Mockery::mock(SocialiteUser::class); + $socialiteUser->shouldReceive('getId')->andReturn($id); + $socialiteUser->shouldReceive('getName')->andReturn('John Doe'); + $socialiteUser->shouldReceive('getAvatar')->andReturn(null); + $socialiteUser->token = 'test-access-token'; + $socialiteUser->refreshToken = 'test-refresh-token'; + $socialiteUser->expiresIn = 5184000; // 60 days + $socialiteUser->approvedScopes = ['openid', 'profile', 'email', 'w_member_social']; + + return $socialiteUser; +} + +test('linkedin connect redirects to oauth provider via the openid driver', function () { $driverMock = Mockery::mock(); $driverMock->shouldReceive('scopes')->andReturnSelf(); $driverMock->shouldReceive('redirect')->andReturn(Mockery::mock([ @@ -27,7 +46,7 @@ ])); Socialite::shouldReceive('driver') - ->with('linkedin') + ->with('linkedin-openid') ->andReturn($driverMock); $response = $this->actingAs($this->user) @@ -40,12 +59,12 @@ }); /** - * Mock the LinkedIn Socialite driver, hit /connect, and return the scopes - * the controller requested. + * Mock the openid driver, hit connect, and return the scopes the controller asked for. * * @return array */ -$captureConnectScopes = function (object $test): array { +function captureLinkedInConnectScopes(object $test): array +{ $captured = []; $driverMock = Mockery::mock(); @@ -60,68 +79,250 @@ 'getTargetUrl' => 'https://www.linkedin.com/oauth/v2/authorization?test=1', ])); - Socialite::shouldReceive('driver') - ->with('linkedin') - ->andReturn($driverMock); + Socialite::shouldReceive('driver')->with('linkedin-openid')->andReturn($driverMock); $test->actingAs($test->user) ->withHeader('X-Inertia', 'true') ->get(route('app.social.linkedin.connect')); return $captured; -}; +} -test('linkedin connect requests the default scope set', function () use ($captureConnectScopes) { +test('linkedin connect requests the union of personal and organization scopes', function () { + config(['trypost.platforms.linkedin.scopes' => ['openid', 'profile', 'email', 'w_member_social']]); + config(['trypost.platforms.linkedin-page.scopes' => ['openid', 'profile', 'email', 'w_organization_social', 'r_organization_social', 'rw_organization_admin', 'w_member_social']]); + + expect(captureLinkedInConnectScopes($this))->toEqualCanonicalizing([ + 'openid', 'profile', 'email', 'w_member_social', + 'w_organization_social', 'r_organization_social', 'rw_organization_admin', + ]); +}); + +test('connect requests only personal scopes when company pages are disabled', function () { + config(['trypost.platforms.linkedin.enabled' => true]); + config(['trypost.platforms.linkedin-page.enabled' => false]); config(['trypost.platforms.linkedin.scopes' => ['openid', 'profile', 'email', 'w_member_social']]); - expect($captureConnectScopes($this))->toEqualCanonicalizing([ + expect(captureLinkedInConnectScopes($this))->toEqualCanonicalizing([ 'openid', 'profile', 'email', 'w_member_social', ]); }); -test('linkedin connect requests the scopes configured via LINKEDIN_SCOPES', function () use ($captureConnectScopes) { - // Operators whose LinkedIn app has legacy/enterprise products approved - // override the default set via LINKEDIN_SCOPES (exploded into the config - // array), e.g. re-adding r_basicprofile to restore the vanityName lookup. - config(['trypost.platforms.linkedin.scopes' => ['openid', 'profile', 'email', 'w_member_social', 'r_basicprofile']]); +test('connect requests only organization scopes when the personal profile is disabled', function () { + config(['trypost.platforms.linkedin.enabled' => false]); + config(['trypost.platforms.linkedin-page.enabled' => true]); + config(['trypost.platforms.linkedin-page.scopes' => ['openid', 'w_organization_social', 'r_organization_social', 'rw_organization_admin']]); - expect($captureConnectScopes($this))->toEqualCanonicalizing([ - 'openid', 'profile', 'email', 'w_member_social', 'r_basicprofile', + expect(captureLinkedInConnectScopes($this))->toEqualCanonicalizing([ + 'openid', 'w_organization_social', 'r_organization_social', 'rw_organization_admin', ]); }); -test('linkedin oauth callback creates account', function () { - session([ - 'social_connect_workspace' => $this->workspace->id, - ]); +test('connect is forbidden when both linkedin capabilities are disabled', function () { + config(['trypost.platforms.linkedin.enabled' => false]); + config(['trypost.platforms.linkedin-page.enabled' => false]); - $socialiteUser = Mockery::mock(SocialiteUser::class); - $socialiteUser->shouldReceive('getId')->andReturn('abc123xyz'); - $socialiteUser->shouldReceive('getNickname')->andReturn(null); - $socialiteUser->shouldReceive('getName')->andReturn('John Doe'); - $socialiteUser->shouldReceive('getAvatar')->andReturn(null); - $socialiteUser->token = 'test-access-token'; - $socialiteUser->refreshToken = 'test-refresh-token'; - $socialiteUser->expiresIn = 5184000; // 60 days - $socialiteUser->approvedScopes = ['openid', 'profile', 'email', 'w_member_social']; + $this->actingAs($this->user) + ->get(route('app.social.linkedin.connect')) + ->assertForbidden(); +}); + +test('connect returns the popup callback when the user has no workspace', function () { + // Runs inside the OAuth popup, so it must not redirect away and strand it. + $this->user->update(['current_workspace_id' => null]); + + $response = $this->actingAs($this->user)->get(route('app.social.linkedin.connect')); + + $response->assertOk(); + $response->assertViewIs('auth.social-callback'); + $response->assertViewHas('success', false); +}); + +test('linkedin callback stores the person and organizations then redirects to the selector', function () { + session(['social_connect_workspace' => $this->workspace->id]); Socialite::shouldReceive('driver') - ->with('linkedin') - ->andReturn(Mockery::mock([ - 'user' => $socialiteUser, - ])); + ->with('linkedin-openid') + ->andReturn(Mockery::mock(['user' => linkedInSocialiteUser()])); Http::fake([ - 'https://api.linkedin.com/v2/me*' => Http::response([ - 'id' => 'abc123xyz', - 'vanityName' => 'johndoe', - 'localizedFirstName' => 'John', - 'localizedLastName' => 'Doe', + config('trypost.platforms.linkedin.api').'/v2/me*' => Http::response(['id' => 'person-123', 'vanityName' => 'johndoe'], 200), + config('trypost.platforms.linkedin.api').'/v2/organizationAcls*' => Http::response([ + 'elements' => [ + ['organization~' => ['id' => 123456, 'localizedName' => 'Test Company', 'vanityName' => 'testcompany']], + ], ], 200), ]); $response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback')); + $response->assertRedirect(route('app.social.linkedin.select-identity')); + + expect(session('linkedin_pending.person.id'))->toBe('person-123'); + expect(session('linkedin_pending.person.vanity_name'))->toBe('johndoe'); + expect(session('linkedin_pending.organizations'))->toHaveCount(1); +}); + +test('linkedin callback still redirects to the selector when the member administers no organizations', function () { + session(['social_connect_workspace' => $this->workspace->id]); + + Socialite::shouldReceive('driver') + ->with('linkedin-openid') + ->andReturn(Mockery::mock(['user' => linkedInSocialiteUser()])); + + Http::fake([ + config('trypost.platforms.linkedin.api').'/v2/me*' => Http::response(['vanityName' => 'johndoe'], 200), + config('trypost.platforms.linkedin.api').'/v2/organizationAcls*' => Http::response(['elements' => []], 200), + ]); + + $response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback')); + + $response->assertRedirect(route('app.social.linkedin.select-identity')); + expect(session('linkedin_pending.organizations'))->toBe([]); +}); + +test('linkedin callback fails with expired session', function () { + $response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback')); + + $response->assertOk(); + $response->assertViewHas('success', false); + $response->assertViewHas('message', 'Session expired. Please try again.'); +}); + +test('linkedin callback handles oauth errors gracefully', function () { + session(['social_connect_workspace' => $this->workspace->id]); + + $mock = Mockery::mock(); + $mock->shouldReceive('user')->andThrow(new Exception('OAuth error')); + + Socialite::shouldReceive('driver')->with('linkedin-openid')->andReturn($mock); + + $response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback')); + + $response->assertOk(); + $response->assertViewHas('success', false); + $response->assertViewHas('message', 'Error connecting account. Please try again.'); +}); + +test('select-identity screen renders the person and organizations', function () { + session(['linkedin_pending' => [ + 'workspace_id' => $this->workspace->id, + 'token' => 'test-access-token', + 'refresh_token' => 'test-refresh-token', + 'expires_in' => 5184000, + 'approved_scopes' => ['openid', 'profile', 'email', 'w_member_social'], + 'person' => ['id' => 'person-123', 'name' => 'John Doe', 'avatar' => null, 'vanity_name' => 'johndoe'], + 'organizations' => [ + ['id' => 123456, 'name' => 'Test Company', 'vanity_name' => 'testcompany', 'logo' => null], + ], + ]]); + + $response = $this->actingAs($this->user)->get(route('app.social.linkedin.select-identity')); + + $response->assertOk(); + $response->assertInertia(fn (Assert $page) => $page + ->component('accounts/LinkedInSelect') + ->where('person.name', 'John Doe') + ->has('organizations', 1) + ); +}); + +test('select-identity hides the personal profile when that capability is disabled', function () { + config(['trypost.platforms.linkedin.enabled' => false]); + config(['trypost.platforms.linkedin-page.enabled' => true]); + + session(['linkedin_pending' => [ + 'workspace_id' => $this->workspace->id, + 'token' => 'test-access-token', + 'refresh_token' => 'test-refresh-token', + 'expires_in' => 5184000, + 'approved_scopes' => ['openid', 'w_organization_social'], + 'person' => ['id' => 'person-123', 'name' => 'John Doe', 'avatar' => null, 'vanity_name' => null], + 'organizations' => [ + ['id' => 123456, 'name' => 'Test Company', 'vanity_name' => 'testcompany', 'logo' => null], + ], + ]]); + + $response = $this->actingAs($this->user)->get(route('app.social.linkedin.select-identity')); + + $response->assertOk(); + $response->assertInertia(fn (Assert $page) => $page + ->component('accounts/LinkedInSelect') + ->where('person', null) + ->has('organizations', 1) + ); +}); + +test('selecting the person is rejected when the personal profile capability is disabled', function () { + config(['trypost.platforms.linkedin.enabled' => false]); + config(['trypost.platforms.linkedin-page.enabled' => true]); + + session(['linkedin_pending' => [ + 'workspace_id' => $this->workspace->id, + 'token' => 'test-access-token', + 'refresh_token' => 'test-refresh-token', + 'expires_in' => 5184000, + 'approved_scopes' => ['openid', 'w_organization_social'], + 'person' => ['id' => 'person-123', 'name' => 'John Doe', 'avatar' => null, 'vanity_name' => null], + 'organizations' => [], + ]]); + + $response = $this->actingAs($this->user)->post(route('app.social.linkedin.select'), [ + 'type' => 'person', + ]); + + $response->assertViewHas('success', false); + $this->assertDatabaseMissing('social_accounts', ['platform_user_id' => 'person-123']); +}); + +test('selecting an organization is rejected when company pages are disabled', function () { + config(['trypost.platforms.linkedin.enabled' => true]); + config(['trypost.platforms.linkedin-page.enabled' => false]); + + session(['linkedin_pending' => [ + 'workspace_id' => $this->workspace->id, + 'token' => 'test-access-token', + 'refresh_token' => 'test-refresh-token', + 'expires_in' => 5184000, + 'approved_scopes' => ['openid', 'profile', 'email', 'w_member_social'], + 'person' => ['id' => 'person-123', 'name' => 'John Doe', 'avatar' => null, 'vanity_name' => 'johndoe'], + 'organizations' => [], + ]]); + + $response = $this->actingAs($this->user)->post(route('app.social.linkedin.select'), [ + 'type' => 'organization', + 'organization_id' => 123456, + ]); + + $response->assertViewHas('success', false); + $this->assertDatabaseMissing('social_accounts', ['platform_user_id' => 123456]); +}); + +test('select-identity returns the popup callback when the session expired', function () { + // Rendered inside the OAuth popup, so a redirect would strand it — it must + // answer with the self-closing callback view instead. + $response = $this->actingAs($this->user)->get(route('app.social.linkedin.select-identity')); + + $response->assertOk(); + $response->assertViewIs('auth.social-callback'); + $response->assertViewHas('success', false); +}); + +test('selecting the person creates a linkedin account', function () { + session(['linkedin_pending' => [ + 'workspace_id' => $this->workspace->id, + 'token' => 'test-access-token', + 'refresh_token' => 'test-refresh-token', + 'expires_in' => 5184000, + 'approved_scopes' => ['openid', 'profile', 'email', 'w_member_social'], + 'person' => ['id' => 'person-123', 'name' => 'John Doe', 'avatar' => null, 'vanity_name' => 'johndoe'], + 'organizations' => [], + ]]); + + $response = $this->actingAs($this->user)->post(route('app.social.linkedin.select'), [ + 'type' => 'person', + ]); + $response->assertOk(); $response->assertViewIs('auth.social-callback'); $response->assertViewHas('success', true); @@ -129,159 +330,212 @@ $this->assertDatabaseHas('social_accounts', [ 'workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn->value, - 'platform_user_id' => 'abc123xyz', + 'platform_user_id' => 'person-123', 'username' => 'johndoe', + 'display_name' => 'John Doe', 'status' => Status::Connected->value, ]); + + expect(session('linkedin_pending'))->toBeNull(); +}); + +test('selecting the person downloads and stores the avatar', function () { + Storage::fake(); + + session(['linkedin_pending' => [ + 'workspace_id' => $this->workspace->id, + 'token' => 'test-access-token', + 'refresh_token' => 'test-refresh-token', + 'expires_in' => 5184000, + 'approved_scopes' => ['openid', 'profile', 'email', 'w_member_social'], + 'person' => ['id' => 'person-avatar', 'name' => 'John Doe', 'avatar' => 'https://media.example.com/avatar.jpg', 'vanity_name' => 'johndoe'], + 'organizations' => [], + ]]); + + Http::fake([ + 'https://media.example.com/avatar.jpg' => Http::response('fake-image-bytes', 200, ['Content-Type' => 'image/jpeg']), + ]); + + $this->actingAs($this->user)->post(route('app.social.linkedin.select'), ['type' => 'person']); + + // The avatar download (uploadFromUrl) ran and a stored path was persisted. + Http::assertSent(fn ($request) => $request->url() === 'https://media.example.com/avatar.jpg'); + + $account = SocialAccount::where('platform_user_id', 'person-avatar')->first(); + expect($account->getRawOriginal('avatar_url'))->not->toBeNull(); +}); + +test('selecting an organization creates a linkedin-page account with the admin recorded in meta', function () { + session(['linkedin_pending' => [ + 'workspace_id' => $this->workspace->id, + 'token' => 'test-access-token', + 'refresh_token' => 'test-refresh-token', + 'expires_in' => 5184000, + 'approved_scopes' => ['openid', 'profile', 'email', 'w_organization_social'], + 'person' => ['id' => 'person-123', 'name' => 'John Doe', 'avatar' => null, 'vanity_name' => 'johndoe'], + 'organizations' => [ + ['id' => 123456, 'name' => 'Test Company', 'vanity_name' => 'testcompany', 'logo' => null], + ], + ]]); + + $response = $this->actingAs($this->user)->post(route('app.social.linkedin.select'), [ + 'type' => 'organization', + 'organization_id' => 123456, + ]); + + $response->assertOk(); + $response->assertViewHas('success', true); + + $account = SocialAccount::where('platform', Platform::LinkedInPage->value) + ->where('platform_user_id', 123456) + ->first(); + + expect($account)->not->toBeNull(); + expect($account->display_name)->toBe('Test Company'); + expect($account->username)->toBe('testcompany'); + expect($account->meta['admin_user_id'])->toBe('person-123'); + expect($account->meta['admin_name'])->toBe('John Doe'); +}); + +test('selecting an organization the member does not administer is rejected', function () { + session(['linkedin_pending' => [ + 'workspace_id' => $this->workspace->id, + 'token' => 'test-access-token', + 'refresh_token' => 'test-refresh-token', + 'expires_in' => 5184000, + 'approved_scopes' => ['openid', 'w_organization_social'], + 'person' => ['id' => 'person-123', 'name' => 'John Doe', 'avatar' => null, 'vanity_name' => 'johndoe'], + 'organizations' => [ + ['id' => 111, 'name' => 'My Company', 'vanity_name' => 'myco', 'logo' => null], + ], + ]]); + + // 999 is not in the admin-verified list — a tampered POST must not connect it. + $response = $this->actingAs($this->user)->post(route('app.social.linkedin.select'), [ + 'type' => 'organization', + 'organization_id' => 999, + ]); + + $response->assertViewHas('success', false); + $this->assertDatabaseMissing('social_accounts', ['platform_user_id' => 999]); +}); + +test('selecting an organization splits comma-separated approvedScopes before saving', function () { + session(['linkedin_pending' => [ + 'workspace_id' => $this->workspace->id, + 'token' => 'test-access-token', + 'refresh_token' => 'test-refresh-token', + 'expires_in' => 5184000, + // Socialite returns LinkedIn scopes CSV-joined into a single element. + 'approved_scopes' => ['email,openid,profile,w_organization_social,r_organization_social,rw_organization_admin,w_member_social'], + 'person' => ['id' => 'person-123', 'name' => 'John Doe', 'avatar' => null, 'vanity_name' => 'johndoe'], + 'organizations' => [ + ['id' => 999888, 'name' => 'Scope Company', 'vanity_name' => 'scopeco', 'logo' => null], + ], + ]]); + + $this->actingAs($this->user)->post(route('app.social.linkedin.select'), [ + 'type' => 'organization', + 'organization_id' => 999888, + ]); + + $account = SocialAccount::where('platform_user_id', 999888)->first(); + expect($account->scopes)->toEqualCanonicalizing([ + 'email', 'openid', 'profile', + 'w_organization_social', 'r_organization_social', + 'rw_organization_admin', 'w_member_social', + ]); }); -test('linkedin callback shows network_taken when the linkedin network is already connected', function () { - config()->set('trypost.self_hosted', false); - - // A LinkedIn Page occupies the shared "linkedin" network for this workspace. - SocialAccount::factory()->linkedinPage()->create([ +test('select rejects an invalid identity type without stranding the popup', function () { + session(['linkedin_pending' => [ 'workspace_id' => $this->workspace->id, - 'platform_user_id' => 'existing-linkedin-page', - ]); + 'token' => 'test-access-token', + 'refresh_token' => 'test-refresh-token', + 'expires_in' => 5184000, + 'approved_scopes' => [], + 'person' => ['id' => 'person-123', 'name' => 'John Doe', 'avatar' => null, 'vanity_name' => 'johndoe'], + 'organizations' => [], + ]]); - session(['social_connect_workspace' => $this->workspace->id]); - - $socialiteUser = Mockery::mock(SocialiteUser::class); - $socialiteUser->shouldReceive('getId')->andReturn('new-profile-id'); - $socialiteUser->shouldReceive('getName')->andReturn('John Doe'); - $socialiteUser->shouldReceive('getAvatar')->andReturn(null); - $socialiteUser->token = 'test-access-token'; - $socialiteUser->refreshToken = 'test-refresh-token'; - $socialiteUser->expiresIn = 5184000; - $socialiteUser->approvedScopes = ['openid', 'profile', 'email', 'w_member_social']; - - Socialite::shouldReceive('driver') - ->with('linkedin') - ->andReturn(Mockery::mock(['user' => $socialiteUser])); - - Http::fake([ - 'https://api.linkedin.com/v2/me*' => Http::response([ - 'id' => 'new-profile-id', - 'vanityName' => 'johndoe', - ], 200), - ]); - - $response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback')); + $response = $this->actingAs($this->user)->post(route('app.social.linkedin.select'), ['type' => 'bogus']); + // A redirect-back would strand the popup; it must answer with the self-closing callback view. $response->assertOk(); $response->assertViewIs('auth.social-callback'); $response->assertViewHas('success', false); - $response->assertViewHas('message', __('accounts.popup_callback.network_taken')); - - $this->assertDatabaseMissing('social_accounts', [ - 'platform' => Platform::LinkedIn->value, - 'platform_user_id' => 'new-profile-id', - ]); + $this->assertDatabaseMissing('social_accounts', ['platform_user_id' => 'person-123']); }); -test('linkedin oauth callback splits comma-separated approvedScopes before saving', function () { - session(['social_connect_workspace' => $this->workspace->id]); - - $socialiteUser = Mockery::mock(SocialiteUser::class); - $socialiteUser->shouldReceive('getId')->andReturn('abc123xyz'); - $socialiteUser->shouldReceive('getNickname')->andReturn(null); - $socialiteUser->shouldReceive('getName')->andReturn('John Doe'); - $socialiteUser->shouldReceive('getAvatar')->andReturn(null); - $socialiteUser->token = 'test-access-token'; - $socialiteUser->refreshToken = 'test-refresh-token'; - $socialiteUser->expiresIn = 5184000; - // LinkedIn returns scopes comma-separated; Socialite's LinkedInProvider - // splits on space (the OAuth 2.0 default), so approvedScopes lands as - // a single-element array with the whole CSV inside. The save path - // must normalize back to individual tokens. - $socialiteUser->approvedScopes = ['email,openid,profile,w_member_social']; - - Socialite::shouldReceive('driver') - ->with('linkedin') - ->andReturn(Mockery::mock(['user' => $socialiteUser])); - - Http::fake([ - 'https://api.linkedin.com/v2/me*' => Http::response([ - 'id' => 'abc123xyz', - 'vanityName' => 'johndoe', - ], 200), +test('select fails with expired session', function () { + $response = $this->actingAs($this->user)->post(route('app.social.linkedin.select'), [ + 'type' => 'person', ]); - $this->actingAs($this->user)->get(route('app.social.linkedin.callback')); - - $account = SocialAccount::where('platform_user_id', 'abc123xyz')->first(); - expect($account->scopes)->toEqualCanonicalizing([ - 'email', 'openid', 'profile', 'w_member_social', - ]); -}); - -test('linkedin callback fails with expired session', function () { - // No session data - simulating expired session - - $response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback')); - $response->assertOk(); $response->assertViewHas('success', false); $response->assertViewHas('message', 'Session expired. Please try again.'); }); -test('user can connect multiple linkedin accounts in self-hosted mode', function () { +test('selecting the person shows network_taken when a linkedin page already occupies the network', function () { + config()->set('trypost.self_hosted', false); + + SocialAccount::factory()->linkedinPage()->create([ + 'workspace_id' => $this->workspace->id, + 'platform_user_id' => 'existing-linkedin-page', + ]); + + session(['linkedin_pending' => [ + 'workspace_id' => $this->workspace->id, + 'token' => 'test-access-token', + 'refresh_token' => 'test-refresh-token', + 'expires_in' => 5184000, + 'approved_scopes' => ['openid', 'profile', 'email', 'w_member_social'], + 'person' => ['id' => 'new-person', 'name' => 'John Doe', 'avatar' => null, 'vanity_name' => 'johndoe'], + 'organizations' => [], + ]]); + + $response = $this->actingAs($this->user)->post(route('app.social.linkedin.select'), [ + 'type' => 'person', + ]); + + $response->assertOk(); + $response->assertViewHas('success', false); + $response->assertViewHas('message', __('accounts.popup_callback.network_taken')); + + $this->assertDatabaseMissing('social_accounts', [ + 'platform' => Platform::LinkedIn->value, + 'platform_user_id' => 'new-person', + ]); +}); + +test('user can connect multiple linkedin organizations in self-hosted mode', function () { config()->set('trypost.self_hosted', true); - SocialAccount::factory()->linkedin()->create([ + SocialAccount::factory()->linkedinPage()->create([ 'workspace_id' => $this->workspace->id, - 'platform_user_id' => 'abc123xyz', + 'platform_user_id' => '123456', ]); - session([ - 'social_connect_workspace' => $this->workspace->id, + session(['linkedin_pending' => [ + 'workspace_id' => $this->workspace->id, + 'token' => 'new-access-token', + 'refresh_token' => 'new-refresh-token', + 'expires_in' => 5184000, + 'approved_scopes' => ['openid', 'profile', 'email', 'w_organization_social'], + 'person' => ['id' => 'person-123', 'name' => 'John Doe', 'avatar' => null, 'vanity_name' => 'johndoe'], + 'organizations' => [ + ['id' => 789012, 'name' => 'Another Company', 'vanity_name' => 'anothercompany', 'logo' => null], + ], + ]]); + + $response = $this->actingAs($this->user)->post(route('app.social.linkedin.select'), [ + 'type' => 'organization', + 'organization_id' => 789012, ]); - $socialiteUser = Mockery::mock(SocialiteUser::class); - $socialiteUser->shouldReceive('getId')->andReturn('xyz789abc'); - $socialiteUser->shouldReceive('getNickname')->andReturn(null); - $socialiteUser->shouldReceive('getName')->andReturn('Jane Doe'); - $socialiteUser->shouldReceive('getAvatar')->andReturn(null); - $socialiteUser->token = 'new-access-token'; - $socialiteUser->refreshToken = 'new-refresh-token'; - $socialiteUser->expiresIn = 5184000; - $socialiteUser->approvedScopes = ['openid', 'profile', 'email', 'w_member_social']; - - Socialite::shouldReceive('driver') - ->with('linkedin') - ->andReturn(Mockery::mock([ - 'user' => $socialiteUser, - ])); - - Http::fake([ - 'https://api.linkedin.com/v2/me*' => Http::response([ - 'vanityName' => 'janedoe', - ], 200), - ]); - - $response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback')); - $response->assertOk(); $response->assertViewHas('success', true); - expect($this->workspace->socialAccounts()->where('platform', Platform::LinkedIn)->count())->toBe(2); -}); - -test('linkedin callback handles oauth errors gracefully', function () { - session([ - 'social_connect_workspace' => $this->workspace->id, - ]); - - $mock = Mockery::mock(); - $mock->shouldReceive('user')->andThrow(new Exception('OAuth error')); - - Socialite::shouldReceive('driver') - ->with('linkedin') - ->andReturn($mock); - - $response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback')); - - $response->assertOk(); - $response->assertViewHas('success', false); - $response->assertViewHas('message', 'Error connecting account. Please try again.'); + expect($this->workspace->socialAccounts()->where('platform', Platform::LinkedInPage)->count())->toBe(2); }); diff --git a/tests/Feature/Social/LinkedInPageControllerTest.php b/tests/Feature/Social/LinkedInPageControllerTest.php deleted file mode 100644 index ac79d246..00000000 --- a/tests/Feature/Social/LinkedInPageControllerTest.php +++ /dev/null @@ -1,311 +0,0 @@ -user = User::factory()->create(); - $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]); - $this->user->update(['current_workspace_id' => $this->workspace->id]); - $this->workspace->members()->attach($this->user->id, ['role' => Role::Member->value]); -}); - -test('linkedin page connect redirects to oauth provider', function () { - $driverMock = Mockery::mock(); - $driverMock->shouldReceive('scopes')->andReturnSelf(); - $driverMock->shouldReceive('with')->andReturnSelf(); - $driverMock->shouldReceive('redirect')->andReturn(Mockery::mock([ - 'getTargetUrl' => 'https://www.linkedin.com/oauth/v2/authorization?test=1', - ])); - - Socialite::shouldReceive('driver') - ->with('linkedin-openid') - ->andReturn($driverMock); - - $response = $this->actingAs($this->user) - ->withHeader('X-Inertia', 'true') - ->get(route('app.social.linkedin-page.connect')); - - $response->assertStatus(409); // Inertia::location returns 409 with X-Inertia header - - expect(session('social_connect_workspace'))->toBe($this->workspace->id); -}); - -test('linkedin page oauth callback fetches organizations', function () { - session([ - 'social_connect_workspace' => $this->workspace->id, - ]); - - $socialiteUser = Mockery::mock(SocialiteUser::class); - $socialiteUser->shouldReceive('getId')->andReturn('user123'); - $socialiteUser->shouldReceive('getName')->andReturn('John Doe'); - $socialiteUser->shouldReceive('getAvatar')->andReturn(null); - $socialiteUser->token = 'test-access-token'; - $socialiteUser->refreshToken = 'test-refresh-token'; - $socialiteUser->expiresIn = 5184000; - - $socialiteMock = Mockery::mock(); - $socialiteMock->shouldReceive('scopes')->andReturn($socialiteMock); - $socialiteMock->shouldReceive('with')->andReturn($socialiteMock); - $socialiteMock->shouldReceive('user')->andReturn($socialiteUser); - - Socialite::shouldReceive('driver') - ->with('linkedin-openid') - ->andReturn($socialiteMock); - - Http::fake([ - 'https://api.linkedin.com/v2/organizationAcls*' => Http::response([ - 'elements' => [ - [ - 'organization~' => [ - 'id' => 123456, - 'localizedName' => 'Test Company', - 'vanityName' => 'testcompany', - ], - ], - ], - ], 200), - ]); - - $response = $this->actingAs($this->user)->get(route('app.social.linkedin-page.callback')); - - $response->assertRedirect(route('app.social.linkedin-page.select-page')); - - expect(session('linkedin_page_pending'))->not->toBeNull(); - expect(session('linkedin_page_pending.organizations'))->toHaveCount(1); -}); - -test('linkedin page callback fails when user has no organizations', function () { - session([ - 'social_connect_workspace' => $this->workspace->id, - ]); - - $socialiteUser = Mockery::mock(SocialiteUser::class); - $socialiteUser->shouldReceive('getId')->andReturn('user123'); - $socialiteUser->shouldReceive('getName')->andReturn('John Doe'); - $socialiteUser->shouldReceive('getAvatar')->andReturn(null); - $socialiteUser->token = 'test-access-token'; - $socialiteUser->refreshToken = 'test-refresh-token'; - $socialiteUser->expiresIn = 5184000; - - $socialiteMock = Mockery::mock(); - $socialiteMock->shouldReceive('scopes')->andReturn($socialiteMock); - $socialiteMock->shouldReceive('with')->andReturn($socialiteMock); - $socialiteMock->shouldReceive('user')->andReturn($socialiteUser); - - Socialite::shouldReceive('driver') - ->with('linkedin-openid') - ->andReturn($socialiteMock); - - Http::fake([ - 'https://api.linkedin.com/v2/organizationAcls*' => Http::response([ - 'elements' => [], - ], 200), - ]); - - $response = $this->actingAs($this->user)->get(route('app.social.linkedin-page.callback')); - - $response->assertOk(); - $response->assertViewHas('success', false); - $response->assertViewHas('message', 'You are not an administrator of any LinkedIn page.'); -}); - -test('linkedin page callback fails with expired session', function () { - // No session data - simulating expired session - - $response = $this->actingAs($this->user)->get(route('app.social.linkedin-page.callback')); - - $response->assertOk(); - $response->assertViewHas('success', false); - $response->assertViewHas('message', 'Session expired. Please try again.'); -}); - -test('linkedin page select creates account', function () { - session([ - 'linkedin_page_pending' => [ - 'workspace_id' => $this->workspace->id, - 'user_id' => 'user123', - 'name' => 'John Doe', - 'avatar' => null, - 'token' => 'test-access-token', - 'refresh_token' => 'test-refresh-token', - 'expires_in' => 5184000, - 'organizations' => [ - ['id' => 123456, 'name' => 'Test Company', 'vanity_name' => 'testcompany', 'logo' => null], - ], - ], - ]); - - $response = $this->actingAs($this->user)->post(route('app.social.linkedin-page.select'), [ - 'organization_id' => 123456, - 'organization_name' => 'Test Company', - 'organization_vanity_name' => 'testcompany', - 'organization_logo' => null, - ]); - - $response->assertOk(); - $response->assertViewIs('auth.social-callback'); - $response->assertViewHas('success', true); - - $this->assertDatabaseHas('social_accounts', [ - 'workspace_id' => $this->workspace->id, - 'platform' => Platform::LinkedInPage->value, - 'platform_user_id' => 123456, - 'username' => 'testcompany', - 'display_name' => 'Test Company', - 'status' => Status::Connected->value, - ]); -}); - -test('linkedin page select splits comma-separated approvedScopes before saving', function () { - session([ - 'linkedin_page_pending' => [ - 'workspace_id' => $this->workspace->id, - 'user_id' => 'user123', - 'name' => 'John Doe', - 'avatar' => null, - 'token' => 'test-access-token', - 'refresh_token' => 'test-refresh-token', - 'expires_in' => 5184000, - // Simulates what Socialite returns for LinkedIn (CSV-joined into - // a single array element because the provider splits on space). - 'approved_scopes' => ['email,openid,profile,w_organization_social,r_organization_social,rw_organization_admin,w_member_social'], - 'organizations' => [ - ['id' => 999888, 'name' => 'Scope Company', 'vanity_name' => 'scopeco', 'logo' => null], - ], - ], - ]); - - $this->actingAs($this->user)->post(route('app.social.linkedin-page.select'), [ - 'organization_id' => 999888, - 'organization_name' => 'Scope Company', - 'organization_vanity_name' => 'scopeco', - 'organization_logo' => null, - ]); - - $account = SocialAccount::where('platform_user_id', 999888)->first(); - expect($account->scopes)->toEqualCanonicalizing([ - 'email', 'openid', 'profile', - 'w_organization_social', 'r_organization_social', - 'rw_organization_admin', 'w_member_social', - ]); -}); - -test('linkedin page select fails with expired session', function () { - // No session data - - $response = $this->actingAs($this->user)->post(route('app.social.linkedin-page.select'), [ - 'organization_id' => 123456, - 'organization_name' => 'Test Company', - 'organization_vanity_name' => 'testcompany', - ]); - - $response->assertOk(); - $response->assertViewHas('success', false); - $response->assertViewHas('message', 'Session expired. Please try again.'); -}); - -test('user can connect multiple linkedin pages in self-hosted mode', function () { - config()->set('trypost.self_hosted', true); - - SocialAccount::factory()->linkedinPage()->create([ - 'workspace_id' => $this->workspace->id, - 'platform_user_id' => '123456', - ]); - - session([ - 'linkedin_page_pending' => [ - 'workspace_id' => $this->workspace->id, - 'user_id' => 'user123', - 'name' => 'John Doe', - 'avatar' => null, - 'token' => 'new-access-token', - 'refresh_token' => 'new-refresh-token', - 'expires_in' => 5184000, - 'organizations' => [ - ['id' => 789012, 'name' => 'Another Company', 'vanity_name' => 'anothercompany', 'logo' => null], - ], - ], - ]); - - $response = $this->actingAs($this->user)->post(route('app.social.linkedin-page.select'), [ - 'organization_id' => 789012, - 'organization_name' => 'Another Company', - 'organization_vanity_name' => 'anothercompany', - 'organization_logo' => null, - ]); - - $response->assertOk(); - $response->assertViewHas('success', true); - - expect($this->workspace->socialAccounts()->where('platform', Platform::LinkedInPage)->count())->toBe(2); -}); - -test('linkedin page callback handles oauth errors gracefully', function () { - session([ - 'social_connect_workspace' => $this->workspace->id, - ]); - - $socialiteMock = Mockery::mock(); - $socialiteMock->shouldReceive('scopes')->andReturn($socialiteMock); - $socialiteMock->shouldReceive('with')->andReturn($socialiteMock); - $socialiteMock->shouldReceive('user')->andThrow(new Exception('OAuth error')); - - Socialite::shouldReceive('driver') - ->with('linkedin-openid') - ->andReturn($socialiteMock); - - $response = $this->actingAs($this->user)->get(route('app.social.linkedin-page.callback')); - - $response->assertOk(); - $response->assertViewHas('success', false); - $response->assertViewHas('message', 'Error connecting account. Please try again.'); -}); - -test('linkedin page select shows network_taken when a linkedin account is already connected', function () { - config()->set('trypost.self_hosted', false); - - SocialAccount::factory()->create([ - 'workspace_id' => $this->workspace->id, - 'platform' => Platform::LinkedIn, - 'platform_user_id' => 'existing-linkedin', - ]); - - session([ - 'linkedin_page_pending' => [ - 'workspace_id' => $this->workspace->id, - 'user_id' => 'user123', - 'name' => 'John Doe', - 'avatar' => null, - 'token' => 'test-access-token', - 'refresh_token' => 'test-refresh-token', - 'expires_in' => 5184000, - 'organizations' => [ - ['id' => 123456, 'name' => 'Test Company', 'vanity_name' => 'testcompany', 'logo' => null], - ], - ], - ]); - - $response = $this->actingAs($this->user)->post(route('app.social.linkedin-page.select'), [ - 'organization_id' => 123456, - 'organization_name' => 'Test Company', - 'organization_vanity_name' => 'testcompany', - 'organization_logo' => null, - ]); - - $response->assertOk(); - $response->assertViewIs('auth.social-callback'); - $response->assertViewHas('success', false); - $response->assertViewHas('message', __('accounts.popup_callback.network_taken')); - - expect($this->workspace->socialAccounts()->whereIn('platform', [Platform::LinkedIn->value, Platform::LinkedInPage->value])->count())->toBe(1); -}); diff --git a/tests/Feature/SocialControllerTest.php b/tests/Feature/SocialControllerTest.php index a0ed0a12..9a99e62a 100644 --- a/tests/Feature/SocialControllerTest.php +++ b/tests/Feature/SocialControllerTest.php @@ -43,6 +43,56 @@ ); }); +test('accounts index offers a single linkedin card and no standalone linkedin page card', function () { + $response = $this->actingAs($this->user)->get(route('app.accounts')); + + $response->assertOk(); + $response->assertInertia(fn ($page) => $page + ->component('accounts/Index', false) + ->where('platforms', fn ($platforms) => collect($platforms)->contains('value', Platform::LinkedIn->value) + && ! collect($platforms)->contains('value', Platform::LinkedInPage->value) + ) + ); +}); + +test('the linkedin card still shows when only company pages are enabled', function () { + config(['trypost.platforms.linkedin.enabled' => false]); + config(['trypost.platforms.linkedin-page.enabled' => true]); + + $response = $this->actingAs($this->user)->get(route('app.accounts')); + + $response->assertInertia(fn ($page) => $page + ->component('accounts/Index', false) + ->where('platforms', fn ($platforms) => collect($platforms)->contains('value', Platform::LinkedIn->value)) + ); +}); + +test('the linkedin card disappears only when both capabilities are disabled', function () { + config(['trypost.platforms.linkedin.enabled' => false]); + config(['trypost.platforms.linkedin-page.enabled' => false]); + + $response = $this->actingAs($this->user)->get(route('app.accounts')); + + $response->assertInertia(fn ($page) => $page + ->component('accounts/Index', false) + ->where('platforms', fn ($platforms) => ! collect($platforms)->contains('value', Platform::LinkedIn->value)) + ); +}); + +test('a connected linkedin page account is still returned so it surfaces under the linkedin card', function () { + SocialAccount::factory()->linkedinPage()->create([ + 'workspace_id' => $this->workspace->id, + ]); + + $response = $this->actingAs($this->user)->get(route('app.accounts')); + + $response->assertOk(); + $response->assertInertia(fn ($page) => $page + ->component('accounts/Index', false) + ->where('connectedAccounts.0.platform', Platform::LinkedInPage->value) + ); +}); + test('an unsubscribed account can disconnect during onboarding (no active subscription required)', function () { config(['trypost.self_hosted' => false]); diff --git a/tests/Unit/Enums/ContentTypeTest.php b/tests/Unit/Enums/ContentTypeTest.php index 5d61e159..e66d7f6d 100644 --- a/tests/Unit/Enums/ContentTypeTest.php +++ b/tests/Unit/Enums/ContentTypeTest.php @@ -10,7 +10,6 @@ expect(ContentType::InstagramReel->label())->toBe('Reel'); expect(ContentType::InstagramStory->label())->toBe('Story'); expect(ContentType::LinkedInPost->label())->toBe('Post'); - expect(ContentType::LinkedInCarousel->label())->toBe('Carousel'); expect(ContentType::YouTubeShort->label())->toBe('Short'); expect(ContentType::XPost->label())->toBe('Post'); expect(ContentType::TikTokVideo->label())->toBe('Video'); @@ -60,7 +59,7 @@ test('content type has correct max media count', function () { expect(ContentType::InstagramFeed->maxMediaCount())->toBe(10); expect(ContentType::InstagramReel->maxMediaCount())->toBe(1); - expect(ContentType::LinkedInCarousel->maxMediaCount())->toBe(20); + expect(ContentType::LinkedInPost->maxMediaCount())->toBe(20); expect(ContentType::XPost->maxMediaCount())->toBe(4); expect(ContentType::PinterestCarousel->maxMediaCount())->toBe(5); expect(ContentType::BlueskyPost->maxMediaCount())->toBe(4); @@ -71,7 +70,7 @@ expect(ContentType::InstagramReel->supportsVideo())->toBeTrue(); expect(ContentType::TikTokVideo->supportsVideo())->toBeTrue(); expect(ContentType::YouTubeShort->supportsVideo())->toBeTrue(); - expect(ContentType::LinkedInCarousel->supportsVideo())->toBeFalse(); + expect(ContentType::LinkedInPost->supportsVideo())->toBeTrue(); expect(ContentType::PinterestPin->supportsVideo())->toBeFalse(); }); @@ -151,28 +150,25 @@ expect(ContentType::MastodonPost->supportsVideo())->toBeTrue(); }); -test('linkedin document content types are pdf-only and single-file', function () { - foreach ([ContentType::LinkedInDocument, ContentType::LinkedInPageDocument] as $type) { - expect($type->label())->toBe('Document'); +test('linkedin post content types accept images, videos and documents but never mixed', function () { + foreach ([ContentType::LinkedInPost, ContentType::LinkedInPagePost] as $type) { + expect($type->supportsImage())->toBeTrue(); + expect($type->supportsVideo())->toBeTrue(); expect($type->supportsDocument())->toBeTrue(); - expect($type->supportsImage())->toBeFalse(); - expect($type->supportsVideo())->toBeFalse(); - expect($type->requiresMedia())->toBeTrue(); - expect($type->maxMediaCount())->toBe(1); + expect($type->supportsMixedMedia())->toBeFalse(); + expect($type->requiresMedia())->toBeFalse(); + expect($type->maxMediaCount())->toBe(20); } - - expect(ContentType::LinkedInDocument->platform())->toBe(Platform::LinkedIn); - expect(ContentType::LinkedInPageDocument->platform())->toBe(Platform::LinkedInPage); }); -test('only linkedin document content types support documents', function () { - expect(ContentType::LinkedInPost->supportsDocument())->toBeFalse(); - expect(ContentType::LinkedInCarousel->supportsDocument())->toBeFalse(); +test('only linkedin post content types support documents', function () { + expect(ContentType::LinkedInPost->supportsDocument())->toBeTrue(); + expect(ContentType::LinkedInPagePost->supportsDocument())->toBeTrue(); expect(ContentType::InstagramFeed->supportsDocument())->toBeFalse(); expect(ContentType::XPost->supportsDocument())->toBeFalse(); }); -test('linkedin document content types are exposed for their platform', function () { - expect(ContentType::forPlatform(Platform::LinkedIn))->toContain(ContentType::LinkedInDocument); - expect(ContentType::forPlatform(Platform::LinkedInPage))->toContain(ContentType::LinkedInPageDocument); +test('linkedin exposes a single post content type per account kind', function () { + expect(ContentType::forPlatform(Platform::LinkedIn))->toHaveCount(1)->toContain(ContentType::LinkedInPost); + expect(ContentType::forPlatform(Platform::LinkedInPage))->toHaveCount(1)->toContain(ContentType::LinkedInPagePost); }); diff --git a/tests/Unit/Enums/PlatformTest.php b/tests/Unit/Enums/PlatformTest.php index 65915963..f0f496a6 100644 --- a/tests/Unit/Enums/PlatformTest.php +++ b/tests/Unit/Enums/PlatformTest.php @@ -45,7 +45,7 @@ }); test('platform has correct max images', function () { - expect(Platform::LinkedIn->maxImages())->toBe(1); + expect(Platform::LinkedIn->maxImages())->toBe(20); expect(Platform::X->maxImages())->toBe(4); expect(Platform::TikTok->maxImages())->toBe(0); expect(Platform::YouTube->maxImages())->toBe(0); @@ -110,3 +110,25 @@ expect($enabled)->not->toContain(Platform::LinkedIn); }); + +test('only linkedin pages are not directly connectable', function () { + expect(Platform::LinkedInPage->isConnectable())->toBeFalse(); + expect(Platform::LinkedIn->isConnectable())->toBeTrue(); + expect(Platform::InstagramFacebook->isConnectable())->toBeTrue(); + expect(Platform::Instagram->isConnectable())->toBeTrue(); +}); + +test('the linkedin card is connectable while either capability is enabled', function () { + config(['trypost.platforms.linkedin.enabled' => true, 'trypost.platforms.linkedin-page.enabled' => false]); + expect(Platform::LinkedIn->isConnectable())->toBeTrue(); + + config(['trypost.platforms.linkedin.enabled' => false, 'trypost.platforms.linkedin-page.enabled' => true]); + expect(Platform::LinkedIn->isConnectable())->toBeTrue(); + + config(['trypost.platforms.linkedin.enabled' => false, 'trypost.platforms.linkedin-page.enabled' => false]); + expect(Platform::LinkedIn->isConnectable())->toBeFalse(); + + // A company page never gets its own card regardless of toggles. + config(['trypost.platforms.linkedin-page.enabled' => true]); + expect(Platform::LinkedInPage->isConnectable())->toBeFalse(); +}); diff --git a/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php b/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php index a557d163..011769f3 100644 --- a/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php +++ b/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php @@ -136,71 +136,90 @@ function runMediaRule(string $contentType, array $media): array expect(runMediaRule(ContentType::DiscordMessage->value, $media))->toBe([]); }); -test('linkedin document accepts a pdf', function () { +test('linkedin post accepts a pdf on its own', function () { $media = [['type' => MediaType::Document->value, 'mime_type' => 'application/pdf']]; - expect(runMediaRule(ContentType::LinkedInDocument->value, $media))->toBe([]); - expect(runMediaRule(ContentType::LinkedInPageDocument->value, $media))->toBe([]); + expect(runMediaRule(ContentType::LinkedInPost->value, $media))->toBe([]); + expect(runMediaRule(ContentType::LinkedInPagePost->value, $media))->toBe([]); }); -test('linkedin document detects a pdf from mime when type field is missing', function () { +test('linkedin post detects a pdf from mime when type field is missing', function () { $media = [['mime_type' => 'application/pdf']]; - expect(runMediaRule(ContentType::LinkedInDocument->value, $media))->toBe([]); + expect(runMediaRule(ContentType::LinkedInPost->value, $media))->toBe([]); }); -test('linkedin document rejects an image', function () { - $media = [['type' => MediaType::Image->value, 'mime_type' => 'image/jpeg']]; - - $errors = runMediaRule(ContentType::LinkedInDocument->value, $media); - - expect($errors)->toHaveCount(1); - expect($errors[0])->toContain('does not support images'); -}); - -test('a pdf is rejected on content types that are not documents', function () { - $media = [['type' => MediaType::Document->value, 'mime_type' => 'application/pdf']]; +test('a pdf must be the only attachment on linkedin', function () { + $media = [ + ['type' => MediaType::Document->value, 'mime_type' => 'application/pdf'], + ['type' => MediaType::Image->value, 'mime_type' => 'image/jpeg'], + ]; $errors = runMediaRule(ContentType::LinkedInPost->value, $media); expect($errors)->toHaveCount(1); - expect($errors[0])->toContain('does not support PDF documents'); + expect($errors[0])->toContain('must be the only attachment'); +}); - expect(runMediaRule(ContentType::LinkedInCarousel->value, $media)[0])->toContain('does not support PDF documents'); +test('linkedin rejects mixing an image and a video', function () { + $media = [ + ['type' => MediaType::Image->value, 'mime_type' => 'image/jpeg'], + ['type' => MediaType::Video->value, 'mime_type' => 'video/mp4'], + ]; + + $errors = runMediaRule(ContentType::LinkedInPost->value, $media); + + expect($errors)->toHaveCount(1); + expect($errors[0])->toContain("can't combine an image and a video"); +}); + +test('a pdf is rejected on content types that do not support documents', function () { + $media = [['type' => MediaType::Document->value, 'mime_type' => 'application/pdf']]; + + $errors = runMediaRule(ContentType::XPost->value, $media); + + expect($errors)->toHaveCount(1); + expect($errors[0])->toContain('does not support PDF documents'); }); test('falls back to stored media when the request omits the media key', function () { + // A PDF fallback on a document-capable type passes. $errors = []; (new ContentTypeCompatibleWithMedia([['type' => 'document', 'mime_type' => 'application/pdf']])) ->setData([]) // no 'media' key in the request -> use the fallback - ->validate('platforms.0.content_type', ContentType::LinkedInDocument->value, function (string $message) use (&$errors): void { + ->validate('platforms.0.content_type', ContentType::LinkedInPost->value, function (string $message) use (&$errors): void { $errors[] = $message; }); expect($errors)->toBe([]); - $imageErrors = []; - (new ContentTypeCompatibleWithMedia([['type' => 'image', 'mime_type' => 'image/jpeg']])) + // The same PDF fallback on X (no document support) is rejected — proving the fallback is used. + $xErrors = []; + (new ContentTypeCompatibleWithMedia([['type' => 'document', 'mime_type' => 'application/pdf']])) ->setData([]) - ->validate('platforms.0.content_type', ContentType::LinkedInDocument->value, function (string $message) use (&$imageErrors): void { - $imageErrors[] = $message; + ->validate('platforms.0.content_type', ContentType::XPost->value, function (string $message) use (&$xErrors): void { + $xErrors[] = $message; }); - expect($imageErrors)->toHaveCount(1); - expect($imageErrors[0])->toContain('does not support images'); + expect($xErrors)->toHaveCount(1); + expect($xErrors[0])->toContain('does not support PDF documents'); }); test('request media takes precedence over the stored fallback', function () { - // Fallback is a PDF, but the request explicitly carries an image instead. + // Fallback is a lone PDF (would pass), but the request carries a PDF + image, + // which must be rejected — proving the request media is used over the fallback. $errors = []; (new ContentTypeCompatibleWithMedia([['type' => 'document', 'mime_type' => 'application/pdf']])) - ->setData(['media' => [['type' => 'image', 'mime_type' => 'image/jpeg']]]) - ->validate('platforms.0.content_type', ContentType::LinkedInDocument->value, function (string $message) use (&$errors): void { + ->setData(['media' => [ + ['type' => 'document', 'mime_type' => 'application/pdf'], + ['type' => 'image', 'mime_type' => 'image/jpeg'], + ]]) + ->validate('platforms.0.content_type', ContentType::LinkedInPost->value, function (string $message) use (&$errors): void { $errors[] = $message; }); expect($errors)->toHaveCount(1); - expect($errors[0])->toContain('does not support images'); + expect($errors[0])->toContain('must be the only attachment'); }); test('does nothing for invalid content type values', function () { diff --git a/tests/Unit/Rules/ContentTypeMatchesPlatformTest.php b/tests/Unit/Rules/ContentTypeMatchesPlatformTest.php index 8a0fce74..c3fe5352 100644 --- a/tests/Unit/Rules/ContentTypeMatchesPlatformTest.php +++ b/tests/Unit/Rules/ContentTypeMatchesPlatformTest.php @@ -35,7 +35,6 @@ function runMatchesPlatformRule(string $contentType, ?string $accountId, array $ ]); expect(runMatchesPlatformRule(ContentType::LinkedInPost->value, $linkedin->id))->toBe([]); - expect(runMatchesPlatformRule(ContentType::LinkedInCarousel->value, $linkedin->id))->toBe([]); }); test('fails when content_type belongs to a different platform', function () { diff --git a/tests/Unit/Rules/ContentTypeMatchesPostPlatformTest.php b/tests/Unit/Rules/ContentTypeMatchesPostPlatformTest.php index cb4f22db..0c0396c0 100644 --- a/tests/Unit/Rules/ContentTypeMatchesPostPlatformTest.php +++ b/tests/Unit/Rules/ContentTypeMatchesPostPlatformTest.php @@ -42,7 +42,6 @@ function runMatchesPostPlatformRule(string $contentType, ?string $postPlatformId ]); expect(runMatchesPostPlatformRule(ContentType::LinkedInPost->value, $postPlatform->id))->toBe([]); - expect(runMatchesPostPlatformRule(ContentType::LinkedInCarousel->value, $postPlatform->id))->toBe([]); }); test('fails when content_type belongs to a different platform than the post_platform', function () { From dec2bc028a57ce8484a3b96b6e0f82eb6207653c Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Wed, 24 Jun 2026 21:23:27 -0300 Subject: [PATCH 06/22] fix(linkedin): show connected company page on the accounts and onboarding grids MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The unified LinkedIn card grouped connected accounts by looking the platform up in the rendered card list, but linkedin-page is no longer a card — so an org-only connection fell through to its own network key and the card showed 'Connect' for an already-connected page, with no way to disconnect or reconnect. Expose each account's network on SocialAccountResource and group by account.network instead. Onboarding still built its connect grid from SocialPlatform::enabled() instead of isConnectable(), so it rendered a standalone LinkedIn Page card with a missing logo whose connect button hit the deleted connect/linkedin-page route (404). Filter by isConnectable() to match the accounts page. --- .../Controllers/App/OnboardingController.php | 14 ++++++++------ app/Http/Resources/App/SocialAccountResource.php | 1 + .../components/accounts/NetworkConnectGrid.vue | 11 +++-------- .../Onboarding/OnboardingControllerTest.php | 16 ++++++++++++++++ tests/Feature/SocialControllerTest.php | 3 +++ 5 files changed, 31 insertions(+), 14 deletions(-) diff --git a/app/Http/Controllers/App/OnboardingController.php b/app/Http/Controllers/App/OnboardingController.php index 06410983..1c488797 100644 --- a/app/Http/Controllers/App/OnboardingController.php +++ b/app/Http/Controllers/App/OnboardingController.php @@ -86,12 +86,14 @@ public function connect(Request $request): Response|RedirectResponse $accounts = $workspace->socialAccounts()->orderBy('id')->get(); - $platforms = collect(SocialPlatform::enabled())->map(fn (SocialPlatform $platform): array => [ - 'value' => $platform->value, - 'label' => $platform->label(), - 'color' => $platform->color(), - 'network' => $platform->network(), - ])->values(); + $platforms = collect(SocialPlatform::cases()) + ->filter(fn (SocialPlatform $platform): bool => $platform->isConnectable()) + ->map(fn (SocialPlatform $platform): array => [ + 'value' => $platform->value, + 'label' => $platform->label(), + 'color' => $platform->color(), + 'network' => $platform->network(), + ])->values(); return Inertia::render('onboarding/Connect', [ 'platforms' => $platforms, diff --git a/app/Http/Resources/App/SocialAccountResource.php b/app/Http/Resources/App/SocialAccountResource.php index bee0dda4..e4bef4e5 100644 --- a/app/Http/Resources/App/SocialAccountResource.php +++ b/app/Http/Resources/App/SocialAccountResource.php @@ -17,6 +17,7 @@ public function toArray(Request $request): array return [ 'id' => $this->id, 'platform' => $this->platform, + 'network' => $this->platform->network(), 'platform_user_id' => $this->platform_user_id, 'username' => $this->username, 'display_name' => $this->display_name, diff --git a/resources/js/components/accounts/NetworkConnectGrid.vue b/resources/js/components/accounts/NetworkConnectGrid.vue index 4808ae54..7e916b04 100644 --- a/resources/js/components/accounts/NetworkConnectGrid.vue +++ b/resources/js/components/accounts/NetworkConnectGrid.vue @@ -21,6 +21,7 @@ export interface AvailablePlatform { export interface ConnectedAccount { id: string; platform: string; + network: string; username: string; display_name: string; avatar_url: string | null; @@ -120,20 +121,14 @@ const platformTheme: Record< const themeFor = (value: string) => platformTheme[value] ?? { bg: 'bg-muted', rotate: '', image: '' }; -const networkOf = (value: string): string => - props.platforms.find((platform) => platform.value === value)?.network ?? - value; - // One account per network: map each connected network to its account so every // platform card belonging to that network reflects the connection. const connectedByNetwork = computed((): Record => { const map: Record = {}; for (const account of props.connectedAccounts) { - const network = networkOf(account.platform); - - if (!map[network]) { - map[network] = account; + if (!map[account.network]) { + map[account.network] = account; } } diff --git a/tests/Feature/Onboarding/OnboardingControllerTest.php b/tests/Feature/Onboarding/OnboardingControllerTest.php index ba489b97..aac0c9bd 100644 --- a/tests/Feature/Onboarding/OnboardingControllerTest.php +++ b/tests/Feature/Onboarding/OnboardingControllerTest.php @@ -4,6 +4,7 @@ use App\Actions\Billing\StartSubscriptionCheckout; use App\Enums\Plan\Slug; +use App\Enums\SocialAccount\Platform; use App\Enums\User\Persona; use App\Jobs\PostHog\SendEvent; use App\Models\Account; @@ -135,6 +136,21 @@ function subscribeOnboardingAccount(Account $account): void ); }); +test('connect offers a single linkedin card and no standalone linkedin page card', function () { + $this->user->update(['persona' => Persona::Agency->value]); + onboardingWorkspace($this->user); + + $response = $this->actingAs($this->user->fresh())->get(route('app.onboarding.connect')); + + $response->assertOk(); + $response->assertInertia(fn ($page) => $page + ->component('onboarding/Connect') + ->where('platforms', fn ($platforms) => collect($platforms)->contains('value', Platform::LinkedIn->value) + && ! collect($platforms)->contains('value', Platform::LinkedInPage->value) + ) + ); +}); + test('connect lists the workspace social accounts already connected', function () { $this->user->update(['persona' => Persona::Agency->value]); $workspace = onboardingWorkspace($this->user); diff --git a/tests/Feature/SocialControllerTest.php b/tests/Feature/SocialControllerTest.php index 9a99e62a..12b960f0 100644 --- a/tests/Feature/SocialControllerTest.php +++ b/tests/Feature/SocialControllerTest.php @@ -87,9 +87,12 @@ $response = $this->actingAs($this->user)->get(route('app.accounts')); $response->assertOk(); + // The grid groups by the account's own `network`, so a linkedin-page account + // must report network=linkedin to surface under the single LinkedIn card. $response->assertInertia(fn ($page) => $page ->component('accounts/Index', false) ->where('connectedAccounts.0.platform', Platform::LinkedInPage->value) + ->where('connectedAccounts.0.network', 'linkedin') ); }); From 6184807abad74703ad08b9abda57a8343125f63b Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Wed, 24 Jun 2026 21:39:33 -0300 Subject: [PATCH 07/22] refactor(linkedin): drop now-unused Platform::enabled() helper The accounts grid and onboarding both build their connect-card list from cases()->filter(isConnectable()) now, leaving the static enabled() helper without any production caller. Remove it and the two unit tests that only exercised it. --- app/Enums/SocialAccount/Platform.php | 10 ---------- tests/Unit/Enums/PlatformTest.php | 15 --------------- 2 files changed, 25 deletions(-) diff --git a/app/Enums/SocialAccount/Platform.php b/app/Enums/SocialAccount/Platform.php index 213f1921..85ee8416 100644 --- a/app/Enums/SocialAccount/Platform.php +++ b/app/Enums/SocialAccount/Platform.php @@ -325,14 +325,4 @@ public function publishConfig(): array default => [], }; } - - /** - * Get all enabled platforms. - * - * @return array - */ - public static function enabled(): array - { - return array_filter(self::cases(), fn (self $platform) => $platform->isEnabled()); - } } diff --git a/tests/Unit/Enums/PlatformTest.php b/tests/Unit/Enums/PlatformTest.php index f0f496a6..b2587f45 100644 --- a/tests/Unit/Enums/PlatformTest.php +++ b/tests/Unit/Enums/PlatformTest.php @@ -96,21 +96,6 @@ expect(Platform::LinkedIn->isEnabled())->toBeFalse(); }); -test('can get all enabled platforms', function () { - $enabled = Platform::enabled(); - - expect($enabled)->toBeArray(); - expect(count($enabled))->toBeGreaterThan(0); -}); - -test('disabled platforms are excluded from enabled list', function () { - config(['trypost.platforms.linkedin.enabled' => false]); - - $enabled = Platform::enabled(); - - expect($enabled)->not->toContain(Platform::LinkedIn); -}); - test('only linkedin pages are not directly connectable', function () { expect(Platform::LinkedInPage->isConnectable())->toBeFalse(); expect(Platform::LinkedIn->isConnectable())->toBeTrue(); From 428b8a5b2724a8f334ce592ef12dda804fb864b6 Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Thu, 25 Jun 2026 09:45:15 -0300 Subject: [PATCH 08/22] fix(posts): preserve gallery media metadata and polish LinkedIn PDF settings Selecting media in the gallery dropped original_filename, size, and meta when building the picked item, so they never reached the post. Since the gallery is the only way to add media, this left PDF documents without a filename (empty title field, 'PDF' thumbnail label, 'Document' fallback on publish) and skipped size/duration validation for all gallery media. Carry those fields through (guarded for unsplash/giphy items that lack them). LinkedIn settings module: render only when a PDF is attached (its only relevant config now that format is inferred from media), pre-fill the document title from the PDF filename (editable), drop the redundant media warning (already surfaced on the channel) and the unused contentType prop/binding. LinkedInSelect: add Person/Organization tag icons. i18n: clearer document-not-alone message in all locales. --- lang/en/posts.php | 4 +-- lang/es/posts.php | 4 +-- lang/pt-BR/posts.php | 4 +-- .../js/components/ChannelConfigurator.vue | 1 - .../js/components/assets/GalleryBrowser.vue | 3 ++ .../posts/editor/LinkedInSettings.vue | 32 ++++++++----------- .../js/pages/accounts/LinkedInSelect.vue | 13 ++++++-- 7 files changed, 32 insertions(+), 29 deletions(-) diff --git a/lang/en/posts.php b/lang/en/posts.php index d2cd6f8f..6d6987f8 100644 --- a/lang/en/posts.php +++ b/lang/en/posts.php @@ -187,7 +187,7 @@ 'no_image_allowed' => 'This post type accepts only videos.', 'no_document_allowed' => 'This post type does not accept PDF documents.', 'no_mixed_media' => "Images and a video can't be combined in the same post.", - 'document_not_alone' => 'A PDF must be the only attachment.', + 'document_not_alone' => 'A PDF must be posted on its own, without other images or videos.', 'gif_not_allowed' => 'This platform does not accept GIF. Remove the GIF or choose a different network.', 'image_too_large' => 'Image exceeds the :max limit for this post type (yours is :current).', 'video_too_large' => 'Video exceeds the :max limit for this post type (yours is :current).', @@ -346,7 +346,7 @@ 'no_mixed_media' => "Images and videos can't be combined in the same post.", 'no_gifs' => 'GIFs are not supported here.', 'no_documents' => 'PDF documents are not supported by this format.', - 'document_not_alone' => 'A PDF must be the only attachment.', + 'document_not_alone' => 'A PDF must be posted on its own, without other images or videos.', 'video_too_large' => 'Video exceeds the size limit for this platform.', 'video_too_long' => 'Video must be under :seconds seconds for this format.', 'image_too_large' => 'Image exceeds the size limit for this platform.', diff --git a/lang/es/posts.php b/lang/es/posts.php index 67774af0..c4c3af01 100644 --- a/lang/es/posts.php +++ b/lang/es/posts.php @@ -187,7 +187,7 @@ 'no_image_allowed' => 'Este tipo acepta solo videos.', 'no_document_allowed' => 'Este tipo no acepta documentos PDF.', 'no_mixed_media' => 'No se pueden combinar imágenes y un video en la misma publicación.', - 'document_not_alone' => 'Un PDF debe ser el único archivo adjunto.', + 'document_not_alone' => 'Un PDF debe publicarse solo, sin otras imágenes ni videos.', 'gif_not_allowed' => 'Esta red no acepta GIF. Elimínalo o selecciona otra red.', 'image_too_large' => 'La imagen supera el límite de :max (la tuya es :current).', 'video_too_large' => 'El video supera el límite de :max (el tuyo es :current).', @@ -346,7 +346,7 @@ 'no_mixed_media' => 'No se pueden combinar imágenes y videos en la misma publicación.', 'no_gifs' => 'Los GIFs no son compatibles aquí.', 'no_documents' => 'Los documentos PDF no son compatibles con este formato.', - 'document_not_alone' => 'Un PDF debe ser el único archivo adjunto.', + 'document_not_alone' => 'Un PDF debe publicarse solo, sin otras imágenes ni videos.', 'video_too_large' => 'El video supera el límite de tamaño de esta plataforma.', 'video_too_long' => 'El video debe durar menos de :seconds segundos en este formato.', 'image_too_large' => 'La imagen supera el límite de tamaño de esta plataforma.', diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.php index 515c8d31..1f0b03c5 100644 --- a/lang/pt-BR/posts.php +++ b/lang/pt-BR/posts.php @@ -187,7 +187,7 @@ 'no_image_allowed' => 'Este tipo aceita apenas vídeos.', 'no_document_allowed' => 'Este tipo não aceita documentos PDF.', 'no_mixed_media' => 'Não dá pra combinar imagens e um vídeo no mesmo post.', - 'document_not_alone' => 'Um PDF deve ser o único anexo.', + 'document_not_alone' => 'Um PDF precisa ser publicado sozinho, sem outras imagens ou vídeos.', 'gif_not_allowed' => 'Esta rede não aceita GIF. Remova o GIF ou escolha outra rede.', 'image_too_large' => 'A imagem passa do limite de :max (a sua tem :current).', 'video_too_large' => 'O vídeo passa do limite de :max (o seu tem :current).', @@ -346,7 +346,7 @@ 'no_mixed_media' => 'Não é possível combinar imagem e vídeo na mesma publicação.', 'no_gifs' => 'GIFs não são suportados aqui.', 'no_documents' => 'Documentos PDF não são suportados por este formato.', - 'document_not_alone' => 'Um PDF deve ser o único anexo.', + 'document_not_alone' => 'Um PDF precisa ser publicado sozinho, sem outras imagens ou vídeos.', 'video_too_large' => 'Vídeo excede o limite de tamanho desta plataforma.', 'video_too_long' => 'Vídeo deve ter menos de :seconds segundos neste formato.', 'image_too_large' => 'Imagem excede o limite de tamanho desta plataforma.', diff --git a/resources/js/components/ChannelConfigurator.vue b/resources/js/components/ChannelConfigurator.vue index 32f5f711..1feb31e2 100644 --- a/resources/js/components/ChannelConfigurator.vue +++ b/resources/js/components/ChannelConfigurator.vue @@ -163,7 +163,6 @@ const selectedChannels = computed(() => props.channels.filter((channel) => isSel v-else-if="channel.platform === Platform.LinkedIn || channel.platform === Platform.LinkedInPage" :social-account="channel.socialAccount" :platform="channel.platform" - :content-type="channel.contentType" :media="media" :meta="channel.meta" :disabled="disabled" diff --git a/resources/js/components/assets/GalleryBrowser.vue b/resources/js/components/assets/GalleryBrowser.vue index 3ef9f68e..882a87d8 100644 --- a/resources/js/components/assets/GalleryBrowser.vue +++ b/resources/js/components/assets/GalleryBrowser.vue @@ -140,6 +140,9 @@ const toggleSelect = (asset: AssetMedia | SavedMedia, extra?: Partial -import { IconAlertTriangle, IconChevronDown, IconChevronUp } from '@tabler/icons-vue'; +import { IconChevronDown, IconChevronUp } from '@tabler/icons-vue'; import { computed, ref } from 'vue'; import { Avatar } from '@/components/ui/avatar'; import { Input } from '@/components/ui/input'; -import { getMediaValidationWarning, isDocumentMedia } from '@/composables/useMedia'; +import { isDocumentMedia } from '@/composables/useMedia'; import { getPlatformLogo } from '@/composables/usePlatformLogo'; import type { MediaItem } from '@/types/media'; import { Platform } from '@/types/platform'; @@ -20,7 +20,6 @@ interface SocialAccount { interface Props { socialAccount: SocialAccount | null; platform: string; - contentType: string; media: MediaItem[]; meta?: Record; disabled?: boolean; @@ -41,20 +40,23 @@ const open = ref(false); const isPage = computed(() => props.platform === Platform.LinkedInPage); -// The publish format follows the media; the only thing to configure is the -// title shown on a document (PDF) post, so we only expose it when a PDF is set. -const hasPdf = computed(() => props.media.some((item) => isDocumentMedia(item))); +const pdfDocument = computed( + () => props.media.find((item) => isDocumentMedia(item)) ?? null, +); + +const hasPdf = computed(() => pdfDocument.value !== null); const documentTitle = computed({ - get: () => (props.meta?.document_title as string | undefined) ?? '', + get: () => + (props.meta?.document_title as string | undefined) || + pdfDocument.value?.original_filename || + '', set: (value: string) => emit('update:meta', { ...props.meta, document_title: value || null }), }); - -const warning = computed(() => getMediaValidationWarning(props.contentType, props.media)); diff --git a/resources/js/pages/accounts/LinkedInSelect.vue b/resources/js/pages/accounts/LinkedInSelect.vue index c728986e..b4b9b9ac 100644 --- a/resources/js/pages/accounts/LinkedInSelect.vue +++ b/resources/js/pages/accounts/LinkedInSelect.vue @@ -1,5 +1,10 @@ \ No newline at end of file + diff --git a/resources/js/pages/accounts/FacebookPageSelect.vue b/resources/js/pages/accounts/FacebookPageSelect.vue index f1218db5..85513db3 100644 --- a/resources/js/pages/accounts/FacebookPageSelect.vue +++ b/resources/js/pages/accounts/FacebookPageSelect.vue @@ -1,9 +1,9 @@