Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
feat: complete create + publish post flow via MCP and REST API
Paulo Castellano9a26e6d80212
diff --git a/TIKTOK_REVIEW_VIDEO_SCRIPT.md b/TIKTOK_REVIEW_VIDEO_SCRIPT.mddeleted file mode 100644index cd781fccc..000000000--- a/TIKTOK_REVIEW_VIDEO_SCRIPT.md+++ /dev/null@@ -1,333 +0,0 @@-# TikTok Direct Post API — Review Video Script--Script for re-submitting trypost to TikTok's Direct Post API audit after the initial rejection. Based on https://developers.tiktok.com/doc/content-sharing-guidelines/--Goal: in ~2–3 minutes of screen recording, prove **every** compliance requirement visually. Narration in English (reviewers are in English-speaking teams).-------## 0. Pre-recording checklist--Before hitting record, set up the state so you can flow through the script without pauses.--### Account / environment-- [ ] A **real TikTok account** connected to trypost (use your personal, not a test stub)-- [ ] Post log in production (`app.trypost.it`) — **not** localhost. Reviewers distrust `.test` domains-- [ ] `npm run build` deployed. Browser cache cleared (hard reload)-- [ ] Dev Tools closed, clean Chrome profile (no extensions bar visible)--### Content to upload-- [ ] One short vertical video (15–30s, 720p+) — original content. **Not** reposted from another platform-- [ ] A caption draft written (avoid preset auto-text — reviewer must see it's editable)-- [ ] Optional: a long video (>max duration of your account) to demonstrate the duration warning--### Workspace state-- [ ] Have a **second TikTok account** also connected — the video should demonstrate multi-account support (each collapse is per-account)-- [ ] Confirm `creator_info` is actually loading (watch Network tab once before recording)--### Recording tool-- Mac: QuickTime > File > New Screen Recording (record cursor + microphone)-- Resolution: 1440p minimum, browser window at 80% scale-- Narration: headset mic, quiet room-------## 1. Opening shot (0:00–0:10)--**Screen:** trypost dashboard home (`/calendar` or `/posts`).--**Narration:**-> "Hi TikTok team. I'm demonstrating the trypost Direct Post integration. trypost is a social media scheduler for authentic creators. Let me walk you through the posting flow for TikTok."--**Why:** establishes you're not copying from another platform and the app is a scheduler for original content (addresses "Intended Use Requirements" in the doc).-------## 2. TikTok authorization flow (0:10–0:30)--**Required by the submission form: "User flow of TikTok authorization page".**--**Screen:** navigate to `/accounts` with no TikTok account connected yet.--**Action:**-1. Click "Connect TikTok" button-2. Wait for TikTok's consent screen to load-3. Show the scopes list on TikTok's page-4. Click "Authorize"-5. Return to trypost with the account now connected (avatar + @handle visible)--**Narration:**-> "To use trypost with TikTok, the creator first authorizes our app. Clicking Connect TikTok takes me to TikTok's official consent page, where I can see the exact scopes we request: user profile, basic info, stats, and video publishing permissions. Once I authorize, I'm returned to trypost and my TikTok account is connected."--**What MUST be visible:**-- trypost's Connect TikTok button-- TikTok's native authorization page (not a clone — the real `open-api.tiktok.com/platform/oauth/connect/` screen)-- The scope list on TikTok's page-- Return redirect back to trypost with the account populated--## 3. Open post editor — creator_info fetched (0:30–0:45)--**Screen:** click "Create post" or open an existing draft.--**Action:** just wait 1–2s for the editor to render.--**Narration:**-> "Now I'll open the post editor. When it loads, trypost automatically fetches the latest creator_info for my TikTok account, so all visibility options and interaction settings you'll see reflect my current account state."--**What MUST be visible:**-- The post editor with the TikTok account nickname visible-- Optional: DevTools Network tab briefly showing the `post/publish/creator_info/query/` call-------## 3. Compose + media upload (0:25–0:40)--**Screen:** post composer.--**Action:**-1. Type a caption manually (e.g. "Testing the TikTok Direct Post integration")-2. Upload the video--**Narration:**-> "I'll write my caption here — notice the caption field is fully editable; trypost does not inject any preset text or hashtags. Now I'll add my video, which I recorded myself."--**What MUST be visible:**-- Caption is user-typed (no auto-fill)-- Media upload visible-- No watermarks or promotional logos added anywhere by trypost-------## 4. Open the Schedule tab + show creator nickname (0:40–0:55)--**Screen:** right sidebar, click "Schedule" tab.--**Action:** click on the TikTok platform in "Publish to" to select it.--**Narration:**-> "I'll select my TikTok account to publish to. Notice the creator's nickname is displayed here so I know exactly which TikTok account this will post to."--**What MUST be visible:**-- The TikTok platform card with **avatar + nickname visible** (not hidden in tooltip)-- Account visibly selected (primary ring)-------## 5. Expand TikTok Settings — walk through each compliance field (0:55–1:45)--**Screen:** click to expand "TikTok Settings" collapse.--**Narration (go slowly here — this is the compliance core):**--### 5.1 Creator identity-> "Inside the settings, I see again which account I'm posting to: my nickname and handle."--### 5.2 Privacy level-**Action:** click the "Who can see this video?" dropdown — reveal it's empty with "Select visibility" placeholder.--> "Privacy is required — there is no default value. The user must explicitly choose a visibility. The options listed come directly from TikTok's creator_info API response, so only the visibility levels that my account can actually use are shown."--**Key moment:** hover the dropdown open so the reviewer sees the options list.--### 5.3 Interaction checkboxes-> "Next, the interaction settings — Comments, Duet, and Stitch. None of them are checked by default; I opt in to each."--**Key moment:** if any of them are greyed out on your account (because you disabled them in TikTok app settings), hover over one and show the tooltip *"Disabled by your TikTok account settings"*.--> "If any of these are disabled on my TikTok account itself, trypost respects that — the checkbox is greyed out and I cannot enable it."--### 5.4 Video made with AI-> "There's an independent toggle to declare if the video was made with AI — off by default."--### 5.5 Disclose video content toggle (CRITICAL SECTION)-**Action:** click the "Disclose video content" checkbox.--> "This is the commercial content disclosure toggle. It starts OFF by default, as required. I'll turn it on to demonstrate."--**What happens when ON:** sub-toggles "Your brand" and "Branded content" appear; a reminder text says *"You need to indicate if your content promotes yourself, a third party, or both"*.--**Action:** scroll up to the top of the page — point at the **disabled** Schedule/Post now button.--> "Right now, with the disclosure toggle on but no sub-option selected, the publish button is disabled, matching TikTok's requirement."--**Action:** back to the settings, click "Your brand" sub-toggle.--> "If I select Your brand, TikTok will classify this as Brand Organic. The disclosure reads: 'Your photo or video will be labeled as Promotional content'. Notice the agreement text below: 'By posting, you agree to TikTok's Music Usage Confirmation'."--**Action:** un-select "Your brand", click "Branded content" instead.--> "If I switch to Branded content, the label changes to 'Paid partnership', and the agreement now includes TikTok's Branded Content Policy, as required."--**Action:** open the privacy dropdown again.--> "And because branded content cannot be posted privately, the 'Only me' option is no longer available. If I had already picked 'Only me' before, trypost automatically clears the selection to force me to pick a valid one."--### 5.6 Duration warning (skip if not applicable)-If you set up the long-video scenario: show the red warning *"Video is Xs long but this account can only post videos up to Ys"*.-------## 6. Preview tab (1:45–2:00)--**Screen:** click the "Preview" tab.--**Narration:**-> "Before posting, I can preview exactly how my post will look. This is the explicit consent step — I only publish after reviewing the content here."--**What MUST be visible:**-- The preview shows the actual video + caption-- Clear that this happens before the upload-------## 7. Publish + processing notification (2:00–2:20)--**Screen:** back to the composer / schedule view.--**Action:**-1. Select a valid privacy level (e.g. Public)-2. Make sure disclose is OFF or one sub-toggle is picked-3. Click "Post now"--**Narration:**-> "I'll set privacy to public and publish. After I hit post, trypost shows me a notification saying the content may take a few minutes to process and appear on my TikTok profile — exactly what TikTok's guideline specifies."--**What MUST be visible:**-- Flash banner: *"Post is being published! It may take a few minutes to process and appear on each platform."*-- Button disables / spinner while submitting-------## 8. Verify on TikTok (2:20–2:40)--**Action:** open tiktok.com in a new tab, navigate to your profile.--**Narration:**-> "And here's the post on my TikTok profile, with the correct visibility, the interaction settings I chose, and — because I had Branded Content disclosed — the 'Paid partnership' label is applied by TikTok automatically."--**What MUST be visible:**-- The exact video just uploaded, live on the TikTok profile-- If branded content was enabled: the "Paid partnership" label-------## 9. Bonus (optional, strong signal): multi-account support (2:40–3:00)--**Screen:** go back to the post editor (or create a new post).--**Action:** select a **second** TikTok account. Show that a second, independent "TikTok Settings" collapse appears for that account.--**Narration:**-> "trypost supports posting to multiple TikTok accounts simultaneously. Each selected account gets its own settings panel with its own creator_info — so each account's privacy options and interaction rules are respected independently."--**Why this helps:** shows you understand the per-creator nature of the compliance, which matches "creator-specific restrictions" in the doc.-------## 10. Closing (3:00 end)--**Narration:**-> "That's the trypost Direct Post flow — fully aligned with TikTok's Content Sharing Guidelines. Thanks for reviewing."--**Screen:** end on the TikTok profile showing the freshly-posted video.-------## Final checklist before uploading the video--Use this as a last gate. **Every** item must be true or the rejection comes back.--### Compliance items demonstrated-- [ ] Creator nickname visible on the upload page-- [ ] Preview of content before publishing-- [ ] Privacy dropdown uses API values (not a static preset)-- [ ] Privacy has no default — user selects-- [ ] Comment / Duet / Stitch all unchecked by default-- [ ] Greyed-out interaction (shown at least once if your account has it)-- [ ] Commercial disclosure toggle default OFF-- [ ] "Your brand" sub-toggle revealed, label "Promotional content"-- [ ] "Branded content" sub-toggle, label "Paid partnership"-- [ ] "Music Usage Confirmation" text + link visible (hover the link)-- [ ] "Branded Content Policy" text + link (when branded content)-- [ ] Publish button disabled while disclose ON + no sub-toggle picked-- [ ] SELF_ONLY (Only me) removed when Branded Content is on-- [ ] Caption/title fully user-editable, no auto-presets-- [ ] Post-publish "may take a few minutes to process" notification-- [ ] Content is original (recorded by you, not reposted)--### What NOT to show-- [ ] No localhost or `.test` domain in the URL bar-- [ ] No dev tools consoles open (unless briefly for the creator_info call)-- [ ] No watermarks/promotional overlays added by trypost-- [ ] No reposted content from other platforms-- [ ] No "Other Apps / tools we compete with" references-- [ ] No preset hashtags or AI-generated caption that the user didn't edit--### Technical-- [ ] Video resolution ≥ 1080p-- [ ] Clear, slow narration in English-- [ ] Cursor visible at each click-- [ ] Total length 2–4 minutes-- [ ] Exported as mp4, < 100MB-------## Why the last submission was rejected (so you know what changed)--Based on the doc, the previous build likely violated:-1. Privacy level had a default (`SELF_ONLY`)-2. Comments checkbox was pre-checked-3. No "Paid partnership" label when branded content selected-4. No block on SELF_ONLY + branded content-5. Publish button not disabled when disclose ON without sub-toggle-6. No creator_info fetched — interactions & privacy options were static-7. No max-duration check-8. No processing-time notification--All addressed in this build. The video above deliberately demonstrates each of these fixes in order.-------## Submission notes--When submitting on TikTok's developer portal for the **Direct Post API audit**:-- Paste a direct link to the video (YouTube unlisted, Loom, or upload in the form)-- In the text field, reference this doc: "See attached video demonstrating compliance with Content Sharing Guidelines sections: creator_info fetch, mandatory metadata, commercial content disclosure labels, privacy restrictions for branded content, publish-button gating, processing notification."-- The video intentionally does not include the OAuth/authentication flow, which falls under the Login Kit audit, not Direct Post API.-- If asked about unaudited-client-restrictions: confirm your test accounts are currently private and posts went to SELF_ONLY during development.-------# 📋 Form Answers (copy / paste)--## Describe your organization's work as it relates to TikTok--trypost is a social media scheduling platform that helps authentic creators, small businesses, and agencies plan, schedule, and publish original content across multiple social networks from a single workspace. Our integration with TikTok enables users to compose and schedule short-form video content for their own TikTok accounts, select per-post settings (privacy level, interaction permissions, commercial disclosure) in full compliance with TikTok's Content Sharing Guidelines, preview content before publishing, and manage multiple TikTok accounts side by side — each account's creator_info (privacy options, interaction rules, max video duration) is respected independently.--We do not repost content from other platforms, inject promotional watermarks, or automate content without explicit user action. Every post is composed, reviewed, and published only upon the user's explicit confirmation. Our role is purely to give creators a better scheduling workflow for content they already own.--## Explain the goal of your application and how Content Posting API integration can be beneficial--trypost helps creators and agencies publish original content consistently across social networks from one workspace, so they can focus on content instead of logging into each platform daily. The Content Posting API is essential because it lets us publish directly to TikTok at scheduled times, fetch creator_info at post time so each account's privacy options, interaction rules and max video duration are respected, and enforce TikTok's Content Sharing Guidelines in the UI — including the commercial disclosure flow, the "Promotional content" / "Paid partnership" labels, and the Music Usage and Branded Content Policy declarations. This benefits TikTok by ensuring uploads go through official endpoints (PULL_FROM_URL, status polling, token refresh), and commercial content is correctly disclosed before it reaches the platform.--## Explain how you determined the daily usage estimate (less than 100)--trypost launched publicly very recently, so our active user base is still small. Our current sign-up volume and TikTok account connection rate put realistic daily publishing on TikTok in the low double digits at most, with clear headroom before approaching 100. We chose this tier because it reflects actual observed usage, not a projection we cannot yet back with data. When real traction pushes us close to the cap, we will reapply with concrete numbers from our analytics to request a higher tier.--## Please list the API response data fields that your API client will save in its database--From /v2/oauth/token/ and /v2/user/info/ (social_accounts table):-- open_id (stored as platform_user_id)-- display_name-- username-- avatar_url (image copied to our storage)-- access_token (encrypted at rest)-- refresh_token (encrypted at rest)-- expires_in (converted to a timestamp)-- granted scopes--From /v2/post/publish/video/init/, /content/init/ and /status/fetch/ (post_platforms table):-- publish_id-- publicaly_available_post_id--Responses from /v2/post/publish/creator_info/query/ and analytics endpoints are fetched on demand and not persisted.diff --git a/app/Actions/Post/CreatePost.php b/app/Actions/Post/CreatePost.phpindex 413bdfbe0..d9a488826 100644--- a/app/Actions/Post/CreatePost.php+++ b/app/Actions/Post/CreatePost.php@@ -9,26 +9,74 @@ use App\Models\Post;use App\Models\User;use App\Models\Workspace;use Carbon\Carbon;+use Illuminate\Support\Facades\DB;class CreatePost{+ /**+ * Create a Post with optional platform selection.+ *+ * `platforms[]` enables specific social accounts. Each entry takes+ * `social_account_id` and an optional `content_type` (defaults to the+ * platform's default). Accounts not listed remain disabled but are still+ * created via SyncPostPlatforms so the user can toggle them later in the+ * editor.+ *+ * @param array{+ * content?: ?string,+ * media?: array<int, mixed>,+ * date?: ?string,+ * scheduled_at?: ?string,+ * platforms?: array<int, array{social_account_id: string, content_type?: string}>+ * } $data+ */public static function execute(Workspace $workspace, User $user, array $data): Post{- $date = data_get($data, 'date') ?: Carbon::now('UTC')->format('Y-m-d');- $scheduledAt = Carbon::parse($date, 'UTC')- ->setTime(9, 0)- ->utc();+ $scheduledAt = self::resolveScheduledAt($data);++ return DB::transaction(function () use ($workspace, $user, $data, $scheduledAt): Post {+ $post = $workspace->posts()->create([+ 'user_id' => $user->id,+ 'content' => data_get($data, 'content', ''),+ 'media' => data_get($data, 'media', []),+ 'status' => PostStatus::Draft,+ 'scheduled_at' => $scheduledAt,+ ]);++ SyncPostPlatforms::execute($post);++ foreach (data_get($data, 'platforms', []) as $platformData) {+ $accountId = data_get($platformData, 'social_account_id');+ if (! $accountId) {+ continue;+ }++ $updates = ['enabled' => true];++ if ($contentType = data_get($platformData, 'content_type')) {+ $updates['content_type'] = $contentType;+ }- $post = $workspace->posts()->create([- 'user_id' => $user->id,- 'content' => data_get($data, 'content', ''),- 'media' => data_get($data, 'media', []),- 'status' => PostStatus::Draft,- 'scheduled_at' => $scheduledAt,- ]);+ $post->postPlatforms()+ ->where('social_account_id', $accountId)+ ->update($updates);+ }- SyncPostPlatforms::execute($post);+ return $post;+ });+ }++ /**+ * @param array<string, mixed> $data+ */+ private static function resolveScheduledAt(array $data): Carbon+ {+ if ($scheduledAt = data_get($data, 'scheduled_at')) {+ return Carbon::parse($scheduledAt)->utc();+ }++ $date = data_get($data, 'date') ?: Carbon::now('UTC')->format('Y-m-d');- return $post;+ return Carbon::parse($date, 'UTC')->setTime(9, 0)->utc();}}diff --git a/app/Enums/PostPlatform/ContentType.php b/app/Enums/PostPlatform/ContentType.phpindex 56973159f..15325a998 100644--- a/app/Enums/PostPlatform/ContentType.php+++ b/app/Enums/PostPlatform/ContentType.php@@ -264,15 +264,39 @@ enum ContentType: string}/**- * Get all content types for a specific platform.+ * Platforms this content_type can be assigned to. Most content types are+ * tied to a single platform; Instagram-family types (feed/carousel/reel/+ * story) work for both `Instagram` (Basic Display) and `InstagramFacebook`+ * (Business via Facebook Page) accounts.+ *+ * @return array<SocialPlatform>+ */+ public function compatiblePlatforms(): array+ {+ $primary = $this->platform();++ return match ($primary) {+ SocialPlatform::Instagram => [SocialPlatform::Instagram, SocialPlatform::InstagramFacebook],+ default => [$primary],+ };+ }++ /**+ * Get all content types for a specific platform. Treats InstagramFacebook+ * as an alias for Instagram so both flavors get the same content types.** @return array<self>*/public static function forPlatform(SocialPlatform $platform): array{+ $effective = match ($platform) {+ SocialPlatform::InstagramFacebook => SocialPlatform::Instagram,+ default => $platform,+ };+return array_filter(self::cases(),- fn (self $type) => $type->platform() === $platform+ fn (self $type) => $type->platform() === $effective);}diff --git a/app/Http/Controllers/Api/PlatformController.php b/app/Http/Controllers/Api/PlatformController.phpnew file mode 100644index 000000000..0ec9edf16--- /dev/null+++ b/app/Http/Controllers/Api/PlatformController.php@@ -0,0 +1,24 @@+<?php++declare(strict_types=1);++namespace App\Http\Controllers\Api;++use App\Enums\SocialAccount\Platform;+use App\Http\Resources\Api\PlatformContentTypesResource;+use Illuminate\Http\JsonResponse;++class PlatformController extends Controller+{+ /**+ * Index of platforms with their valid content_types and publishing+ * constraints — used by clients to build correct `platforms[].content_type`+ * payloads for `POST /api/posts` and `PUT /api/posts/{id}`.+ */+ public function contentTypes(): JsonResponse+ {+ return response()->json([+ 'platforms' => PlatformContentTypesResource::collection(Platform::cases())->resolve(),+ ]);+ }+}diff --git a/app/Http/Controllers/Api/PostController.php b/app/Http/Controllers/Api/PostController.phpindex 3f6f4ab29..e2f6ab172 100644--- a/app/Http/Controllers/Api/PostController.php+++ b/app/Http/Controllers/Api/PostController.php@@ -10,8 +10,12 @@ use App\Actions\Post\UpdatePost;use App\Enums\Post\Action as PostAction;use App\Http\Requests\Api\Post\StorePostRequest;use App\Http\Requests\Api\Post\UpdatePostRequest;+use App\Http\Resources\Api\PostMediaAttachResource;+use App\Http\Resources\Api\PostMetricsResource;+use App\Http\Resources\Api\PostPreviewResource;use App\Http\Resources\Api\PostResource;use App\Models\Post;+use App\Services\Post\MediaAttacher;use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;use Illuminate\Http\Resources\Json\AnonymousResourceCollection;@@ -31,9 +35,7 @@ class PostController extends Controllerpublic function show(Request $request, Post $post): PostResource{- if ($post->workspace_id !== $request->user()->currentWorkspace->id) {- abort(Response::HTTP_NOT_FOUND);- }+ $this->ensurePostInCurrentWorkspace($request, $post);$post->load(['postPlatforms.socialAccount', 'user', 'labels']);@@ -57,9 +59,7 @@ class PostController extends Controllerpublic function update(UpdatePostRequest $request, Post $post): PostResource|JsonResponse{- if ($post->workspace_id !== $request->user()->currentWorkspace->id) {- abort(Response::HTTP_NOT_FOUND);- }+ $this->ensurePostInCurrentWorkspace($request, $post);$result = UpdatePost::execute($request->user()->currentWorkspace, $post, $request->validated());@@ -75,12 +75,51 @@ class PostController extends Controllerpublic function destroy(Request $request, Post $post): JsonResponse{- if ($post->workspace_id !== $request->user()->currentWorkspace->id) {- abort(Response::HTTP_NOT_FOUND);- }+ $this->ensurePostInCurrentWorkspace($request, $post);DeletePost::execute($post);return response()->json(null, Response::HTTP_NO_CONTENT);}++ public function attachMedia(Request $request, Post $post): PostMediaAttachResource+ {+ $this->ensurePostInCurrentWorkspace($request, $post);++ $validated = $request->validate([+ 'urls' => ['required', 'array', 'min:1', 'max:10'],+ 'urls.*' => ['url:http,https'],+ ]);++ $result = app(MediaAttacher::class)->attachFromUrls($post, $validated['urls']);++ $post->refresh()->load(['postPlatforms.socialAccount', 'labels']);++ return new PostMediaAttachResource($post, $result);+ }++ public function metrics(Request $request, Post $post): PostMetricsResource+ {+ $this->ensurePostInCurrentWorkspace($request, $post);++ $post->load(['postPlatforms.socialAccount']);++ return new PostMetricsResource($post);+ }++ public function preview(Request $request, Post $post): PostPreviewResource+ {+ $this->ensurePostInCurrentWorkspace($request, $post);++ $post->load(['postPlatforms.socialAccount']);++ return new PostPreviewResource($post);+ }++ private function ensurePostInCurrentWorkspace(Request $request, Post $post): void+ {+ if ($post->workspace_id !== $request->user()->currentWorkspace->id) {+ abort(Response::HTTP_NOT_FOUND);+ }+ }}diff --git a/app/Http/Controllers/App/PostController.php b/app/Http/Controllers/App/PostController.phpindex d906ad951..afeba1dfc 100644--- a/app/Http/Controllers/App/PostController.php+++ b/app/Http/Controllers/App/PostController.php@@ -18,22 +18,13 @@ use App\Http\Resources\App\PlatformConfigResource;use App\Http\Resources\App\SocialAccountResource;use App\Models\Post;use App\Models\PostPlatform;-use App\Services\Social\BlueskyAnalytics;-use App\Services\Social\FacebookAnalytics;-use App\Services\Social\InstagramAnalytics;-use App\Services\Social\LinkedInPageAnalytics;-use App\Services\Social\MastodonAnalytics;-use App\Services\Social\PinterestAnalytics;+use App\Services\Post\PostMetricsFetcher;use App\Services\Social\PinterestPublisher;-use App\Services\Social\ThreadsAnalytics;use App\Services\Social\TikTokCreatorInfo;-use App\Services\Social\XAnalytics;-use App\Services\Social\YouTubeAnalytics;use Carbon\Carbon;use Illuminate\Http\JsonResponse;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;-use Illuminate\Support\Facades\Cache;use Inertia\Inertia;use Inertia\Response;@@ -186,26 +177,7 @@ class PostController extends Controllerabort(404);}- if ($postPlatform->status->value !== 'published' || ! $postPlatform->platform_post_id) {- return response()->json(['unsupported' => true, 'reason' => 'not_published']);- }-- $cacheKey = "post_metrics:{$postPlatform->id}";-- $metrics = Cache::remember($cacheKey, 300, fn () => match ($postPlatform->platform) {- Platform::X => app(XAnalytics::class)->fetchPostMetrics($postPlatform),- Platform::Bluesky => app(BlueskyAnalytics::class)->fetchPostMetrics($postPlatform),- Platform::Mastodon => app(MastodonAnalytics::class)->fetchPostMetrics($postPlatform),- Platform::Instagram, Platform::InstagramFacebook => app(InstagramAnalytics::class)->fetchPostMetrics($postPlatform),- Platform::Facebook => app(FacebookAnalytics::class)->fetchPostMetrics($postPlatform),- Platform::Threads => app(ThreadsAnalytics::class)->fetchPostMetrics($postPlatform),- Platform::LinkedInPage => app(LinkedInPageAnalytics::class)->fetchPostMetrics($postPlatform),- Platform::YouTube => app(YouTubeAnalytics::class)->fetchPostMetrics($postPlatform),- Platform::Pinterest => app(PinterestAnalytics::class)->fetchPostMetrics($postPlatform),- default => ['unsupported' => true, 'reason' => 'platform_not_supported'],- });-- return response()->json($metrics);+ return response()->json(app(PostMetricsFetcher::class)->forPlatform($postPlatform));}public function show(Request $request, Post $post): Response|RedirectResponsediff --git a/app/Http/Requests/Api/Post/StorePostRequest.php b/app/Http/Requests/Api/Post/StorePostRequest.phpindex 51b66a296..cbeb3fa37 100644--- a/app/Http/Requests/Api/Post/StorePostRequest.php+++ b/app/Http/Requests/Api/Post/StorePostRequest.php@@ -6,6 +6,7 @@ namespace App\Http\Requests\Api\Post;use App\Enums\Post\Status;use App\Enums\PostPlatform\ContentType;+use App\Rules\ContentTypeMatchesPlatform;use Illuminate\Foundation\Http\FormRequest;use Illuminate\Validation\Rule;@@ -20,8 +21,19 @@ class StorePostRequest extends FormRequest{return ['platforms' => ['required', 'array', 'min:1'],- 'platforms.*.social_account_id' => ['required', 'uuid', Rule::exists('social_accounts', 'id')->where('workspace_id', $this->user()->currentWorkspace->id)],- 'platforms.*.content_type' => ['required', 'string', Rule::in(array_column(ContentType::cases(), 'value'))],+ 'platforms.*.social_account_id' => [+ 'required',+ 'uuid',+ Rule::exists('social_accounts', 'id')+ ->where('workspace_id', $this->user()->currentWorkspace->id)+ ->where('is_active', true),+ ],+ 'platforms.*.content_type' => [+ 'required',+ 'string',+ Rule::in(array_column(ContentType::cases(), 'value')),+ new ContentTypeMatchesPlatform,+ ],'platforms.*.content' => ['nullable', 'string', 'max:63206'],'scheduled_at' => ['nullable', 'date', 'after:now'],'status' => ['nullable', 'string', Rule::in(array_column(Status::cases(), 'value'))],diff --git a/app/Http/Requests/Api/Post/UpdatePostRequest.php b/app/Http/Requests/Api/Post/UpdatePostRequest.phpindex b283660fb..29fa072a2 100644--- a/app/Http/Requests/Api/Post/UpdatePostRequest.php+++ b/app/Http/Requests/Api/Post/UpdatePostRequest.php@@ -7,6 +7,7 @@ namespace App\Http\Requests\Api\Post;use App\Enums\Post\Status;use App\Enums\PostPlatform\ContentType;use App\Models\Post;+use App\Rules\ContentTypeMatchesPostPlatform;use Illuminate\Foundation\Http\FormRequest;use Illuminate\Validation\Rule;@@ -25,7 +26,12 @@ class UpdatePostRequest extends FormRequest'media' => ['sometimes', 'array'],'platforms' => ['sometimes', 'array'],'platforms.*.id' => ['required', 'uuid', Rule::exists('post_platforms', 'id')->where('post_id', $this->route('post') instanceof Post ? $this->route('post')->id : $this->route('post'))],- 'platforms.*.content_type' => ['sometimes', 'string', Rule::in(array_column(ContentType::cases(), 'value'))],+ 'platforms.*.content_type' => [+ 'sometimes',+ 'string',+ Rule::in(array_column(ContentType::cases(), 'value')),+ new ContentTypeMatchesPostPlatform,+ ],'platforms.*.meta' => ['nullable', 'array'],'scheduled_at' => ['nullable',diff --git a/app/Http/Resources/Api/PlatformContentTypesResource.php b/app/Http/Resources/Api/PlatformContentTypesResource.phpnew file mode 100644index 000000000..1082de9fd--- /dev/null+++ b/app/Http/Resources/Api/PlatformContentTypesResource.php@@ -0,0 +1,50 @@+<?php++declare(strict_types=1);++namespace App\Http\Resources\Api;++use App\Enums\PostPlatform\ContentType;+use App\Enums\SocialAccount\Platform;+use Illuminate\Http\Request;+use Illuminate\Http\Resources\Json\JsonResource;++/**+ * Describes a single SocialPlatform with its valid content_types and+ * publishing constraints (length budgets, allowed media types, etc.).+ *+ * `JsonResource::collection(Platform::cases())` produces the full index.+ */+class PlatformContentTypesResource extends JsonResource+{+ /**+ * @return array<string, mixed>+ */+ public function toArray(Request $request): array+ {+ /** @var Platform $platform */+ $platform = $this->resource;++ return [+ 'platform' => $platform->value,+ 'label' => $platform->label(),+ 'max_content_length' => $platform->maxContentLength(),+ 'recommended_content_length' => $platform->recommendedAiContentLength(),+ 'allowed_media_types' => array_map(+ fn ($type) => $type->value,+ $platform->allowedMediaTypes(),+ ),+ 'default_content_type' => ContentType::defaultFor($platform)->value,+ 'content_types' => array_map(+ fn (ContentType $type) => [+ 'value' => $type->value,+ 'label' => $type->label(),+ 'description' => $type->description(),+ 'max_media_count' => $type->maxMediaCount(),+ 'requires_media' => $type->requiresMedia(),+ ],+ array_values(ContentType::forPlatform($platform)),+ ),+ ];+ }+}diff --git a/app/Http/Resources/Api/PostMediaAttachResource.php b/app/Http/Resources/Api/PostMediaAttachResource.phpnew file mode 100644index 000000000..8c20d9d32--- /dev/null+++ b/app/Http/Resources/Api/PostMediaAttachResource.php@@ -0,0 +1,36 @@+<?php++declare(strict_types=1);++namespace App\Http\Resources\Api;++use App\Models\Post;+use Illuminate\Http\Request;+use Illuminate\Http\Resources\Json\JsonResource;++/**+ * Wraps a Post with the result of an attach-media operation+ * (counts + list of failed URLs).+ */+class PostMediaAttachResource extends JsonResource+{+ /**+ * @param array{attached: array<int, array<string, mixed>>, failed: array<int, string>} $result+ */+ public function __construct(Post $post, private readonly array $result)+ {+ parent::__construct($post);+ }++ /**+ * @return array<string, mixed>+ */+ public function toArray(Request $request): array+ {+ return [+ 'post' => (new PostResource($this->resource))->resolve(),+ 'attached_count' => count($this->result['attached']),+ 'failed_urls' => $this->result['failed'],+ ];+ }+}diff --git a/app/Http/Resources/Api/PostMetricsResource.php b/app/Http/Resources/Api/PostMetricsResource.phpnew file mode 100644index 000000000..6724a00fc--- /dev/null+++ b/app/Http/Resources/Api/PostMetricsResource.php@@ -0,0 +1,27 @@+<?php++declare(strict_types=1);++namespace App\Http\Resources\Api;++use App\Services\Post\PostMetricsFetcher;+use Illuminate\Http\Request;+use Illuminate\Http\Resources\Json\JsonResource;++/**+ * Wraps a Post with its per-platform engagement metrics. The actual fetching+ * (with cache + per-platform dispatch) is delegated to PostMetricsFetcher.+ */+class PostMetricsResource extends JsonResource+{+ /**+ * @return array<string, mixed>+ */+ public function toArray(Request $request): array+ {+ return [+ 'post_id' => $this->id,+ 'platforms' => app(PostMetricsFetcher::class)->forPost($this->resource)->all(),+ ];+ }+}diff --git a/app/Http/Resources/Api/PostPreviewResource.php b/app/Http/Resources/Api/PostPreviewResource.phpnew file mode 100644index 000000000..3e524bdf7--- /dev/null+++ b/app/Http/Resources/Api/PostPreviewResource.php@@ -0,0 +1,24 @@+<?php++declare(strict_types=1);++namespace App\Http\Resources\Api;++use App\Services\Post\PostPreviewer;+use Illuminate\Http\Request;+use Illuminate\Http\Resources\Json\JsonResource;++/**+ * Wraps a Post with per-platform sanitized previews. Sanitization is+ * delegated to PostPreviewer (which calls ContentSanitizer).+ */+class PostPreviewResource extends JsonResource+{+ /**+ * @return array<string, mixed>+ */+ public function toArray(Request $request): array+ {+ return app(PostPreviewer::class)->forPost($this->resource);+ }+}diff --git a/app/Mcp/Servers/TryPostServer.php b/app/Mcp/Servers/TryPostServer.phpindex 95a2e0d6a..6bd9df354 100644--- a/app/Mcp/Servers/TryPostServer.php+++ b/app/Mcp/Servers/TryPostServer.php@@ -11,10 +11,16 @@ use App\Mcp\Tools\Label\CreateLabelTool;use App\Mcp\Tools\Label\DeleteLabelTool;use App\Mcp\Tools\Label\ListLabelsTool;use App\Mcp\Tools\Label\UpdateLabelTool;+use App\Mcp\Tools\Platform\ListContentTypesTool;+use App\Mcp\Tools\Post\AttachMediaFromUrlTool;use App\Mcp\Tools\Post\CreatePostTool;use App\Mcp\Tools\Post\DeletePostTool;+use App\Mcp\Tools\Post\GetPostMetricsTool;use App\Mcp\Tools\Post\GetPostTool;use App\Mcp\Tools\Post\ListPostsTool;+use App\Mcp\Tools\Post\PreviewPostTool;+use App\Mcp\Tools\Post\PublishPostTool;+use App\Mcp\Tools\Post\UpdatePostTool;use App\Mcp\Tools\Signature\CreateSignatureTool;use App\Mcp\Tools\Signature\DeleteSignatureTool;use App\Mcp\Tools\Signature\ListSignaturesTool;@@ -39,7 +45,15 @@ class TryPostServer extends ServerListPostsTool::class,GetPostTool::class,CreatePostTool::class,+ UpdatePostTool::class,+ PublishPostTool::class,+ PreviewPostTool::class,DeletePostTool::class,+ AttachMediaFromUrlTool::class,+ GetPostMetricsTool::class,++ // Platforms (read-only metadata)+ ListContentTypesTool::class,// SignaturesListSignaturesTool::class,diff --git a/app/Mcp/Tools/Platform/ListContentTypesTool.php b/app/Mcp/Tools/Platform/ListContentTypesTool.phpnew file mode 100644index 000000000..a7b3b632c--- /dev/null+++ b/app/Mcp/Tools/Platform/ListContentTypesTool.php@@ -0,0 +1,52 @@+<?php++declare(strict_types=1);++namespace App\Mcp\Tools\Platform;++use App\Enums\PostPlatform\ContentType;+use App\Enums\SocialAccount\Platform;+use Laravel\Mcp\Request;+use Laravel\Mcp\Response;+use Laravel\Mcp\ResponseFactory;+use Laravel\Mcp\Server\Attributes\Description;+use Laravel\Mcp\Server\Tool;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly]+#[Description('List the valid content_types per social platform plus their constraints (max content length, recommended length, max media count, whether media is required, default content_type). Use before create-post-tool / update-post-tool to know which content_type to set.')]+class ListContentTypesTool extends Tool+{+ public function handle(Request $request): ResponseFactory+ {+ $platforms = [];++ foreach (Platform::cases() as $platform) {+ $contentTypes = array_map(+ fn (ContentType $type) => [+ 'value' => $type->value,+ 'label' => $type->label(),+ 'description' => $type->description(),+ 'max_media_count' => $type->maxMediaCount(),+ 'requires_media' => $type->requiresMedia(),+ ],+ array_values(ContentType::forPlatform($platform)),+ );++ $platforms[] = [+ 'platform' => $platform->value,+ 'label' => $platform->label(),+ 'max_content_length' => $platform->maxContentLength(),+ 'recommended_content_length' => $platform->recommendedAiContentLength(),+ 'allowed_media_types' => array_map(+ fn ($type) => $type->value,+ $platform->allowedMediaTypes(),+ ),+ 'default_content_type' => ContentType::defaultFor($platform)->value,+ 'content_types' => $contentTypes,+ ];+ }++ return Response::structured(['platforms' => $platforms]);+ }+}diff --git a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.phpnew file mode 100644index 000000000..efd65842d--- /dev/null+++ b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php@@ -0,0 +1,59 @@+<?php++declare(strict_types=1);++namespace App\Mcp\Tools\Post;++use App\Http\Resources\Api\PostResource;+use App\Models\Post;+use App\Services\Post\MediaAttacher;+use Illuminate\Contracts\JsonSchema\JsonSchema;+use Laravel\Mcp\Request;+use Laravel\Mcp\Response;+use Laravel\Mcp\ResponseFactory;+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).')]+class AttachMediaFromUrlTool extends Tool+{+ public function handle(Request $request): Response|ResponseFactory+ {+ $validated = $request->validate([+ 'post_id' => ['required', 'uuid'],+ 'urls' => ['required', 'array', 'min:1', 'max:10'],+ 'urls.*' => ['url:http,https'],+ ]);++ $post = Post::where('workspace_id', $request->user()->current_workspace_id)+ ->find(data_get($validated, 'post_id'));++ if (! $post) {+ return Response::error('Post not found.');+ }++ $result = app(MediaAttacher::class)->attachFromUrls(+ $post,+ data_get($validated, 'urls', []),+ );++ $post->refresh()->load(['postPlatforms.socialAccount', 'labels']);++ return Response::structured([+ 'post' => (new PostResource($post))->resolve(),+ 'attached_count' => count($result['attached']),+ 'failed_urls' => $result['failed'],+ ]);+ }++ public function schema(JsonSchema $schema): array+ {+ return [+ 'post_id' => $schema->string()->required()->description('UUID of the post to attach media to.'),+ '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.'),+ ];+ }+}diff --git a/app/Mcp/Tools/Post/CreatePostTool.php b/app/Mcp/Tools/Post/CreatePostTool.phpindex 3350f8eda..4de9ac805 100644--- a/app/Mcp/Tools/Post/CreatePostTool.php+++ b/app/Mcp/Tools/Post/CreatePostTool.php@@ -5,29 +5,45 @@ declare(strict_types=1);namespace App\Mcp\Tools\Post;use App\Actions\Post\CreatePost;+use App\Enums\PostPlatform\ContentType;use App\Http\Resources\Api\PostResource;+use App\Rules\ContentTypeMatchesPlatform;use Illuminate\Contracts\JsonSchema\JsonSchema;+use Illuminate\Validation\Rule;use Laravel\Mcp\Request;use Laravel\Mcp\Response;use Laravel\Mcp\ResponseFactory;use Laravel\Mcp\Server\Attributes\Description;use Laravel\Mcp\Server\Tool;-#[Description('Create a new draft post in the current workspace. The post is automatically attached to every active social account in the workspace (one PostPlatform per account).')]+#[Description('Create a draft post in the current workspace. Accepts content, scheduled_at, label_ids, and a list of platforms (social accounts to publish on, with their content_type). Use list-content-types-tool to discover valid content_types per platform.')]class CreatePostTool extends Tool{public function handle(Request $request): ResponseFactory{+ $workspace = $request->user()->currentWorkspace;+$validated = $request->validate([- 'content' => ['nullable', 'string'],- 'date' => ['nullable', 'date_format:Y-m-d'],+ 'content' => ['nullable', 'string', 'max:63206'],+ 'scheduled_at' => ['nullable', 'date', 'after:now'],+ 'label_ids' => ['sometimes', 'array'],+ 'label_ids.*' => ['uuid', Rule::exists('workspace_labels', 'id')->where('workspace_id', $workspace->id)],+ 'platforms' => ['sometimes', 'array'],+ 'platforms.*.social_account_id' => [+ 'required',+ 'uuid',+ Rule::exists('social_accounts', 'id')+ ->where('workspace_id', $workspace->id)+ ->where('is_active', true),+ ],+ 'platforms.*.content_type' => ['required', 'string', Rule::in(array_column(ContentType::cases(), 'value')), new ContentTypeMatchesPlatform],]);- $post = CreatePost::execute(- $request->user()->currentWorkspace,- $request->user(),- $validated,- );+ $post = CreatePost::execute($workspace, $request->user(), $validated);++ if ($labelIds = data_get($validated, 'label_ids')) {+ $post->labels()->sync($labelIds);+ }$post->load(['postPlatforms.socialAccount', 'labels']);@@ -37,8 +53,17 @@ class CreatePostTool extends Toolpublic function schema(JsonSchema $schema): array{return [- 'content' => $schema->string()->description('The post caption/text content. Optional — can be edited later.'),- 'date' => $schema->string()->description('Scheduled date as Y-m-d (e.g. 2026-05-10). Defaults to today. Time is fixed at 09:00 UTC; edit the post later for a specific time.'),+ 'content' => $schema->string()->description('The post caption/text body. Optional — can be edited later.'),+ 'scheduled_at' => $schema->string()->description('ISO 8601 datetime in the future (e.g. 2026-05-10T15:30:00Z). Defaults to today at 09:00 UTC.'),+ 'label_ids' => $schema->array()+ ->items($schema->string())+ ->description('Workspace label IDs to attach to the post.'),+ 'platforms' => $schema->array()+ ->items($schema->object(fn ($p) => [+ 'social_account_id' => $p->string()->required()->description('UUID of the connected social account.'),+ 'content_type' => $p->string()->required()->description('Format for this platform (e.g. linkedin_post, x_post, instagram_feed).'),+ ]))+ ->description('Platforms to publish on. Accounts not listed remain available but disabled.'),];}}diff --git a/app/Mcp/Tools/Post/GetPostMetricsTool.php b/app/Mcp/Tools/Post/GetPostMetricsTool.phpnew file mode 100644index 000000000..b6ceb14f4--- /dev/null+++ b/app/Mcp/Tools/Post/GetPostMetricsTool.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++namespace App\Mcp\Tools\Post;++use App\Models\Post;+use App\Services\Post\PostMetricsFetcher;+use Illuminate\Contracts\JsonSchema\JsonSchema;+use Laravel\Mcp\Request;+use Laravel\Mcp\Response;+use Laravel\Mcp\ResponseFactory;+use Laravel\Mcp\Server\Attributes\Description;+use Laravel\Mcp\Server\Tool;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly]+#[Description('Fetch engagement metrics (likes, comments, shares, etc.) for a published post across all platforms it was posted to. Returns "unsupported" entries for platforms that do not expose post-level metrics or for unpublished platforms.')]+class GetPostMetricsTool extends Tool+{+ public function handle(Request $request): Response|ResponseFactory+ {+ $validated = $request->validate([+ 'post_id' => ['required', 'uuid'],+ ]);++ $post = Post::where('workspace_id', $request->user()->current_workspace_id)+ ->with(['postPlatforms.socialAccount'])+ ->find(data_get($validated, 'post_id'));++ if (! $post) {+ return Response::error('Post not found.');+ }++ return Response::structured([+ 'post_id' => $post->id,+ 'platforms' => app(PostMetricsFetcher::class)->forPost($post)->all(),+ ]);+ }++ public function schema(JsonSchema $schema): array+ {+ return [+ 'post_id' => $schema->string()->required()->description('UUID of the published post.'),+ ];+ }+}diff --git a/app/Mcp/Tools/Post/ListPostsTool.php b/app/Mcp/Tools/Post/ListPostsTool.phpindex dcaea5e4b..68d3bc5ea 100644--- a/app/Mcp/Tools/Post/ListPostsTool.php+++ b/app/Mcp/Tools/Post/ListPostsTool.php@@ -4,7 +4,10 @@ declare(strict_types=1);namespace App\Mcp\Tools\Post;+use App\Enums\Post\Status;use App\Http\Resources\Api\PostResource;+use Illuminate\Contracts\JsonSchema\JsonSchema;+use Illuminate\Validation\Rule;use Laravel\Mcp\Request;use Laravel\Mcp\Response;use Laravel\Mcp\ResponseFactory;@@ -13,20 +16,55 @@ use Laravel\Mcp\Server\Tool;use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;#[IsReadOnly]-#[Description('List posts for the current workspace, ordered by scheduled date (newest first).')]+#[Description('List posts for the current workspace, ordered by scheduled date (newest first). Optional filters: status (draft|scheduled|published) and search (matches against post content).')]class ListPostsTool extends Tool{public function handle(Request $request): ResponseFactory{- $posts = $request->user()->currentWorkspace+ $validated = $request->validate([+ 'status' => ['sometimes', 'string', Rule::in([+ Status::Draft->value,+ Status::Scheduled->value,+ Status::Published->value,+ Status::Failed->value,+ ])],+ 'search' => ['sometimes', 'string', 'max:255'],+ 'limit' => ['sometimes', 'integer', 'min:1', 'max:100'],+ ]);++ $query = $request->user()->currentWorkspace->posts()- ->with(['postPlatforms.socialAccount', 'labels'])- ->latest('scheduled_at')- ->limit(50)+ ->with(['postPlatforms.socialAccount', 'labels']);++ $query = match (data_get($validated, 'status')) {+ Status::Draft->value => $query->draft(),+ Status::Scheduled->value => $query->scheduled(),+ Status::Published->value => $query->published(),+ Status::Failed->value => $query->failed(),+ default => $query,+ };++ if ($search = data_get($validated, 'search')) {+ $query->where('content', 'ilike', '%'.$search.'%');+ }++ $posts = $query->latest('scheduled_at')+ ->limit((int) data_get($validated, 'limit', 50))->get();return Response::structured(['posts' => PostResource::collection($posts)->resolve(),]);}++ public function schema(JsonSchema $schema): array+ {+ return [+ 'status' => $schema->string()+ ->enum(['draft', 'scheduled', 'published', 'failed'])+ ->description('Filter by status. "published" includes partially-published posts.'),+ 'search' => $schema->string()->description('Case-insensitive substring match against the post content.'),+ 'limit' => $schema->integer()->description('Max results (1-100, default 50).'),+ ];+ }}diff --git a/app/Mcp/Tools/Post/PreviewPostTool.php b/app/Mcp/Tools/Post/PreviewPostTool.phpnew file mode 100644index 000000000..f4ae064c6--- /dev/null+++ b/app/Mcp/Tools/Post/PreviewPostTool.php@@ -0,0 +1,44 @@+<?php++declare(strict_types=1);++namespace App\Mcp\Tools\Post;++use App\Models\Post;+use App\Services\Post\PostPreviewer;+use Illuminate\Contracts\JsonSchema\JsonSchema;+use Laravel\Mcp\Request;+use Laravel\Mcp\Response;+use Laravel\Mcp\ResponseFactory;+use Laravel\Mcp\Server\Attributes\Description;+use Laravel\Mcp\Server\Tool;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly]+#[Description('Preview how a post will render on each enabled platform — applies platform-specific content sanitization (length truncation, forbidden chars, etc.) without publishing. Returns the original content alongside per-platform sanitized versions and length stats.')]+class PreviewPostTool extends Tool+{+ public function handle(Request $request): Response|ResponseFactory+ {+ $validated = $request->validate([+ 'post_id' => ['required', 'uuid'],+ ]);++ $post = Post::where('workspace_id', $request->user()->current_workspace_id)+ ->with(['postPlatforms.socialAccount'])+ ->find(data_get($validated, 'post_id'));++ if (! $post) {+ return Response::error('Post not found.');+ }++ return Response::structured(app(PostPreviewer::class)->forPost($post));+ }++ public function schema(JsonSchema $schema): array+ {+ return [+ 'post_id' => $schema->string()->required()->description('UUID of the post to preview.'),+ ];+ }+}diff --git a/app/Mcp/Tools/Post/PublishPostTool.php b/app/Mcp/Tools/Post/PublishPostTool.phpnew file mode 100644index 000000000..e27d9b391--- /dev/null+++ b/app/Mcp/Tools/Post/PublishPostTool.php@@ -0,0 +1,68 @@+<?php++declare(strict_types=1);++namespace App\Mcp\Tools\Post;++use App\Actions\Post\UpdatePost;+use App\Enums\Post\Action as PostAction;+use App\Enums\Post\Status;+use App\Http\Resources\Api\PostResource;+use App\Models\Post;+use Illuminate\Contracts\JsonSchema\JsonSchema;+use Laravel\Mcp\Request;+use Laravel\Mcp\Response;+use Laravel\Mcp\ResponseFactory;+use Laravel\Mcp\Server\Attributes\Description;+use Laravel\Mcp\Server\Tool;+use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;++#[IsDestructive]+#[Description('Publish a draft post — either immediately or scheduled for a future time. The post must already have at least one enabled platform. Use update-post-tool first to set content/platforms.')]+class PublishPostTool extends Tool+{+ public function handle(Request $request): Response|ResponseFactory+ {+ $workspace = $request->user()->currentWorkspace;++ $validated = $request->validate([+ 'post_id' => ['required', 'uuid'],+ 'scheduled_at' => ['nullable', 'date', 'after:now'],+ ]);++ $post = Post::where('workspace_id', $workspace->id)->find(data_get($validated, 'post_id'));++ if (! $post) {+ return Response::error('Post not found.');+ }++ if (! $post->postPlatforms()->where('enabled', true)->exists()) {+ return Response::error('Post has no enabled platforms. Use update-post-tool to enable at least one platform first.');+ }++ $scheduledAt = data_get($validated, 'scheduled_at');++ $result = UpdatePost::execute($workspace, $post, [+ 'status' => $scheduledAt ? Status::Scheduled->value : Status::Publishing->value,+ 'scheduled_at' => $scheduledAt,+ ]);++ if (data_get($result, 'action') === PostAction::AlreadyPublished) {+ return Response::error('Post is already published.');+ }++ /** @var Post $updated */+ $updated = data_get($result, 'post');+ $updated->load(['postPlatforms.socialAccount', 'labels']);++ return Response::structured((new PostResource($updated))->resolve());+ }++ public function schema(JsonSchema $schema): array+ {+ return [+ 'post_id' => $schema->string()->required()->description('UUID of the post to publish.'),+ 'scheduled_at' => $schema->string()->description('ISO 8601 datetime in the future. If provided, the post is queued for that time. If omitted, publishing starts immediately.'),+ ];+ }+}diff --git a/app/Mcp/Tools/Post/UpdatePostTool.php b/app/Mcp/Tools/Post/UpdatePostTool.phpnew file mode 100644index 000000000..87f576cb7--- /dev/null+++ b/app/Mcp/Tools/Post/UpdatePostTool.php@@ -0,0 +1,84 @@+<?php++declare(strict_types=1);++namespace App\Mcp\Tools\Post;++use App\Actions\Post\UpdatePost;+use App\Enums\Post\Action as PostAction;+use App\Enums\Post\Status;+use App\Enums\PostPlatform\ContentType;+use App\Http\Resources\Api\PostResource;+use App\Models\Post;+use App\Rules\ContentTypeMatchesPostPlatform;+use Illuminate\Contracts\JsonSchema\JsonSchema;+use Illuminate\Validation\Rule;+use Laravel\Mcp\Request;+use Laravel\Mcp\Response;+use Laravel\Mcp\ResponseFactory;+use Laravel\Mcp\Server\Attributes\Description;+use Laravel\Mcp\Server\Tool;++#[Description('Update a draft post — content, media, scheduled_at, labels, and which platforms are enabled. Cannot edit a post that has already been published.')]+class UpdatePostTool extends Tool+{+ public function handle(Request $request): Response|ResponseFactory+ {+ $workspace = $request->user()->currentWorkspace;++ $validated = $request->validate([+ 'post_id' => ['required', 'uuid'],+ 'content' => ['nullable', 'string', 'max:63206'],+ 'scheduled_at' => ['nullable', 'date', 'after:now'],+ 'status' => ['sometimes', 'string', Rule::in([Status::Draft->value, Status::Scheduled->value])],+ 'label_ids' => ['sometimes', 'array'],+ 'label_ids.*' => ['uuid', Rule::exists('workspace_labels', 'id')->where('workspace_id', $workspace->id)],+ 'platforms' => ['sometimes', 'array'],+ 'platforms.*.id' => ['required', 'uuid'],+ 'platforms.*.content_type' => ['sometimes', 'string', Rule::in(array_column(ContentType::cases(), 'value')), new ContentTypeMatchesPostPlatform],+ 'platforms.*.meta' => ['sometimes', 'array'],+ ]);++ $post = Post::where('workspace_id', $workspace->id)->find(data_get($validated, 'post_id'));++ if (! $post) {+ return Response::error('Post not found.');+ }++ $payload = collect($validated)->except('post_id')->all();++ $result = UpdatePost::execute($workspace, $post, $payload);++ if (data_get($result, 'action') === PostAction::AlreadyPublished) {+ return Response::error('Cannot edit a published post.');+ }++ /** @var Post $updated */+ $updated = data_get($result, 'post');+ $updated->load(['postPlatforms.socialAccount', 'labels']);++ return Response::structured((new PostResource($updated))->resolve());+ }++ public function schema(JsonSchema $schema): array+ {+ return [+ 'post_id' => $schema->string()->required()->description('UUID of the post to update.'),+ 'content' => $schema->string()->description('New caption/text body.'),+ 'scheduled_at' => $schema->string()->description('ISO 8601 datetime in the future. Required if status is "scheduled".'),+ 'status' => $schema->string()+ ->enum([Status::Draft->value, Status::Scheduled->value])+ ->description('Post status. Use "draft" to keep editing, "scheduled" to schedule the post. Use publish-post-tool for immediate publish.'),+ 'label_ids' => $schema->array()+ ->items($schema->string())+ ->description('Workspace label IDs to attach (replaces existing labels).'),+ 'platforms' => $schema->array()+ ->items($schema->object(fn ($p) => [+ 'id' => $p->string()->required()->description('UUID of the post_platform row (from get-post-tool / list-posts-tool).'),+ 'content_type' => $p->string()->description('New content_type for this platform.'),+ 'meta' => $p->object()->description('Per-platform metadata override (e.g. aspect_ratio, board_id for Pinterest).'),+ ]))+ ->description('Platforms to enable for publishing. Any platform NOT listed will be disabled. Pass an empty array to disable all.'),+ ];+ }+}diff --git a/app/Rules/ContentTypeMatchesPlatform.php b/app/Rules/ContentTypeMatchesPlatform.phpnew file mode 100644index 000000000..4e6ab8516--- /dev/null+++ b/app/Rules/ContentTypeMatchesPlatform.php@@ -0,0 +1,61 @@+<?php++declare(strict_types=1);++namespace App\Rules;++use App\Enums\PostPlatform\ContentType;+use App\Models\SocialAccount;+use Closure;+use Illuminate\Contracts\Validation\DataAwareRule;+use Illuminate\Contracts\Validation\ValidationRule;++/**+ * Cross-validates platforms[].content_type against platforms[].social_account_id+ * — ensures the chosen content_type is supported by the account's platform.+ *+ * Use on `platforms.*.content_type` rules in form requests / tools that accept+ * a `platforms[]` array with `social_account_id` siblings.+ */+class ContentTypeMatchesPlatform implements DataAwareRule, ValidationRule+{+ /** @var array<string, mixed> */+ private array $data = [];++ /**+ * @param array<string, mixed> $data+ */+ public function setData(array $data): static+ {+ $this->data = $data;++ return $this;+ }++ public function validate(string $attribute, mixed $value, Closure $fail): void+ {+ // attribute is e.g. "platforms.0.content_type" — the sibling+ // social_account_id lives at "platforms.0.social_account_id".+ $accountKey = preg_replace('/\.content_type$/', '.social_account_id', $attribute);+ $accountId = data_get($this->data, $accountKey);++ if (! $accountId) {+ return;+ }++ $contentType = ContentType::tryFrom((string) $value);+ $account = SocialAccount::find($accountId);++ if (! $contentType || ! $account) {+ return;+ }++ if (! in_array($account->platform, $contentType->compatiblePlatforms(), true)) {+ $fail(sprintf(+ 'content_type "%s" is not compatible with the %s account.',+ $contentType->value,+ $account->platform->label(),+ ));+ }+ }+}diff --git a/app/Rules/ContentTypeMatchesPostPlatform.php b/app/Rules/ContentTypeMatchesPostPlatform.phpnew file mode 100644index 000000000..b967155a3--- /dev/null+++ b/app/Rules/ContentTypeMatchesPostPlatform.php@@ -0,0 +1,57 @@+<?php++declare(strict_types=1);++namespace App\Rules;++use App\Enums\PostPlatform\ContentType;+use App\Models\PostPlatform;+use Closure;+use Illuminate\Contracts\Validation\DataAwareRule;+use Illuminate\Contracts\Validation\ValidationRule;++/**+ * Cross-validates platforms[].content_type against the platform of the+ * post_platform row identified by platforms[].id — used on UPDATE flows+ * where the social_account is implicit (already attached to the post).+ */+class ContentTypeMatchesPostPlatform implements DataAwareRule, ValidationRule+{+ /** @var array<string, mixed> */+ private array $data = [];++ /**+ * @param array<string, mixed> $data+ */+ public function setData(array $data): static+ {+ $this->data = $data;++ return $this;+ }++ public function validate(string $attribute, mixed $value, Closure $fail): void+ {+ $idKey = preg_replace('/\.content_type$/', '.id', $attribute);+ $postPlatformId = data_get($this->data, $idKey);++ if (! $postPlatformId) {+ return;+ }++ $contentType = ContentType::tryFrom((string) $value);+ $postPlatform = PostPlatform::with('socialAccount')->find($postPlatformId);++ if (! $contentType || ! $postPlatform || ! $postPlatform->socialAccount) {+ return;+ }++ if (! in_array($postPlatform->socialAccount->platform, $contentType->compatiblePlatforms(), true)) {+ $fail(sprintf(+ 'content_type "%s" is not compatible with the %s account.',+ $contentType->value,+ $postPlatform->socialAccount->platform->label(),+ ));+ }+ }+}diff --git a/app/Services/Post/MediaAttacher.php b/app/Services/Post/MediaAttacher.phpnew file mode 100644index 000000000..0ccdfd58d--- /dev/null+++ b/app/Services/Post/MediaAttacher.php@@ -0,0 +1,186 @@+<?php++declare(strict_types=1);++namespace App\Services\Post;++use App\Enums\Media\Type as MediaType;+use App\Models\Media;+use App\Models\Post;+use App\Models\Workspace;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Storage;+use Illuminate\Support\Str;++/**+ * Downloads media from public URLs and attaches them to a post. Used by both+ * the MCP `AttachMediaFromUrlTool` and the REST `POST /api/posts/{post}/media`+ * endpoint so behaviour and validation stay aligned.+ */+class MediaAttacher+{+ private const ALLOWED_IMAGE_MIMES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];++ private const ALLOWED_VIDEO_MIMES = ['video/mp4', 'video/quicktime', 'video/webm'];++ private const MAX_BYTES = 50 * 1024 * 1024; // 50 MB++ /**+ * @param array<int, string> $urls+ * @return array{attached: array<int, array<string, mixed>>, failed: array<int, string>}+ */+ public function attachFromUrls(Post $post, array $urls): array+ {+ $allowedTypes = $this->allowedMediaTypesFor($post);++ $existing = collect($post->media ?? []);+ $attached = [];+ $failed = [];++ foreach ($urls as $url) {+ $item = $this->downloadAndStore($post->workspace, $url, $allowedTypes);++ if ($item === null) {+ $failed[] = $url;++ continue;+ }++ $attached[] = $item;+ }++ if ($attached !== []) {+ $post->update([+ 'media' => $existing->concat($attached)->all(),+ ]);+ }++ return ['attached' => $attached, 'failed' => $failed];+ }++ /**+ * Intersection of allowed media types across platforms enabled on the+ * post. If no platform is enabled, accept anything supported.+ *+ * @return array<MediaType>+ */+ private function allowedMediaTypesFor(Post $post): array+ {+ $enabledPlatforms = $post->postPlatforms()+ ->where('enabled', true)+ ->with('socialAccount')+ ->get()+ ->pluck('socialAccount.platform')+ ->filter();++ if ($enabledPlatforms->isEmpty()) {+ return [MediaType::Image, MediaType::Video];+ }++ $sets = $enabledPlatforms+ ->map(fn ($platform) => array_map(fn ($type) => $type->value, $platform->allowedMediaTypes()))+ ->all();++ $intersection = array_values(array_intersect(...$sets));++ return array_map(fn ($value) => MediaType::from($value), $intersection);+ }++ /**+ * @param array<MediaType> $allowedTypes+ * @return array<string, mixed>|null+ */+ private function downloadAndStore(Workspace $workspace, string $url, array $allowedTypes): ?array+ {+ $response = Http::timeout(20)->get($url);++ if (! $response->successful()) {+ return null;+ }++ $body = $response->body();+ $bytes = strlen($body);++ if ($bytes === 0 || $bytes > self::MAX_BYTES) {+ return null;+ }++ $mime = $response->header('Content-Type');+ $mime = $mime ? trim(explode(';', $mime)[0]) : null;++ $type = $this->resolveType($mime);++ if ($type === null || ! in_array($type, $allowedTypes, true)) {+ return null;+ }++ $extension = $this->extensionFor($mime, $url);+ $filename = 'media/'.Str::uuid()->toString().'.'.$extension;+ $originalFilename = basename(parse_url($url, PHP_URL_PATH) ?? '') ?: 'download.'.$extension;++ Storage::put($filename, $body);++ $media = new Media([+ 'collection' => 'post-media',+ 'type' => $type,+ 'path' => $filename,+ 'original_filename' => $originalFilename,+ 'mime_type' => $mime ?? '',+ 'size' => $bytes,+ 'order' => 0,+ ]);+ $media->mediable_type = Workspace::class;+ $media->mediable_id = $workspace->id;+ $media->save();++ return [+ 'id' => $media->id,+ 'path' => $media->path,+ 'url' => $media->url,+ 'type' => $type->value,+ 'mime_type' => $media->mime_type,+ 'original_filename' => $media->original_filename,+ ];+ }++ private function resolveType(?string $mime): ?MediaType+ {+ if ($mime === null) {+ return null;+ }++ if (in_array($mime, self::ALLOWED_IMAGE_MIMES, true)) {+ return MediaType::Image;+ }++ if (in_array($mime, self::ALLOWED_VIDEO_MIMES, true)) {+ return MediaType::Video;+ }++ return null;+ }++ private function extensionFor(?string $mime, string $url): string+ {+ $byMime = match ($mime) {+ 'image/jpeg' => 'jpg',+ 'image/png' => 'png',+ 'image/gif' => 'gif',+ 'image/webp' => 'webp',+ 'video/mp4' => 'mp4',+ 'video/quicktime' => 'mov',+ 'video/webm' => 'webm',+ default => null,+ };++ if ($byMime) {+ return $byMime;+ }++ $byUrl = strtolower(pathinfo(parse_url($url, PHP_URL_PATH) ?? '', PATHINFO_EXTENSION));++ return in_array($byUrl, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'mov', 'webm'], true)+ ? $byUrl+ : 'bin';+ }+}diff --git a/app/Services/Post/PostMetricsFetcher.php b/app/Services/Post/PostMetricsFetcher.phpnew file mode 100644index 000000000..9f6ba8c4c--- /dev/null+++ b/app/Services/Post/PostMetricsFetcher.php@@ -0,0 +1,76 @@+<?php++declare(strict_types=1);++namespace App\Services\Post;++use App\Enums\SocialAccount\Platform;+use App\Models\Post;+use App\Models\PostPlatform;+use App\Services\Social\BlueskyAnalytics;+use App\Services\Social\FacebookAnalytics;+use App\Services\Social\InstagramAnalytics;+use App\Services\Social\LinkedInPageAnalytics;+use App\Services\Social\MastodonAnalytics;+use App\Services\Social\PinterestAnalytics;+use App\Services\Social\ThreadsAnalytics;+use App\Services\Social\XAnalytics;+use App\Services\Social\YouTubeAnalytics;+use Illuminate\Support\Collection;+use Illuminate\Support\Facades\Cache;++/**+ * Fetches per-platform post metrics. Used by the web controller, the REST+ * API controller, and the MCP `GetPostMetricsTool` so that the per-platform+ * dispatch and 5-minute cache stay in one place.+ */+class PostMetricsFetcher+{+ /**+ * @return Collection<int, array{+ * post_platform_id: string,+ * platform: string,+ * status: string,+ * platform_post_id: ?string,+ * platform_url: ?string,+ * metrics: array<int, array{label: string, value: int}>|array{unsupported: true, reason: string}+ * }>+ */+ public function forPost(Post $post): Collection+ {+ return $post->postPlatforms+ ->where('enabled', true)+ ->values()+ ->map(fn (PostPlatform $pp) => [+ 'post_platform_id' => $pp->id,+ 'platform' => $pp->platform->value,+ 'status' => $pp->status->value,+ 'platform_post_id' => $pp->platform_post_id,+ 'platform_url' => $pp->platform_url,+ 'metrics' => $this->forPlatform($pp),+ ]);+ }++ /**+ * @return array<int, array{label: string, value: int}>|array{unsupported: true, reason: string}+ */+ public function forPlatform(PostPlatform $postPlatform): array+ {+ if ($postPlatform->status->value !== 'published' || ! $postPlatform->platform_post_id) {+ return ['unsupported' => true, 'reason' => 'not_published'];+ }++ return Cache::remember("post_metrics:{$postPlatform->id}", 300, fn () => match ($postPlatform->platform) {+ Platform::X => app(XAnalytics::class)->fetchPostMetrics($postPlatform),+ Platform::Bluesky => app(BlueskyAnalytics::class)->fetchPostMetrics($postPlatform),+ Platform::Mastodon => app(MastodonAnalytics::class)->fetchPostMetrics($postPlatform),+ Platform::Instagram, Platform::InstagramFacebook => app(InstagramAnalytics::class)->fetchPostMetrics($postPlatform),+ Platform::Facebook => app(FacebookAnalytics::class)->fetchPostMetrics($postPlatform),+ Platform::Threads => app(ThreadsAnalytics::class)->fetchPostMetrics($postPlatform),+ Platform::LinkedInPage => app(LinkedInPageAnalytics::class)->fetchPostMetrics($postPlatform),+ Platform::YouTube => app(YouTubeAnalytics::class)->fetchPostMetrics($postPlatform),+ Platform::Pinterest => app(PinterestAnalytics::class)->fetchPostMetrics($postPlatform),+ default => ['unsupported' => true, 'reason' => 'platform_not_supported'],+ });+ }+}diff --git a/app/Services/Post/PostPreviewer.php b/app/Services/Post/PostPreviewer.phpnew file mode 100644index 000000000..549491db6--- /dev/null+++ b/app/Services/Post/PostPreviewer.php@@ -0,0 +1,73 @@+<?php++declare(strict_types=1);++namespace App\Services\Post;++use App\Models\Post;+use App\Models\PostPlatform;+use App\Services\Social\ContentSanitizer;+use Illuminate\Support\Collection;++/**+ * Renders per-platform previews of a post — applies the platform-specific+ * `ContentSanitizer` rules without publishing. Used by the REST API+ * preview endpoint and the MCP `PreviewPostTool` so the rendering rules+ * stay in one place.+ */+class PostPreviewer+{+ public function __construct(private readonly ContentSanitizer $sanitizer) {}++ /**+ * @return array{+ * post_id: string,+ * original_content: string,+ * original_length: int,+ * platforms: array<int, array{+ * post_platform_id: string,+ * platform: string,+ * content_type: ?string,+ * sanitized_content: string,+ * sanitized_length: int,+ * max_content_length: int,+ * truncated: bool+ * }>+ * }+ */+ public function forPost(Post $post): array+ {+ $original = (string) $post->content;++ return [+ 'post_id' => $post->id,+ 'original_content' => $original,+ 'original_length' => mb_strlen($original),+ 'platforms' => $this->platformPreviews($post, $original)->all(),+ ];+ }++ /**+ * @return Collection<int, array<string, mixed>>+ */+ private function platformPreviews(Post $post, string $original): Collection+ {+ return $post->postPlatforms+ ->where('enabled', true)+ ->values()+ ->map(function (PostPlatform $pp) use ($original) {+ $platform = $pp->socialAccount?->platform ?? $pp->platform;+ $sanitized = $original === '' ? '' : $this->sanitizer->sanitize($original, $platform);++ return [+ 'post_platform_id' => $pp->id,+ 'platform' => $platform->value,+ 'content_type' => $pp->content_type?->value,+ 'sanitized_content' => $sanitized,+ 'sanitized_length' => mb_strlen($sanitized),+ 'max_content_length' => $platform->maxContentLength(),+ 'truncated' => mb_strlen($sanitized) < mb_strlen($original),+ ];+ });+ }+}diff --git a/bootstrap/app.php b/bootstrap/app.phpindex 5629cb144..77e37ac5e 100644--- a/bootstrap/app.php+++ b/bootstrap/app.php@@ -15,7 +15,7 @@ return Application::configure(basePath: dirname(__DIR__))->withRouting(web: __DIR__.'/../routes/web.php',api: __DIR__.'/../routes/api.php',- apiPrefix: '',+ apiPrefix: 'api',commands: __DIR__.'/../routes/console.php',channels: __DIR__.'/../routes/channels.php',health: '/up',diff --git a/docs/superpowers/plans/2026-04-14-workspace-billing-plans.md b/docs/superpowers/plans/2026-04-14-workspace-billing-plans.mddeleted file mode 100644index 24fff357e..000000000--- a/docs/superpowers/plans/2026-04-14-workspace-billing-plans.md+++ /dev/null@@ -1,2223 +0,0 @@-# Workspace Billing, Plans & Brands — Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Move billing from User to Workspace, introduce tiered plans with limits, and add Brands for grouping social accounts.--**Architecture:** Workspace becomes the Cashier Billable entity with a `plan_id` FK. Plans table stores limits (social accounts, members, brands, AI images/videos, data retention). Laravel Pennant features resolve plan limits per workspace. Brands group social accounts within a workspace. Policies enforce limits using Pennant.--**Tech Stack:** Laravel 13, Cashier (Stripe), Pennant, Pest, Vue 3 + Inertia v3-------### Task 1: Create Plans Migration and Model--**Files:**-- Create: `database/migrations/2026_04_14_000001_create_plans_table.php`-- Create: `app/Models/Plan.php`-- Create: `app/Enums/Plan/Slug.php`--- [ ] **Step 1: Create migration**--Run: `php artisan make:migration create_plans_table --no-interaction`--Replace contents with:--```php-<?php--declare(strict_types=1);--use Illuminate\Database\Migrations\Migration;-use Illuminate\Database\Schema\Blueprint;-use Illuminate\Support\Facades\Schema;--return new class extends Migration-{- public function up(): void- {- Schema::create('plans', function (Blueprint $table) {- $table->uuid('id')->primary();- $table->string('slug')->unique();- $table->string('name');- $table->string('stripe_monthly_price_id')->nullable();- $table->string('stripe_yearly_price_id')->nullable();- $table->integer('monthly_price');- $table->integer('yearly_price');- $table->integer('social_account_limit');- $table->integer('member_limit');- $table->integer('brand_limit');- $table->integer('ai_images_limit');- $table->integer('ai_videos_limit');- $table->integer('data_retention_days');- $table->integer('sort')->default(0);- $table->boolean('is_archived')->default(false);- $table->timestamps();- });- }-- public function down(): void- {- Schema::dropIfExists('plans');- }-};-```--- [ ] **Step 2: Create Slug enum**--Create `app/Enums/Plan/Slug.php`:--```php-<?php--declare(strict_types=1);--namespace App\Enums\Plan;--enum Slug: string-{- case Starter = 'starter';- case Plus = 'plus';- case Pro = 'pro';- case Max = 'max';-- public function label(): string- {- return match ($this) {- self::Starter => 'Starter',- self::Plus => 'Plus',- self::Pro => 'Pro',- self::Max => 'Max',- };- }-}-```--- [ ] **Step 3: Create Plan model**--Create `app/Models/Plan.php`:--```php-<?php--declare(strict_types=1);--namespace App\Models;--use App\Enums\Plan\Slug;-use Illuminate\Database\Eloquent\Builder;-use Illuminate\Database\Eloquent\Concerns\HasUuids;-use Illuminate\Database\Eloquent\Model;-use Illuminate\Database\Eloquent\Relations\HasMany;--class Plan extends Model-{- use HasUuids;-- protected $fillable = [- 'slug',- 'name',- 'stripe_monthly_price_id',- 'stripe_yearly_price_id',- 'monthly_price',- 'yearly_price',- 'social_account_limit',- 'member_limit',- 'brand_limit',- 'ai_images_limit',- 'ai_videos_limit',- 'data_retention_days',- 'sort',- 'is_archived',- ];-- protected function casts(): array- {- return [- 'slug' => Slug::class,- 'monthly_price' => 'integer',- 'yearly_price' => 'integer',- 'social_account_limit' => 'integer',- 'member_limit' => 'integer',- 'brand_limit' => 'integer',- 'ai_images_limit' => 'integer',- 'ai_videos_limit' => 'integer',- 'data_retention_days' => 'integer',- 'sort' => 'integer',- 'is_archived' => 'boolean',- ];- }-- public function scopeActive(Builder $query): Builder- {- return $query->where('is_archived', false);- }-- public function workspaces(): HasMany- {- return $this->hasMany(Workspace::class);- }-- public function formattedMonthlyPrice(): string- {- return '$' . number_format($this->monthly_price / 100, 0);- }-- public function formattedYearlyPrice(): string- {- return '$' . number_format($this->yearly_price / 100, 0);- }-}-```--- [ ] **Step 4: Add Plan to morph map**--In `app/Providers/AppServiceProvider.php`, add to the `enforceMorphMap` array (inside `configureMorphMap` method):--```php-'plan' => Plan::class,-```--And add the import at the top:--```php-use App\Models\Plan;-```--- [ ] **Step 5: Run migration**--Run: `php artisan migrate`-Expected: `plans` table created.--- [ ] **Step 6: Commit**--```bash-git add -A && git commit -m "feat: create plans table, model, and slug enum"-```-------### Task 2: Create PlanSeeder--**Files:**-- Create: `database/seeders/PlanSeeder.php`-- Modify: `database/seeders/DatabaseSeeder.php`-- Create: `tests/Feature/PlanSeederTest.php`--- [ ] **Step 1: Write the failing test**--Run: `php artisan make:test PlanSeederTest --pest --no-interaction`--Replace contents with:--```php-<?php--declare(strict_types=1);--use App\Enums\Plan\Slug;-use App\Models\Plan;--test('plan seeder creates 4 plans', function () {- $this->seed(\Database\Seeders\PlanSeeder::class);-- expect(Plan::count())->toBe(4);-});--test('plan seeder creates plans with correct limits', function () {- $this->seed(\Database\Seeders\PlanSeeder::class);-- $starter = Plan::where('slug', Slug::Starter)->first();- expect($starter)->not->toBeNull()- ->and($starter->name)->toBe('Starter')- ->and($starter->monthly_price)->toBe(1900)- ->and($starter->yearly_price)->toBe(19000)- ->and($starter->social_account_limit)->toBe(5)- ->and($starter->member_limit)->toBe(1)- ->and($starter->brand_limit)->toBe(0)- ->and($starter->ai_images_limit)->toBe(50)- ->and($starter->ai_videos_limit)->toBe(10)- ->and($starter->data_retention_days)->toBe(30);-- $max = Plan::where('slug', Slug::Max)->first();- expect($max)->not->toBeNull()- ->and($max->monthly_price)->toBe(9900)- ->and($max->social_account_limit)->toBe(100)- ->and($max->member_limit)->toBe(20)- ->and($max->brand_limit)->toBe(50)- ->and($max->data_retention_days)->toBe(730);-});--test('plan seeder is idempotent', function () {- $this->seed(\Database\Seeders\PlanSeeder::class);- $this->seed(\Database\Seeders\PlanSeeder::class);-- expect(Plan::count())->toBe(4);-});--test('plan active scope excludes archived plans', function () {- $this->seed(\Database\Seeders\PlanSeeder::class);-- Plan::where('slug', Slug::Starter)->update(['is_archived' => true]);-- expect(Plan::active()->count())->toBe(3);-});-```--- [ ] **Step 2: Run tests to verify they fail**--Run: `php artisan test --compact tests/Feature/PlanSeederTest.php`-Expected: FAIL (PlanSeeder class not found)--- [ ] **Step 3: Create PlanSeeder**--Create `database/seeders/PlanSeeder.php`:--```php-<?php--declare(strict_types=1);--namespace Database\Seeders;--use App\Models\Plan;-use Illuminate\Database\Seeder;--class PlanSeeder extends Seeder-{- public function run(): void- {- $plans = [- [- 'slug' => 'starter',- 'name' => 'Starter',- 'stripe_monthly_price_id' => env('STRIPE_STARTER_MONTHLY'),- 'stripe_yearly_price_id' => env('STRIPE_STARTER_YEARLY'),- 'monthly_price' => 1900,- 'yearly_price' => 19000,- 'social_account_limit' => 5,- 'member_limit' => 1,- 'brand_limit' => 0,- 'ai_images_limit' => 50,- 'ai_videos_limit' => 10,- 'data_retention_days' => 30,- 'sort' => 1,- ],- [- 'slug' => 'plus',- 'name' => 'Plus',- 'stripe_monthly_price_id' => env('STRIPE_PLUS_MONTHLY'),- 'stripe_yearly_price_id' => env('STRIPE_PLUS_YEARLY'),- 'monthly_price' => 2900,- 'yearly_price' => 29000,- 'social_account_limit' => 10,- 'member_limit' => 5,- 'brand_limit' => 5,- 'ai_images_limit' => 150,- 'ai_videos_limit' => 30,- 'data_retention_days' => 60,- 'sort' => 2,- ],- [- 'slug' => 'pro',- 'name' => 'Pro',- 'stripe_monthly_price_id' => env('STRIPE_PRO_MONTHLY'),- 'stripe_yearly_price_id' => env('STRIPE_PRO_YEARLY'),- 'monthly_price' => 4900,- 'yearly_price' => 49000,- 'social_account_limit' => 30,- 'member_limit' => 15,- 'brand_limit' => 15,- 'ai_images_limit' => 500,- 'ai_videos_limit' => 100,- 'data_retention_days' => 90,- 'sort' => 3,- ],- [- 'slug' => 'max',- 'name' => 'Max',- 'stripe_monthly_price_id' => env('STRIPE_MAX_MONTHLY'),- 'stripe_yearly_price_id' => env('STRIPE_MAX_YEARLY'),- 'monthly_price' => 9900,- 'yearly_price' => 99000,- 'social_account_limit' => 100,- 'member_limit' => 20,- 'brand_limit' => 50,- 'ai_images_limit' => 2000,- 'ai_videos_limit' => 500,- 'data_retention_days' => 730,- 'sort' => 4,- ],- ];-- foreach ($plans as $plan) {- Plan::updateOrCreate(- ['slug' => $plan['slug']],- $plan,- );- }- }-}-```--- [ ] **Step 4: Register in DatabaseSeeder**--In `database/seeders/DatabaseSeeder.php`, add inside `run()`:--```php-$this->call([- PlanSeeder::class,-]);-```--- [ ] **Step 5: Run tests**--Run: `php artisan test --compact tests/Feature/PlanSeederTest.php`-Expected: 4 passed--- [ ] **Step 6: Run seeder**--Run: `php artisan db:seed --class=PlanSeeder`--- [ ] **Step 7: Commit**--```bash-git add -A && git commit -m "feat: create PlanSeeder with 4 tiered plans"-```-------### Task 3: Create Brands Migration, Model, and CRUD--**Files:**-- Create: `database/migrations/2026_04_14_000002_create_brands_table.php`-- Create: `database/migration/2026_04_14_000003_add_brand_id_to_social_accounts_table.php`-- Create: `app/Models/Brand.php`-- Create: `app/Http/Controllers/App/BrandController.php`-- Create: `app/Http/Requests/App/Brand/StoreBrandRequest.php`-- Create: `app/Http/Requests/App/Brand/UpdateBrandRequest.php`-- Create: `app/Policies/BrandPolicy.php`-- Modify: `app/Models/Workspace.php` — add `brands()` relationship-- Modify: `app/Models/SocialAccount.php` — add `brand()` relationship-- Modify: `routes/app.php` — add brand routes-- Modify: `app/Providers/AppServiceProvider.php` — add Brand to morph map-- Create: `tests/Feature/BrandControllerTest.php`--- [ ] **Step 1: Create brands migration**--Run: `php artisan make:migration create_brands_table --no-interaction`--Replace contents with:--```php-<?php--declare(strict_types=1);--use Illuminate\Database\Migrations\Migration;-use Illuminate\Database\Schema\Blueprint;-use Illuminate\Support\Facades\Schema;--return new class extends Migration-{- public function up(): void- {- Schema::create('brands', function (Blueprint $table) {- $table->uuid('id')->primary();- $table->foreignUuid('workspace_id')->constrained()->cascadeOnDelete();- $table->string('name');- $table->timestamps();- });- }-- public function down(): void- {- Schema::dropIfExists('brands');- }-};-```--- [ ] **Step 2: Create brand_id migration for social_accounts**--Run: `php artisan make:migration add_brand_id_to_social_accounts_table --no-interaction`--Replace contents with:--```php-<?php--declare(strict_types=1);--use Illuminate\Database\Migrations\Migration;-use Illuminate\Database\Schema\Blueprint;-use Illuminate\Support\Facades\Schema;--return new class extends Migration-{- public function up(): void- {- Schema::table('social_accounts', function (Blueprint $table) {- $table->foreignUuid('brand_id')->nullable()->after('workspace_id')->constrained()->nullOnDelete();- });- }-- public function down(): void- {- Schema::table('social_accounts', function (Blueprint $table) {- $table->dropConstrainedForeignId('brand_id');- });- }-};-```--- [ ] **Step 3: Create Brand model**--Create `app/Models/Brand.php`:--```php-<?php--declare(strict_types=1);--namespace App\Models;--use Illuminate\Database\Eloquent\Concerns\HasUuids;-use Illuminate\Database\Eloquent\Model;-use Illuminate\Database\Eloquent\Relations\BelongsTo;-use Illuminate\Database\Eloquent\Relations\HasMany;--class Brand extends Model-{- use HasUuids;-- protected $fillable = [- 'workspace_id',- 'name',- ];-- public function workspace(): BelongsTo- {- return $this->belongsTo(Workspace::class);- }-- public function socialAccounts(): HasMany- {- return $this->hasMany(SocialAccount::class);- }-}-```--- [ ] **Step 4: Add relationships to Workspace and SocialAccount**--In `app/Models/Workspace.php`, add method:--```php-public function brands(): HasMany-{- return $this->hasMany(Brand::class);-}-```--In `app/Models/SocialAccount.php`, add `brand_id` to fillable and add method:--```php-public function brand(): BelongsTo-{- return $this->belongsTo(Brand::class);-}-```--- [ ] **Step 5: Add Brand to morph map**--In `app/Providers/AppServiceProvider.php`, add to `enforceMorphMap`:--```php-'brand' => Brand::class,-```--And import `use App\Models\Brand;`--- [ ] **Step 6: Create BrandPolicy**--Run: `php artisan make:policy BrandPolicy --no-interaction`--Replace contents with:--```php-<?php--declare(strict_types=1);--namespace App\Policies;--use App\Enums\UserWorkspace\Role;-use App\Models\Brand;-use App\Models\User;-use App\Models\Workspace;--class BrandPolicy-{- public function viewAny(User $user, Workspace $workspace): bool- {- return $workspace->hasMember($user);- }-- public function create(User $user, Workspace $workspace): bool- {- if (! $this->canManage($user, $workspace)) {- return false;- }-- if (config('trypost.self_hosted')) {- return true;- }-- $limit = $workspace->plan?->brand_limit ?? 0;-- return $workspace->brands()->count() < $limit;- }-- public function update(User $user, Brand $brand): bool- {- return $this->canManage($user, $brand->workspace);- }-- public function delete(User $user, Brand $brand): bool- {- return $this->canManage($user, $brand->workspace);- }-- private function canManage(User $user, Workspace $workspace): bool- {- $member = $workspace->members()->where('user_id', $user->id)->first();-- if (! $member) {- return false;- }-- return in_array(Role::tryFrom($member->pivot->role), [Role::Owner, Role::Admin]);- }-}-```--- [ ] **Step 7: Create Form Requests**--Create `app/Http/Requests/App/Brand/StoreBrandRequest.php`:--```php-<?php--declare(strict_types=1);--namespace App\Http\Requests\App\Brand;--use Illuminate\Foundation\Http\FormRequest;--class StoreBrandRequest extends FormRequest-{- public function authorize(): bool- {- return true;- }-- public function rules(): array- {- return [- 'name' => ['required', 'string', 'max:255'],- ];- }-}-```--Create `app/Http/Requests/App/Brand/UpdateBrandRequest.php`:--```php-<?php--declare(strict_types=1);--namespace App\Http\Requests\App\Brand;--use Illuminate\Foundation\Http\FormRequest;--class UpdateBrandRequest extends FormRequest-{- public function authorize(): bool- {- return true;- }-- public function rules(): array- {- return [- 'name' => ['required', 'string', 'max:255'],- ];- }-}-```--- [ ] **Step 8: Create BrandController**--Create `app/Http/Controllers/App/BrandController.php`:--```php-<?php--declare(strict_types=1);--namespace App\Http\Controllers\App;--use App\Http\Requests\App\Brand\StoreBrandRequest;-use App\Http\Requests\App\Brand\UpdateBrandRequest;-use App\Models\Brand;-use Illuminate\Http\RedirectResponse;-use Illuminate\Http\Request;-use Inertia\Inertia;-use Inertia\Response;--class BrandController extends Controller-{- public function index(Request $request): Response- {- $workspace = $request->user()->currentWorkspace;-- $this->authorize('viewAny', [Brand::class, $workspace]);-- $brands = $workspace->brands()- ->withCount('socialAccounts')- ->orderBy('name')- ->get();-- return Inertia::render('brands/Index', [- 'brands' => $brands,- 'canCreate' => $request->user()->can('create', [Brand::class, $workspace]),- ]);- }-- public function store(StoreBrandRequest $request): RedirectResponse- {- $workspace = $request->user()->currentWorkspace;-- $this->authorize('create', [Brand::class, $workspace]);-- $workspace->brands()->create([- 'name' => data_get($request->validated(), 'name'),- ]);-- return back();- }-- public function update(UpdateBrandRequest $request, Brand $brand): RedirectResponse- {- $this->authorize('update', $brand);-- $brand->update([- 'name' => data_get($request->validated(), 'name'),- ]);-- return back();- }-- public function destroy(Request $request, Brand $brand): RedirectResponse- {- $this->authorize('delete', $brand);-- $brand->delete();-- return back();- }-}-```--- [ ] **Step 9: Add routes**--In `routes/app.php`, inside the subscribed middleware group (after the Labels section, around line 164), add:--```php-// Brands-Route::get('brands', [BrandController::class, 'index'])->name('app.brands.index');-Route::post('brands', [BrandController::class, 'store'])->name('app.brands.store');-Route::put('brands/{brand}', [BrandController::class, 'update'])->name('app.brands.update');-Route::delete('brands/{brand}', [BrandController::class, 'destroy'])->name('app.brands.destroy');-```--Add the import at the top: `use App\Http\Controllers\App\BrandController;`--- [ ] **Step 10: Run migrations**--Run: `php artisan migrate`--- [ ] **Step 11: Write tests**--Run: `php artisan make:test BrandControllerTest --pest --no-interaction`--Replace contents with:--```php-<?php--declare(strict_types=1);--use App\Enums\Plan\Slug;-use App\Enums\SocialAccount\Platform;-use App\Enums\SocialAccount\Status as AccountStatus;-use App\Enums\User\Setup;-use App\Enums\UserWorkspace\Role;-use App\Models\Brand;-use App\Models\Plan;-use App\Models\SocialAccount;-use App\Models\User;-use App\Models\Workspace;--beforeEach(function () {- config(['trypost.self_hosted' => true]);-- $this->user = User::factory()->create(['setup' => Setup::Completed]);- $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::Owner->value]);-});--test('can list brands', function () {- Brand::create(['workspace_id' => $this->workspace->id, 'name' => 'Brand A']);- Brand::create(['workspace_id' => $this->workspace->id, 'name' => 'Brand B']);-- $response = $this->actingAs($this->user)->get(route('app.brands.index'));-- $response->assertOk();- $brands = $response->original->getData()['page']['props']['brands'];- expect($brands)->toHaveCount(2);-});--test('can create brand', function () {- $response = $this->actingAs($this->user)- ->post(route('app.brands.store'), ['name' => 'My Brand']);-- $response->assertRedirect();- expect($this->workspace->brands()->count())->toBe(1)- ->and($this->workspace->brands()->first()->name)->toBe('My Brand');-});--test('can update brand', function () {- $brand = Brand::create(['workspace_id' => $this->workspace->id, 'name' => 'Old Name']);-- $response = $this->actingAs($this->user)- ->put(route('app.brands.update', $brand), ['name' => 'New Name']);-- $response->assertRedirect();- expect($brand->fresh()->name)->toBe('New Name');-});--test('can delete brand', function () {- $brand = Brand::create(['workspace_id' => $this->workspace->id, 'name' => 'To Delete']);-- $response = $this->actingAs($this->user)- ->delete(route('app.brands.destroy', $brand));-- $response->assertRedirect();- expect(Brand::find($brand->id))->toBeNull();-});--test('deleting brand nullifies social account brand_id', function () {- $brand = Brand::create(['workspace_id' => $this->workspace->id, 'name' => 'Test Brand']);-- $account = SocialAccount::factory()->create([- 'workspace_id' => $this->workspace->id,- 'brand_id' => $brand->id,- 'platform' => Platform::Instagram,- 'status' => AccountStatus::Connected,- ]);-- $this->actingAs($this->user)->delete(route('app.brands.destroy', $brand));-- expect($account->fresh()->brand_id)->toBeNull();-});--test('cannot create brand beyond plan limit', function () {- config(['trypost.self_hosted' => false]);-- $plan = Plan::create([- 'slug' => 'starter', 'name' => 'Starter',- 'monthly_price' => 1900, 'yearly_price' => 19000,- 'social_account_limit' => 5, 'member_limit' => 1,- 'brand_limit' => 0, 'ai_images_limit' => 50,- 'ai_videos_limit' => 10, 'data_retention_days' => 30,- 'sort' => 1,- ]);- $this->workspace->update(['plan_id' => $plan->id]);-- $response = $this->actingAs($this->user)- ->post(route('app.brands.store'), ['name' => 'Should Fail']);-- $response->assertForbidden();-});--test('cannot access brands from another workspace', function () {- $otherUser = User::factory()->create(['setup' => Setup::Completed]);- $otherWorkspace = Workspace::factory()->create(['user_id' => $otherUser->id]);- $otherUser->update(['current_workspace_id' => $otherWorkspace->id]);- $otherWorkspace->members()->attach($otherUser->id, ['role' => Role::Owner->value]);-- $brand = Brand::create(['workspace_id' => $this->workspace->id, 'name' => 'Not Yours']);-- $response = $this->actingAs($otherUser)- ->put(route('app.brands.update', $brand), ['name' => 'Hacked']);-- $response->assertForbidden();-});-```--- [ ] **Step 12: Run tests**--Run: `php artisan test --compact tests/Feature/BrandControllerTest.php`-Expected: All passed--- [ ] **Step 13: Run Pint**--Run: `vendor/bin/pint --dirty --format agent`--- [ ] **Step 14: Commit**--```bash-git add -A && git commit -m "feat: create brands with CRUD, policy, and tests"-```-------### Task 4: Move Billable from User to Workspace--**Files:**-- Create: `database/migrations/2026_04_14_000004_add_billing_columns_to_workspaces_table.php`-- Create: `database/migrations/2026_04_14_000005_migrate_subscriptions_to_workspace.php`-- Create: `database/migrations/2026_04_14_000006_remove_billing_columns_from_users_table.php`-- Modify: `app/Models/Workspace.php` — add Billable trait, plan relationship, billing methods-- Modify: `app/Models/User.php` — remove Billable trait and billing methods-- Modify: `app/Models/Traits/HasWorkspace.php` — remove workspace quantity methods-- Modify: `app/Providers/AppServiceProvider.php` — set Cashier customer model to Workspace-- Modify: `app/Http/Middleware/App/EnsureSubscribed.php` — check workspace subscription-- Modify: `app/Http/Controllers/App/BillingController.php` — use workspace for billing-- Modify: `app/Http/Controllers/App/OnboardingController.php` — use workspace for checkout-- Modify: `app/Listeners/StripeEventListener.php` — find Workspace by stripe_id-- Modify: `config/cashier.php` — remove plans section-- Modify: `database/factories/WorkspaceFactory.php` — add plan_id-- Create: `tests/Feature/WorkspaceBillingTest.php`--- [ ] **Step 1: Create migration to add billing columns to workspaces**--Run: `php artisan make:migration add_billing_columns_to_workspaces_table --no-interaction`--```php-<?php--declare(strict_types=1);--use Illuminate\Database\Migrations\Migration;-use Illuminate\Database\Schema\Blueprint;-use Illuminate\Support\Facades\Schema;--return new class extends Migration-{- public function up(): void- {- Schema::table('workspaces', function (Blueprint $table) {- $table->foreignUuid('plan_id')->nullable()->after('timezone')->constrained()->nullOnDelete();- $table->string('stripe_id')->nullable()->after('plan_id')->index();- $table->string('pm_type')->nullable()->after('stripe_id');- $table->string('pm_last_four')->nullable()->after('pm_type');- $table->timestamp('trial_ends_at')->nullable()->after('pm_last_four');- });- }-- public function down(): void- {- Schema::table('workspaces', function (Blueprint $table) {- $table->dropConstrainedForeignId('plan_id');- $table->dropIndex(['stripe_id']);- $table->dropColumn(['stripe_id', 'pm_type', 'pm_last_four', 'trial_ends_at']);- });- }-};-```--- [ ] **Step 2: Create migration to change subscriptions FK**--Run: `php artisan make:migration migrate_subscriptions_to_workspace --no-interaction`--```php-<?php--declare(strict_types=1);--use Illuminate\Database\Migrations\Migration;-use Illuminate\Database\Schema\Blueprint;-use Illuminate\Support\Facades\Schema;--return new class extends Migration-{- public function up(): void- {- Schema::table('subscriptions', function (Blueprint $table) {- $table->dropForeign(['user_id']);- $table->dropColumn('user_id');- $table->foreignUuid('workspace_id')->after('id')->constrained()->cascadeOnDelete();- });- }-- public function down(): void- {- Schema::table('subscriptions', function (Blueprint $table) {- $table->dropForeign(['workspace_id']);- $table->dropColumn('workspace_id');- $table->foreignUuid('user_id')->after('id')->constrained()->cascadeOnDelete();- });- }-};-```--- [ ] **Step 3: Create migration to remove billing columns from users**--Run: `php artisan make:migration remove_billing_columns_from_users_table --no-interaction`--```php-<?php--declare(strict_types=1);--use Illuminate\Database\Migrations\Migration;-use Illuminate\Database\Schema\Blueprint;-use Illuminate\Support\Facades\Schema;--return new class extends Migration-{- public function up(): void- {- Schema::table('users', function (Blueprint $table) {- $table->dropIndex(['stripe_id']);- $table->dropColumn(['stripe_id', 'pm_type', 'pm_last_four', 'trial_ends_at']);- });- }-- public function down(): void- {- Schema::table('users', function (Blueprint $table) {- $table->string('stripe_id')->nullable()->index();- $table->string('pm_type')->nullable();- $table->string('pm_last_four')->nullable();- $table->timestamp('trial_ends_at')->nullable();- });- }-};-```--- [ ] **Step 4: Update Workspace model**--Replace `app/Models/Workspace.php` with:--```php-<?php--declare(strict_types=1);--namespace App\Models;--use App\Models\Traits\HasMedia;-use Database\Factories\WorkspaceFactory;-use Illuminate\Database\Eloquent\Concerns\HasUuids;-use Illuminate\Database\Eloquent\Factories\HasFactory;-use Illuminate\Database\Eloquent\Model;-use Illuminate\Database\Eloquent\Relations\BelongsTo;-use Illuminate\Database\Eloquent\Relations\BelongsToMany;-use Illuminate\Database\Eloquent\Relations\HasMany;-use Laravel\Cashier\Billable;--class Workspace extends Model-{- /** @use HasFactory<WorkspaceFactory> */- use Billable, HasFactory, HasMedia, HasUuids;-- public const SUBSCRIPTION_NAME = 'default';-- protected $fillable = [- 'user_id',- 'name',- 'timezone',- 'plan_id',- ];-- protected $appends = ['has_logo', 'logo_url'];-- public function getHasLogoAttribute(): bool- {- return $this->getFirstMedia('logo') !== null;- }-- public function getLogoUrlAttribute(): ?string- {- return $this->getFirstMediaUrl('logo') ?: null;- }-- public function owner(): BelongsTo- {- return $this->belongsTo(User::class, 'user_id');- }-- public function plan(): BelongsTo- {- return $this->belongsTo(Plan::class);- }-- public function members(): BelongsToMany- {- return $this->belongsToMany(User::class)- ->withPivot('role')- ->withTimestamps();- }-- public function socialAccounts(): HasMany- {- return $this->hasMany(SocialAccount::class);- }-- public function posts(): HasMany- {- return $this->hasMany(Post::class);- }-- public function invites(): HasMany- {- return $this->hasMany(WorkspaceInvite::class);- }-- public function hashtags(): HasMany- {- return $this->hasMany(WorkspaceHashtag::class);- }-- public function labels(): HasMany- {- return $this->hasMany(WorkspaceLabel::class);- }-- public function apiTokens(): HasMany- {- return $this->hasMany(ApiToken::class);- }-- public function brands(): HasMany- {- return $this->hasMany(Brand::class);- }-- public function hasMember(User $user): bool- {- return $this->user_id === $user->id || $this->members()->where('user_id', $user->id)->exists();- }-- public function hasConnectedPlatform(string $platform): bool- {- return $this->socialAccounts()->where('platform', $platform)->exists();- }-- public function getSocialAccount(string $platform): ?SocialAccount- {- return $this->socialAccounts()->where('platform', $platform)->first();- }-- public function hasActiveSubscription(): bool- {- if (config('trypost.self_hosted')) {- return true;- }-- return $this->subscribed(self::SUBSCRIPTION_NAME);- }-- public function isOnTrial(): bool- {- $subscription = $this->subscription(self::SUBSCRIPTION_NAME);-- return $subscription?->onTrial() ?? false;- }-- public function stripeEmail(): string- {- return $this->owner?->email ?? '';- }-- public function stripeName(): string- {- return $this->name;- }-}-```--- [ ] **Step 5: Update User model — remove Billable**--In `app/Models/User.php`:--1. Remove `use Laravel\Cashier\Billable;` import (line 20)-2. Remove `Billable` from the trait use line (line 25): change to `use HasFactory, HasMedia, HasUuids, HasWorkspace, Notifiable;`-3. Remove `SUBSCRIPTION_NAME` constant (line 27)-4. Remove `hasActiveSubscription()` method (lines 120-127)-5. Remove `hasEverSubscribed()` method (lines 132-135)--- [ ] **Step 6: Simplify HasWorkspace trait**--Replace `app/Models/Traits/HasWorkspace.php` — remove all quantity/billing methods, keep only workspace navigation:--```php-<?php--declare(strict_types=1);--namespace App\Models\Traits;--use App\Enums\UserWorkspace\Role;-use App\Models\Workspace;-use Illuminate\Database\Eloquent\Relations\BelongsTo;-use Illuminate\Database\Eloquent\Relations\BelongsToMany;--trait HasWorkspace-{- public function workspaces(): BelongsToMany- {- return $this->belongsToMany(Workspace::class, 'user_workspace')- ->withPivot('role')- ->withTimestamps();- }-- public function currentWorkspace(): BelongsTo- {- return $this->belongsTo(Workspace::class, 'current_workspace_id');- }-- public function switchWorkspace(Workspace $workspace): void- {- $this->update(['current_workspace_id' => $workspace->id]);- }-- public function belongsToWorkspace(Workspace $workspace): bool- {- return $this->workspaces()->where('workspaces.id', $workspace->id)->exists();- }-- public function ownedWorkspacesCount(): int- {- return $this->workspaces()->wherePivot('role', Role::Owner->value)->count();- }-}-```--- [ ] **Step 7: Update AppServiceProvider — Cashier customer model**--In `app/Providers/AppServiceProvider.php`, add after line 77 (`Cashier::useSubscriptionItemModel`):--```php-Cashier::useCustomerModel(Workspace::class);-```--- [ ] **Step 8: Update EnsureSubscribed middleware**--Replace `app/Http/Middleware/App/EnsureSubscribed.php`:--```php-<?php--declare(strict_types=1);--namespace App\Http\Middleware\App;--use App\Models\Workspace;-use Closure;-use Illuminate\Http\Request;-use Symfony\Component\HttpFoundation\Response;--class EnsureSubscribed-{- public function handle(Request $request, Closure $next): Response- {- if (config('trypost.self_hosted')) {- return $next($request);- }-- $user = $request->user();-- if (! $user) {- return redirect()->route('login');- }-- $workspace = $user->currentWorkspace;-- if ($workspace && $workspace->hasActiveSubscription()) {- return $next($request);- }-- return redirect()->route('app.subscribe');- }-}-```--- [ ] **Step 9: Update BillingController**--Replace `app/Http/Controllers/App/BillingController.php`:--```php-<?php--declare(strict_types=1);--namespace App\Http\Controllers\App;--use App\Models\Plan;-use App\Models\Workspace;-use Illuminate\Http\RedirectResponse;-use Illuminate\Http\Request;-use Inertia\Inertia;-use Inertia\Response;-use Symfony\Component\HttpFoundation\Response as SymfonyResponse;--class BillingController extends Controller-{- public function subscribe(Request $request): Response|RedirectResponse- {- $workspace = $request->user()->currentWorkspace;-- if ($workspace && $workspace->hasActiveSubscription()) {- return redirect()->route('app.billing.index');- }-- return Inertia::render('billing/Subscribe', [- 'plans' => Plan::active()->orderBy('sort')->get(),- 'trialDays' => config('cashier.trial_days'),- ]);- }-- public function checkout(Request $request, Plan $plan): SymfonyResponse- {- $workspace = $request->user()->currentWorkspace;-- $this->authorize('manageBilling', $workspace);-- $priceId = $request->input('interval', 'monthly') === 'yearly'- ? $plan->stripe_yearly_price_id- : $plan->stripe_monthly_price_id;-- abort_if(! $priceId, 422, 'Plan price not configured');-- $workspace->createOrGetStripeCustomer([- 'email' => $workspace->stripeEmail(),- 'name' => $workspace->stripeName(),- ]);-- $subscription = $workspace->newSubscription(Workspace::SUBSCRIPTION_NAME, $priceId)- ->allowPromotionCodes()- ->trialDays(config('cashier.trial_days'));-- $checkoutSession = $subscription->checkout([- 'success_url' => route('app.billing.processing') . '?status=success',- 'cancel_url' => route('app.billing.processing') . '?status=cancelled',- ]);-- $workspace->update(['plan_id' => $plan->id]);-- return Inertia::location($checkoutSession->url);- }-- public function processing(Request $request): Response|RedirectResponse- {- $workspace = $request->user()->currentWorkspace;- $status = $request->query('status', 'processing');-- if ($workspace && $workspace->subscribed(Workspace::SUBSCRIPTION_NAME)) {- return redirect()->route('app.calendar');- }-- if (! in_array($status, ['processing', 'success', 'cancelled'])) {- $status = 'processing';- }-- return Inertia::render('billing/Processing', [- 'workspaceId' => $workspace?->id,- 'status' => $status,- ]);- }-- public function index(Request $request): Response|RedirectResponse- {- $workspace = $request->user()->currentWorkspace;-- $this->authorize('manageBilling', $workspace);-- $subscription = $workspace->subscription(Workspace::SUBSCRIPTION_NAME);-- return Inertia::render('billing/Index', [- 'hasSubscription' => $workspace->subscribed(Workspace::SUBSCRIPTION_NAME),- 'onTrial' => $subscription?->onTrial() ?? false,- 'trialEndsAt' => $subscription?->trial_ends_at?->toFormattedDateString(),- 'subscription' => $subscription?->only([- 'stripe_status',- 'ends_at',- ]),- 'plan' => $workspace->plan,- 'plans' => Plan::active()->orderBy('sort')->get(),- 'invoices' => $workspace->invoices()->map(fn ($invoice) => [- 'id' => $invoice->id,- 'date' => $invoice->date()->toFormattedDateString(),- 'total' => $invoice->total(),- 'status' => $invoice->status,- 'invoice_pdf' => $invoice->invoice_pdf,- ]),- 'defaultPaymentMethod' => $workspace->defaultPaymentMethod()?->card?->only([- 'brand',- 'last4',- 'exp_month',- 'exp_year',- ]),- ]);- }-- public function swap(Request $request, Plan $plan): RedirectResponse- {- $workspace = $request->user()->currentWorkspace;-- $this->authorize('manageBilling', $workspace);-- abort_unless($workspace->subscribed(Workspace::SUBSCRIPTION_NAME), 422, 'No active subscription');-- $priceId = $request->input('interval', 'monthly') === 'yearly'- ? $plan->stripe_yearly_price_id- : $plan->stripe_monthly_price_id;-- abort_if(! $priceId, 422, 'Plan price not configured');-- $workspace->subscription(Workspace::SUBSCRIPTION_NAME)->swap($priceId);- $workspace->update(['plan_id' => $plan->id]);-- return redirect()->route('app.billing.index');- }-- public function portal(Request $request): RedirectResponse- {- $workspace = $request->user()->currentWorkspace;-- $this->authorize('manageBilling', $workspace);-- return $workspace->redirectToBillingPortal(- route('app.billing.index')- );- }-}-```--- [ ] **Step 10: Update OnboardingController**--In `app/Http/Controllers/App/OnboardingController.php`, update `storeConnect()` method (lines 76-106). Change from `$user->newSubscription(...)` to `$workspace->newSubscription(...)`:--```php-public function storeConnect(Request $request): SymfonyResponse|RedirectResponse-{- $user = $request->user();- $workspace = $user->currentWorkspace;-- if (config('trypost.self_hosted')) {- $user->update([- 'setup' => Setup::Completed,- ]);-- session()->flash('flash.banner', __('auth.flash.welcome'));- session()->flash('flash.bannerStyle', 'success');-- return redirect()->route('app.calendar');- }-- $user->update([- 'setup' => Setup::Subscription,- ]);-- $defaultPlan = Plan::where('slug', PlanSlug::Starter)->first();-- $workspace->createOrGetStripeCustomer([- 'email' => $workspace->stripeEmail(),- 'name' => $workspace->stripeName(),- ]);-- $subscription = $workspace->newSubscription(Workspace::SUBSCRIPTION_NAME, $defaultPlan->stripe_monthly_price_id)- ->allowPromotionCodes()- ->trialDays(config('cashier.trial_days'));-- $checkoutSession = $subscription->checkout([- 'success_url' => route('app.onboarding.complete') . '?session_id={CHECKOUT_SESSION_ID}',- 'cancel_url' => route('app.onboarding.connect'),- ]);-- $workspace->update(['plan_id' => $defaultPlan->id]);-- return Inertia::location($checkoutSession->url);-}-```--Add imports at the top:-```php-use App\Enums\Plan\Slug as PlanSlug;-use App\Models\Plan;-use App\Models\Workspace;-```--- [ ] **Step 11: Update StripeEventListener**--Replace `app/Listeners/StripeEventListener.php`:--```php-<?php--declare(strict_types=1);--namespace App\Listeners;--use App\Enums\User\Setup;-use App\Events\SubscriptionCreated;-use App\Models\Workspace;-use Illuminate\Support\Facades\Log;-use Laravel\Cashier\Events\WebhookReceived;--class StripeEventListener-{- public function handle(WebhookReceived $event): void- {- try {- $type = data_get($event->payload, 'type');- $stripeCustomerId = data_get($event->payload, 'data.object.customer');-- if (! $stripeCustomerId) {- return;- }-- $workspace = Workspace::where('stripe_id', $stripeCustomerId)->first();-- if (! $workspace) {- return;- }-- match ($type) {- 'customer.subscription.created' => $this->handleSubscriptionCreated($workspace, $event->payload),- 'customer.subscription.updated' => $this->handleSubscriptionUpdated($workspace, $event->payload),- 'customer.subscription.deleted' => $this->handleSubscriptionDeleted($workspace, $event->payload),- default => null,- };- } catch (\Exception $e) {- Log::error('Stripe webhook error: ' . $e->getMessage(), [- 'exception' => $e,- 'payload' => $event->payload,- ]);- }- }-- protected function handleSubscriptionCreated(Workspace $workspace, array $payload): void- {- $owner = $workspace->owner;-- if ($owner && $owner->setup === Setup::Subscription) {- $owner->update(['setup' => Setup::Completed]);- }-- SubscriptionCreated::dispatch($workspace);- }-- protected function handleSubscriptionUpdated(Workspace $workspace, array $payload): void- {- //- }-- protected function handleSubscriptionDeleted(Workspace $workspace, array $payload): void- {- //- }-}-```--- [ ] **Step 12: Update SubscriptionCreated event**--Check and update `app/Events/SubscriptionCreated.php` to accept Workspace instead of User. (If it broadcasts to the user, it should get the owner from the workspace.)--- [ ] **Step 13: Update routes**--In `routes/app.php`, update billing routes:--Replace line 42:-```php-Route::post('billing/checkout/{plan}', [BillingController::class, 'checkout'])->name('app.billing.checkout');-```--Inside the subscribed middleware group, add after the billing portal route (line 173):-```php-Route::post('settings/billing/swap/{plan}', [BillingController::class, 'swap'])->name('app.billing.swap');-```--- [ ] **Step 14: Remove plans config from cashier.php**--In `config/cashier.php`, remove the entire `plans` section (lines 129-163) and the `trial_days` section below it. Keep `trial_days` as a standalone config:--Remove the `plans` array. Keep:-```php-'trial_days' => env('CASHIER_TRIAL_DAYS', 8),-```--- [ ] **Step 15: Update WorkspaceFactory**--In `database/factories/WorkspaceFactory.php`, add `plan_id` to definition:--```php-'plan_id' => null,-```--- [ ] **Step 16: Run migrations**--Run: `php artisan migrate`--- [ ] **Step 17: Write tests**--Run: `php artisan make:test WorkspaceBillingTest --pest --no-interaction`--Replace contents with:--```php-<?php--declare(strict_types=1);--use App\Enums\User\Setup;-use App\Enums\UserWorkspace\Role;-use App\Models\Plan;-use App\Models\User;-use App\Models\Workspace;--beforeEach(function () {- config(['trypost.self_hosted' => true]);-- $this->user = User::factory()->create(['setup' => Setup::Completed]);- $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::Owner->value]);-});--test('workspace has active subscription in self hosted mode', function () {- expect($this->workspace->hasActiveSubscription())->toBeTrue();-});--test('workspace without subscription is not active in saas mode', function () {- config(['trypost.self_hosted' => false]);-- expect($this->workspace->hasActiveSubscription())->toBeFalse();-});--test('workspace belongs to plan', function () {- $plan = Plan::create([- 'slug' => 'starter', 'name' => 'Starter',- 'monthly_price' => 1900, 'yearly_price' => 19000,- 'social_account_limit' => 5, 'member_limit' => 1,- 'brand_limit' => 0, 'ai_images_limit' => 50,- 'ai_videos_limit' => 10, 'data_retention_days' => 30,- 'sort' => 1,- ]);-- $this->workspace->update(['plan_id' => $plan->id]);-- expect($this->workspace->fresh()->plan->name)->toBe('Starter');-});--test('ensure subscribed middleware passes in self hosted mode', function () {- $response = $this->actingAs($this->user)->get(route('app.calendar'));-- $response->assertOk();-});--test('ensure subscribed middleware redirects without subscription in saas mode', function () {- config(['trypost.self_hosted' => false]);-- $response = $this->actingAs($this->user)->get(route('app.calendar'));-- $response->assertRedirect(route('app.subscribe'));-});--test('billing page is accessible by workspace owner', function () {- $response = $this->actingAs($this->user)->get(route('app.billing.index'));-- $response->assertOk();-});--test('billing page is not accessible by workspace member', function () {- $member = User::factory()->create(['setup' => Setup::Completed]);- $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);- $member->update(['current_workspace_id' => $this->workspace->id]);-- $response = $this->actingAs($member)->get(route('app.billing.index'));-- $response->assertForbidden();-});--test('subscribe page shows plans', function () {- config(['trypost.self_hosted' => false]);-- $this->seed(\Database\Seeders\PlanSeeder::class);-- $response = $this->actingAs($this->user)->get(route('app.subscribe'));-- $response->assertOk();- $plans = $response->original->getData()['page']['props']['plans'];- expect($plans)->toHaveCount(4);-});--test('stripe email returns workspace owner email', function () {- expect($this->workspace->stripeEmail())->toBe($this->user->email);-});--test('stripe name returns workspace name', function () {- expect($this->workspace->stripeName())->toBe($this->workspace->name);-});-```--- [ ] **Step 18: Run all tests**--Run: `php artisan test --compact`-Expected: All passed (fix any failures from the billing migration)--- [ ] **Step 19: Run Pint**--Run: `vendor/bin/pint --dirty --format agent`--- [ ] **Step 20: Commit**--```bash-git add -A && git commit -m "feat: move Billable from User to Workspace with plan support"-```-------### Task 5: Create Pennant Features--**Files:**-- Create: `app/Features/SocialAccountLimit.php`-- Create: `app/Features/MemberLimit.php`-- Create: `app/Features/BrandLimit.php`-- Create: `app/Features/AiImagesLimit.php`-- Create: `app/Features/AiVideosLimit.php`-- Create: `app/Features/DataRetentionDays.php`-- Modify: `app/Providers/AppServiceProvider.php` — configure Pennant-- Create: `tests/Unit/Features/SocialAccountLimitTest.php`-- Create: `tests/Unit/Features/MemberLimitTest.php`-- Create: `tests/Unit/Features/BrandLimitTest.php`-- Create: `tests/Unit/Features/AiImagesLimitTest.php`-- Create: `tests/Unit/Features/AiVideosLimitTest.php`-- Create: `tests/Unit/Features/DataRetentionDaysTest.php`--- [ ] **Step 1: Create feature classes**--Create `app/Features/SocialAccountLimit.php`:--```php-<?php--declare(strict_types=1);--namespace App\Features;--use App\Models\Workspace;--class SocialAccountLimit-{- public function resolve(Workspace $scope): int- {- return $scope->plan?->social_account_limit ?? 5;- }-}-```--Create `app/Features/MemberLimit.php`:--```php-<?php--declare(strict_types=1);--namespace App\Features;--use App\Models\Workspace;--class MemberLimit-{- public function resolve(Workspace $scope): int- {- return $scope->plan?->member_limit ?? 1;- }-}-```--Create `app/Features/BrandLimit.php`:--```php-<?php--declare(strict_types=1);--namespace App\Features;--use App\Models\Workspace;--class BrandLimit-{- public function resolve(Workspace $scope): int- {- return $scope->plan?->brand_limit ?? 0;- }-}-```--Create `app/Features/AiImagesLimit.php`:--```php-<?php--declare(strict_types=1);--namespace App\Features;--use App\Models\Workspace;--class AiImagesLimit-{- public function resolve(Workspace $scope): int- {- return $scope->plan?->ai_images_limit ?? 50;- }-}-```--Create `app/Features/AiVideosLimit.php`:--```php-<?php--declare(strict_types=1);--namespace App\Features;--use App\Models\Workspace;--class AiVideosLimit-{- public function resolve(Workspace $scope): int- {- return $scope->plan?->ai_videos_limit ?? 10;- }-}-```--Create `app/Features/DataRetentionDays.php`:--```php-<?php--declare(strict_types=1);--namespace App\Features;--use App\Models\Workspace;--class DataRetentionDays-{- public function resolve(Workspace $scope): int- {- return $scope->plan?->data_retention_days ?? 30;- }-}-```--- [ ] **Step 2: Configure Pennant in AppServiceProvider**--In `app/Providers/AppServiceProvider.php`, add at the end of `boot()` method (after the Cashier lines):--```php-Feature::resolveScopeUsing(fn () => auth()->user()?->currentWorkspace);-Feature::useMorphMap();-Feature::discover();-```--Add import at top:-```php-use Laravel\Pennant\Feature;-```--- [ ] **Step 3: Write unit tests**--Create `tests/Unit/Features/SocialAccountLimitTest.php`:--```php-<?php--declare(strict_types=1);--use App\Features\SocialAccountLimit;-use App\Models\Plan;-use App\Models\Workspace;--test('returns plan social account limit', function () {- $plan = new Plan(['social_account_limit' => 30]);- $workspace = new Workspace;- $workspace->setRelation('plan', $plan);-- expect((new SocialAccountLimit)->resolve($workspace))->toBe(30);-});--test('falls back to 5 when no plan', function () {- $workspace = new Workspace;- $workspace->setRelation('plan', null);-- expect((new SocialAccountLimit)->resolve($workspace))->toBe(5);-});-```--Create `tests/Unit/Features/MemberLimitTest.php`:--```php-<?php--declare(strict_types=1);--use App\Features\MemberLimit;-use App\Models\Plan;-use App\Models\Workspace;--test('returns plan member limit', function () {- $plan = new Plan(['member_limit' => 15]);- $workspace = new Workspace;- $workspace->setRelation('plan', $plan);-- expect((new MemberLimit)->resolve($workspace))->toBe(15);-});--test('falls back to 1 when no plan', function () {- $workspace = new Workspace;- $workspace->setRelation('plan', null);-- expect((new MemberLimit)->resolve($workspace))->toBe(1);-});-```--Create `tests/Unit/Features/BrandLimitTest.php`:--```php-<?php--declare(strict_types=1);--use App\Features\BrandLimit;-use App\Models\Plan;-use App\Models\Workspace;--test('returns plan brand limit', function () {- $plan = new Plan(['brand_limit' => 15]);- $workspace = new Workspace;- $workspace->setRelation('plan', $plan);-- expect((new BrandLimit)->resolve($workspace))->toBe(15);-});--test('falls back to 0 when no plan', function () {- $workspace = new Workspace;- $workspace->setRelation('plan', null);-- expect((new BrandLimit)->resolve($workspace))->toBe(0);-});-```--Create `tests/Unit/Features/AiImagesLimitTest.php`:--```php-<?php--declare(strict_types=1);--use App\Features\AiImagesLimit;-use App\Models\Plan;-use App\Models\Workspace;--test('returns plan ai images limit', function () {- $plan = new Plan(['ai_images_limit' => 500]);- $workspace = new Workspace;- $workspace->setRelation('plan', $plan);-- expect((new AiImagesLimit)->resolve($workspace))->toBe(500);-});--test('falls back to 50 when no plan', function () {- $workspace = new Workspace;- $workspace->setRelation('plan', null);-- expect((new AiImagesLimit)->resolve($workspace))->toBe(50);-});-```--Create `tests/Unit/Features/AiVideosLimitTest.php`:--```php-<?php--declare(strict_types=1);--use App\Features\AiVideosLimit;-use App\Models\Plan;-use App\Models\Workspace;--test('returns plan ai videos limit', function () {- $plan = new Plan(['ai_videos_limit' => 100]);- $workspace = new Workspace;- $workspace->setRelation('plan', $plan);-- expect((new AiVideosLimit)->resolve($workspace))->toBe(100);-});--test('falls back to 10 when no plan', function () {- $workspace = new Workspace;- $workspace->setRelation('plan', null);-- expect((new AiVideosLimit)->resolve($workspace))->toBe(10);-});-```--Create `tests/Unit/Features/DataRetentionDaysTest.php`:--```php-<?php--declare(strict_types=1);--use App\Features\DataRetentionDays;-use App\Models\Plan;-use App\Models\Workspace;--test('returns plan data retention days', function () {- $plan = new Plan(['data_retention_days' => 730]);- $workspace = new Workspace;- $workspace->setRelation('plan', $plan);-- expect((new DataRetentionDays)->resolve($workspace))->toBe(730);-});--test('falls back to 30 when no plan', function () {- $workspace = new Workspace;- $workspace->setRelation('plan', null);-- expect((new DataRetentionDays)->resolve($workspace))->toBe(30);-});-```--- [ ] **Step 4: Run unit tests**--Run: `php artisan test --compact tests/Unit/Features/`-Expected: 12 passed--- [ ] **Step 5: Run Pint**--Run: `vendor/bin/pint --dirty --format agent`--- [ ] **Step 6: Commit**--```bash-git add -A && git commit -m "feat: add Pennant features for plan limit resolution"-```-------### Task 6: Update BrandPolicy to Use Pennant + Limit Enforcement on Social Accounts and Members--**Files:**-- Modify: `app/Policies/BrandPolicy.php` — use Pennant-- Modify: `app/Policies/WorkspacePolicy.php` — add member limit check-- Create: `tests/Feature/LimitEnforcementTest.php`--- [ ] **Step 1: Update BrandPolicy to use Pennant**--Replace the `create` method in `app/Policies/BrandPolicy.php`:--```php-use App\Features\BrandLimit;-use Laravel\Pennant\Feature;--public function create(User $user, Workspace $workspace): bool-{- if (! $this->canManage($user, $workspace)) {- return false;- }-- if (config('trypost.self_hosted')) {- return true;- }-- $limit = Feature::for($workspace)->value(BrandLimit::class);-- return $workspace->brands()->count() < $limit;-}-```--- [ ] **Step 2: Add member limit to WorkspacePolicy**--In `app/Policies/WorkspacePolicy.php`, add method:--```php-use App\Features\MemberLimit;-use Laravel\Pennant\Feature;--public function inviteMember(User $user, Workspace $workspace): bool-{- if (! $this->hasRole($user, $workspace, [Role::Owner, Role::Admin])) {- return false;- }-- if (config('trypost.self_hosted')) {- return true;- }-- $limit = Feature::for($workspace)->value(MemberLimit::class);-- return $workspace->members()->count() < $limit;-}-```--- [ ] **Step 3: Write limit enforcement tests**--Run: `php artisan make:test LimitEnforcementTest --pest --no-interaction`--Replace contents with:--```php-<?php--declare(strict_types=1);--use App\Enums\Plan\Slug;-use App\Enums\SocialAccount\Platform;-use App\Enums\SocialAccount\Status as AccountStatus;-use App\Enums\User\Setup;-use App\Enums\UserWorkspace\Role;-use App\Models\Brand;-use App\Models\Plan;-use App\Models\SocialAccount;-use App\Models\User;-use App\Models\Workspace;--beforeEach(function () {- config(['trypost.self_hosted' => false]);-- $this->plan = Plan::create([- 'slug' => 'plus', 'name' => 'Plus',- 'monthly_price' => 2900, 'yearly_price' => 29000,- 'social_account_limit' => 10, 'member_limit' => 5,- 'brand_limit' => 5, 'ai_images_limit' => 150,- 'ai_videos_limit' => 30, 'data_retention_days' => 60,- 'sort' => 2,- ]);-- $this->user = User::factory()->create(['setup' => Setup::Completed]);- $this->workspace = Workspace::factory()->create([- 'user_id' => $this->user->id,- 'plan_id' => $this->plan->id,- ]);- $this->user->update(['current_workspace_id' => $this->workspace->id]);- $this->workspace->members()->attach($this->user->id, ['role' => Role::Owner->value]);-});--test('can create brand within limit', function () {- expect($this->user->can('create', [Brand::class, $this->workspace]))->toBeTrue();-});--test('cannot create brand beyond limit', function () {- for ($i = 0; $i < 5; $i++) {- Brand::create(['workspace_id' => $this->workspace->id, 'name' => "Brand {$i}"]);- }-- expect($this->user->can('create', [Brand::class, $this->workspace]))->toBeFalse();-});--test('can invite member within limit', function () {- expect($this->user->can('inviteMember', $this->workspace))->toBeTrue();-});--test('cannot invite member beyond limit', function () {- for ($i = 0; $i < 4; $i++) {- $member = User::factory()->create(['setup' => Setup::Completed]);- $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);- }-- // Owner (1) + 4 members = 5 = limit- expect($this->user->can('inviteMember', $this->workspace))->toBeFalse();-});--test('self hosted mode bypasses brand limit', function () {- config(['trypost.self_hosted' => true]);-- for ($i = 0; $i < 10; $i++) {- Brand::create(['workspace_id' => $this->workspace->id, 'name' => "Brand {$i}"]);- }-- expect($this->user->can('create', [Brand::class, $this->workspace]))->toBeTrue();-});--test('self hosted mode bypasses member limit', function () {- config(['trypost.self_hosted' => true]);-- for ($i = 0; $i < 10; $i++) {- $member = User::factory()->create(['setup' => Setup::Completed]);- $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);- }-- expect($this->user->can('inviteMember', $this->workspace))->toBeTrue();-});-```--- [ ] **Step 4: Run tests**--Run: `php artisan test --compact tests/Feature/LimitEnforcementTest.php`-Expected: All passed--- [ ] **Step 5: Run Pint**--Run: `vendor/bin/pint --dirty --format agent`--- [ ] **Step 6: Commit**--```bash-git add -A && git commit -m "feat: enforce plan limits via Pennant in policies"-```-------### Task 7: Run Full Test Suite and Fix Breakages--- [ ] **Step 1: Run full test suite**--Run: `php artisan test --compact`--- [ ] **Step 2: Fix any failures caused by the billing migration**--Common things to check:-- Tests that reference `User::SUBSCRIPTION_NAME` — change to `Workspace::SUBSCRIPTION_NAME`-- Tests that call `$user->subscribed()` — change to `$workspace->subscribed()`-- Tests that reference `$user->subscription()` — change to `$workspace->subscription()`-- Tests that use `$user->stripe_id` — the field no longer exists on User-- Middleware tests that check EnsureSubscribed — now checks workspace-- WorkspaceController tests that call `canCreateWorkspace` — method removed--- [ ] **Step 3: Run Pint**--Run: `vendor/bin/pint --dirty --format agent`--- [ ] **Step 4: Run full test suite again**--Run: `php artisan test --compact`-Expected: All passed--- [ ] **Step 5: Commit**--```bash-git add -A && git commit -m "fix: update existing tests for workspace billing migration"-```diff --git a/docs/superpowers/specs/2026-04-14-workspace-billing-plans-design.md b/docs/superpowers/specs/2026-04-14-workspace-billing-plans-design.mddeleted file mode 100644index 7eb33c3cf..000000000--- a/docs/superpowers/specs/2026-04-14-workspace-billing-plans-design.md+++ /dev/null@@ -1,322 +0,0 @@-# Account Billing, Plans & Workspaces--## Overview--Introduce an Account entity as the central billing and organizational unit. Account holds the Stripe subscription, plan, and limits. Workspaces group social accounts within an Account. Users belong to one Account with an account-level role (admin/user) and can be assigned to specific workspaces with workspace-level roles (member/viewer). The Account owner has full access to everything.--## Data Model--```-Account (Billable, plan_id, owner_id)- ├── Users (account_id, account_role: admin/user)- └── Workspaces- ├── Members (user_id, workspace_role: member/viewer)- ├── Invites- └── Social Accounts-```--## Roles--### Account-level--Owner is determined by `accounts.owner_id`. No account-level role column on users. Only the owner can manage billing, create workspaces, and delete the account. The owner has full access to all workspaces automatically.--### Workspace-level roles (`user_workspace.role`)--| Role | Permissions |-|---|---|-| Admin | Everything in the workspace: manage members, connect accounts, settings |-| Member | Create posts, schedule |-| Viewer | View only (future: comments) |--The Account owner has full access to all workspaces without needing a workspace pivot record.--## Plans--| Limit | Starter ($19/$190) | Plus ($29/$290) | Pro ($49/$490) | Max ($99/$990) |-|---|---|---|---|---|-| Social accounts | 5 | 10 | 30 | 100 |-| Members | 1 | 5 | 15 | 20 |-| Workspaces | 1 | 5 | 15 | 50 |-| AI Images/month | 50 | 150 | 500 | 2000 |-| AI Videos/month | 10 | 30 | 100 | 500 |-| Data retention (days) | 30 | 60 | 90 | 730 |-| Monthly price | $19 | $29 | $49 | $99 |-| Yearly price | $190 | $290 | $490 | $990 |--All limits are at the **Account level** (totals across all workspaces).--Starter plan: 1 member (owner only), 1 workspace (default, UI hides workspace management).--Trial period: 8 days (configurable via `CASHIER_TRIAL_DAYS`).-------## Database Changes--### New table: `accounts`--| Column | Type | Notes |-|---|---|---|-| id | uuid, PK | |-| owner_id | FK -> users, nullable initially | Set after user creation (chicken-egg) |-| plan_id | FK -> plans, nullable | Current plan |-| name | string | Account/company name |-| stripe_id | string, nullable, indexed | Stripe customer ID |-| pm_type | string, nullable | Payment method type |-| pm_last_four | string, nullable | Last 4 digits |-| trial_ends_at | timestamp, nullable | |-| timestamps | | |--Note: `owner_id` is nullable because during signup the user and account are created in the same transaction. Set `owner_id` after user creation.--### New table: `plans` (unchanged from current)--Already implemented. slug, name, stripe price IDs, all limits, sort, is_archived.--### Modify table: `users`--Add columns:-- `account_id` (FK -> accounts, nullable, constrained)-- `account_role` (string, default 'user') — enum: admin, user--Remove columns:-- `stripe_id`, `pm_type`, `pm_last_four`, `trial_ends_at` (already removed)--### Modify table: `workspaces`--Remove columns:-- `plan_id` (moves to Account)-- `stripe_id`, `pm_type`, `pm_last_four`, `trial_ends_at` (moves to Account)--Add columns:-- `account_id` (FK -> accounts, constrained, cascade delete)--Keep: `user_id` (original creator, not necessarily the owner), `name`, `timezone`--### Modify table: `user_workspace`--Change `role` values from `owner/admin/member` to `member/viewer`. Owner is determined by Account, not workspace pivot.--### Modify table: `subscriptions`--Change FK from `workspace_id` to `account_id`.--### Modify table: `invites` (rename from `workspace_invites`)--| Column | Type | Notes |-|---|---|---|-| id | uuid, PK | |-| account_id | FK -> accounts, cascade delete | |-| email | string | Invited email |-| workspaces | json | Array of {workspace_id, role} |-| invited_by | FK -> users, nullable | Who sent the invite |-| accepted_at | timestamp, nullable | |-| timestamps | | |--### Remove table: `brands`--Brands concept is replaced by Workspaces. Remove brands table, remove `brand_id` from social_accounts.-------## Models--### Account (new)--- UUID primary key-- `Billable` trait from Cashier-- Constant: `SUBSCRIPTION_NAME = 'default'`-- Fillable: name, owner_id, plan_id-- Relationships: `owner()` belongsTo User, `plan()` belongsTo Plan, `users()` hasMany User, `workspaces()` hasMany Workspace, `invites()` hasMany Invite-- Methods: `hasActiveSubscription()`, `isOnTrial()`, `stripeEmail()` (owner email), `stripeName()` (account name)--### User (modified)--- Remove `Billable` trait (already removed)-- Add `account_id` and `account_role` to fillable-- Add cast: `account_role` to `AccountRole` enum-- Add relationship: `account()` belongsTo Account-- Remove: `HasWorkspace` trait methods related to billing-- Keep: `currentWorkspace()`, `switchWorkspace()`, workspace navigation methods-- Add: `isAccountOwner()` — `$this->id === $this->account?->owner_id`-- Add: `isAccountAdmin()` — `$this->account_role === AccountRole::Admin || $this->isAccountOwner()`--### Workspace (modified)--- Remove `Billable` trait-- Remove billing fields from fillable (stripe_id, pm_type, pm_last_four, trial_ends_at, plan_id)-- Add `account_id` to fillable-- Add relationship: `account()` belongsTo Account-- Keep: members(), socialAccounts(), posts(), invites is now on Account--### Invite (modified from WorkspaceInvite)--- Rename model from WorkspaceInvite to Invite-- Add: `account_id`, `workspaces` (json), `invited_by`-- Add cast: `workspaces` to array-- Relationship: `account()` belongsTo Account, `invitedBy()` belongsTo User-------## Enums--### AccountRole (new)--```php-enum AccountRole: string-{- case Admin = 'admin';- case User = 'user';-}-```--### WorkspaceRole (modify existing)--```php-enum WorkspaceRole: string-{- case Member = 'member';- case Viewer = 'viewer';-}-```--Remove `Owner` and `Admin` cases.-------## Cashier Configuration--### AppServiceProvider--```php-Cashier::useCustomerModel(Account::class);-```-------## Middleware: EnsureSubscribed--1. If `config('trypost.self_hosted')` → pass-2. Get `$user->account`-3. If account has active subscription or trial → pass-4. Redirect to `/subscribe`-------## Pennant Features--Scope changes from Workspace to Account:--```php-Feature::resolveScopeUsing(fn () => auth()->user()?->account);-```--All 6 feature classes receive `Account $scope` instead of `Workspace $scope`:-- `SocialAccountLimit` — `$scope->plan?->social_account_limit ?? 5`-- `MemberLimit` — `$scope->plan?->member_limit ?? 1`-- `WorkspaceLimit` — `$scope->plan?->workspace_limit ?? 1` (replaces BrandLimit)-- `AiImagesLimit` — `$scope->plan?->ai_images_limit ?? 50`-- `AiVideosLimit` — `$scope->plan?->ai_videos_limit ?? 10`-- `DataRetentionDays` — `$scope->plan?->data_retention_days ?? 30`-------## Limit Enforcement--All limits checked at Account level:--- **Social accounts**: total across all workspaces in the account-- **Members**: unique users in the account (excluding owner) — `$account->users()->where('id', '!=', $account->owner_id)->count()`-- **Workspaces**: `$account->workspaces()->count()`-- **AI images/videos**: monthly usage tracked per account-- **Data retention**: applied per account-------## Controllers--### BillingController--All operations on `$user->account`:-- `$account->subscribed()`, `$account->subscription()`, `$account->invoices()`--### OnboardingController--Signup flow:-1. Create Account-2. Create User with `account_id` and `account_role = admin` (owner)-3. Set `account.owner_id`-4. Create default Workspace with `account_id`-5. Stripe checkout on Account--### StripeEventListener--Find `Account::where('stripe_id', $stripeCustomerId)` instead of Workspace.--### InviteController (replaces WorkspaceInviteController)--- `store()`: create invite on Account with workspaces + roles array-- On accept: set user's `account_id`, create workspace pivot records-------## Signup Flow--1. User registers (name, email, password)-2. `CreateUser` action:- - Creates Account (name = user's name)- - Creates User with `account_id`, `account_role = admin`- - Sets `account.owner_id = user.id`- - Creates default Workspace within Account- - Sets `user.current_workspace_id`-3. Onboarding: role → connect accounts → Stripe checkout (on Account)--## Invite Flow--1. Owner/Admin creates invite: email + [{workspace_id, role}]-2. Email sent with invite link-3. Person clicks link:- - If no TryPost account: register with `account_id` pre-set, `account_role = user`- - If has TryPost account with same Account: add workspace assignments- - If has TryPost account with different Account: error — must use different email-4. Workspace pivot records created per the invite's workspaces array-------## UI Behavior by Plan--### Starter (1 workspace, 1 member)-- Workspace switcher hidden-- "Create workspace" hidden-- Invite members hidden-- Simple single-workspace experience--### Plus and above-- Workspace switcher visible-- Create workspace button visible-- Invite members visible-- Full multi-workspace experience-------## Plans table: workspace_limit replaces brand_limit--| Column change | Old | New |-|---|---|---|-| brand_limit | 0, 5, 15, 50 | renamed to workspace_limit: 1, 5, 15, 50 |-------## Self-hosted mode--All limits bypassed. Account still exists but no billing. Unlimited workspaces, members, social accounts.-------## What does NOT change--- Social account OAuth flows (connect/disconnect)-- Post creation and publishing-- Analytics-- Multi-account social connections (multiple accounts per platform)diff --git a/docs/superpowers/specs/2026-04-23-instagram-facebook-variants-design.md b/docs/superpowers/specs/2026-04-23-instagram-facebook-variants-design.mddeleted file mode 100644index 673d60f5e..000000000--- a/docs/superpowers/specs/2026-04-23-instagram-facebook-variants-design.md+++ /dev/null@@ -1,288 +0,0 @@-# Instagram and Facebook Content Variants in Post Editor--**Date:** 2026-04-23-**Branch:** feature/workspace-billing-plans--## Problem--The post editor has per-platform settings for TikTok (`TikTokSettings.vue`) but no equivalent UI for choosing content variants on Instagram (Feed / Reel / Story) and Facebook (Post / Reel / Story). The backend already supports these variants — `ContentType` enum maps to publisher branches in `InstagramPublisher` and `FacebookPublisher`, `UpdatePost` persists `content_type`, and `UpdatePostRequest` validates it — but `SyncPostPlatforms` always defaults to `InstagramFeed` / `FacebookPost` and the frontend has no way for users to change it.--Users currently can only publish Feed posts on Instagram and standard Posts on Facebook, even when they want Reels or Stories.--## Goals--- Let users choose content variant per connected Instagram and Facebook account on the post edit page.-- Match the visual pattern established by `TikTokSettings.vue` (collapsible card with platform context).-- Support multiple connected accounts of the same platform (each card is independent — user can pick different variants for different accounts in the same post).-- Block submission with a clear warning when the chosen variant is incompatible with the attached media (mirrors existing `tiktokComplianceValid` pattern).-- Centralize media rules in a single source of truth, re-used for validation and for per-card warnings.--## Non-Goals--- Backend changes (publishers already handle all variants).-- Variant support for platforms beyond Instagram and Facebook (LinkedIn, Pinterest, etc. come later).-- Restricting the media upload picker based on variant — the variant-driven accept/max logic stays on the validation side, not on the file input (user can still drop any media; we just warn + block publish).--## Design--### New Files--- `resources/js/components/posts/editor/InstagramSettings.vue` — rendered for `Platform::Instagram` and `Platform::InstagramFacebook` (same variant set).-- `resources/js/components/posts/editor/FacebookSettings.vue` — rendered for `Platform::Facebook`.-- `resources/js/composables/useMediaRules.ts` — restored from `main`, single source of truth for per-`content_type` media constraints.--### Modified Files--- `resources/js/pages/posts/Edit.vue` — add `platformContentTypes` state, compliance computeds, update `getSubmitData()` and autosave watcher, pipe new state into `ScheduleTab` and `PreviewTab`.-- `resources/js/components/posts/editor/ScheduleTab.vue` — accept `platformContentTypes` prop, emit `update:platform-content-type`, render `InstagramSettings` / `FacebookSettings` blocks per selected account.-- `resources/js/components/posts/editor/PreviewTab.vue` — read variant from `platformContentTypes[previewPlatform.id]` so preview updates live when user toggles variants.-- `lang/en/posts.php`, `lang/es/posts.php`, `lang/pt-BR/posts.php` — add translation keys for settings card, variant labels, warnings.--### Component Structure (`InstagramSettings.vue`, `FacebookSettings.vue`)--Mirror `TikTokSettings.vue`'s outer shell:--- Collapsible root card with border.-- Header button: platform icon + `"Instagram settings"` / `"Facebook settings"` + chevron up/down.-- Closed by default; clicking the header toggles `open` ref.-- Body (when open):- - "Posting to" row: `Avatar` component + display name + `@username` of the connected account (critical when the user has multiple accounts of the same platform — makes clear which card configures which account).- - Variant picker: three horizontal pill buttons, one per variant. Active pill gets `bg-primary/10 border-primary`; inactive gets muted styling. Clicking emits `update:content-type` with the new value.- - Warning block (conditionally rendered): when `useMediaRules(contentType)` indicates the current `media` array violates the rules, render an `IconAlertTriangle` + short i18n message explaining the specific violation ("Reel requires a video", "Story accepts only 1 media", etc.).--Props:--```ts-interface Props {- socialAccount: SocialAccount | null;- contentType: string; // e.g. 'instagram_reel'- media: MediaItem[]; // to evaluate compliance warnings- disabled?: boolean;-}-```--Emits:--```ts-'update:content-type': [value: string]-```--### Variant Catalog--| Platform | Variants | Default |-|----------|----------|---------|-| Instagram (standalone + via Facebook) | `instagram_feed`, `instagram_reel`, `instagram_story` | `instagram_feed` |-| Facebook | `facebook_post`, `facebook_reel`, `facebook_story` | `facebook_post` |--Labels and descriptions are already defined in `App\Enums\PostPlatform\ContentType` (`label()` and `description()` methods). Frontend uses i18n keys for display so strings stay in translation files, not in enum PHP strings.--### State Management in `Edit.vue`--Add a `platformContentTypes` ref that mirrors the existing `platformMeta` pattern exactly:--```ts-const platformContentTypes = ref<Record<string, string>>(- Object.fromEntries(- post.value.post_platforms.map((pp) => [pp.id, pp.content_type ?? '']),- ),-);--const updatePlatformContentType = (platformId: string, contentType: string) => {- platformContentTypes.value = {- ...platformContentTypes.value,- [platformId]: contentType,- };-};-```--This produces a dictionary keyed by `post_platform.id`, so two Instagram accounts get two independent entries.--Update `getSubmitData()` to read `content_type` from state instead of the prop:--```ts-const platforms = post.value.post_platforms- .filter((pp) => selectedPlatformIds.value.includes(pp.id))- .map((pp) => ({- id: pp.id,- content_type: platformContentTypes.value[pp.id] ?? pp.content_type,- meta: platformMeta.value[pp.id] ?? pp.meta ?? {},- }));-```--Add `platformContentTypes` to the autosave `watch`:--```ts-watch(- [content, media, selectedPlatformIds, scheduledDateTime, selectedLabelIds, platformMeta, platformContentTypes],- triggerAutosave,- { deep: true },-);-```--### Media Rules Composable--Restore `resources/js/composables/useMediaRules.ts` from `main` (the file already covered Instagram, Facebook, and every other platform correctly). The restored file keeps its original `useMediaRules(contentTypeRef)` reactive form (used inside settings components) and adds a small non-reactive helper for use in `Edit.vue`'s validation computeds:--- `useMediaRules(contentTypeRef: Ref<string>)` — reactive, already present on `main`, for use in `<script setup>` of settings components.-- `getMediaRules(contentType: string): MediaRules` — new plain helper that returns the same rules dictionary entry imperatively, so compliance computeds in `Edit.vue` don't need to wrap in refs.--The rules object keys off `content_type` values (e.g. `instagram_reel`) and returns `{ maxFiles, minFiles?, acceptImages, acceptVideos, requiresMedia }`.--### Compliance Validation--Add a single media-vs-rules helper in `Edit.vue`:--```ts-const isMediaValidForContentType = (contentType: string, mediaItems: MediaItem[]): boolean => {- const rules = getMediaRules(contentType);- const videos = mediaItems.filter((m) => m.type === 'video' || m.mime_type?.startsWith('video/'));- const images = mediaItems.filter((m) => m.type === 'image' || m.mime_type?.startsWith('image/'));- const total = mediaItems.length;-- if (rules.requiresMedia && total === 0) return false;- if (total > rules.maxFiles) return false;- if (rules.minFiles && total < rules.minFiles) return false;- if (!rules.acceptVideos && videos.length > 0) return false;- if (!rules.acceptImages && images.length > 0) return false;- return true;-};-```--Two new computeds parallel to the existing `tiktokComplianceValid`:--```ts-const instagramComplianceValid = computed(() =>- post.value.post_platforms- .filter((pp) => ['instagram', 'instagram-facebook'].includes(pp.platform)- && selectedPlatformIds.value.includes(pp.id))- .every((pp) => {- const ct = platformContentTypes.value[pp.id];- return Boolean(ct) && isMediaValidForContentType(ct, media.value);- }),-);--const facebookComplianceValid = computed(() =>- post.value.post_platforms- .filter((pp) => pp.platform === 'facebook'- && selectedPlatformIds.value.includes(pp.id))- .every((pp) => {- const ct = platformContentTypes.value[pp.id];- return Boolean(ct) && isMediaValidForContentType(ct, media.value);- }),-);-```--Submit buttons (`PickTimePopover` trigger and the primary "Post now" / "Schedule" button) gain these computeds in their `:disabled` expression, and `:title` falls back to the first failing platform's i18n message when compliance is false.--### `ScheduleTab.vue` Integration--Add prop and emit:--```ts-defineProps<{- // ...existing props- platformContentTypes: Record<string, string>;-}>();--defineEmits<{- // ...existing emits- 'update:platform-content-type': [platformId: string, contentType: string];-}>();-```--Compute filtered lists (complement to existing `selectedTikTokPlatforms`):--```ts-const selectedInstagramPlatforms = computed(() =>- props.postPlatforms.filter(- (pp) => ['instagram', 'instagram-facebook'].includes(pp.platform)- && props.selectedPlatformIds.includes(pp.id),- ),-);--const selectedFacebookPlatforms = computed(() =>- props.postPlatforms.filter(- (pp) => pp.platform === 'facebook' && props.selectedPlatformIds.includes(pp.id),- ),-);-```--Render blocks in the existing "Platform-specific settings" region, after the TikTok block:--```vue-<div v-if="selectedInstagramPlatforms.length > 0" class="space-y-4">- <InstagramSettings- v-for="pp in selectedInstagramPlatforms"- :key="pp.id"- :social-account="pp.social_account"- :content-type="platformContentTypes[pp.id] ?? ''"- :media="media ?? []"- :disabled="isReadOnly"- @update:content-type="emit('update:platform-content-type', pp.id, $event)"- />-</div>--<div v-if="selectedFacebookPlatforms.length > 0" class="space-y-4">- <FacebookSettings- v-for="pp in selectedFacebookPlatforms"- :key="pp.id"- :social-account="pp.social_account"- :content-type="platformContentTypes[pp.id] ?? ''"- :media="media ?? []"- :disabled="isReadOnly"- @update:content-type="emit('update:platform-content-type', pp.id, $event)"- />-</div>-```--### Preview Reactivity--`PreviewTab.vue` currently receives `contentType` as a prop read from `previewPlatform.content_type` (i.e., the server-side value from the last save). Update `Edit.vue`'s template to read from local state so the preview updates live:--```vue-<PreviewTab- v-if="previewPlatform"- :platform="previewPlatform.platform"- :content="content"- :media="media"- :social-account="previewPlatform.social_account"- :content-type="platformContentTypes[previewPlatform.id] ?? previewPlatform.content_type"-/>-```--### Translation Keys--Add under `posts.form.instagram.*` and `posts.form.facebook.*` (for all three locales):--- `settings` — "Instagram settings" / "Facebook settings"-- `posting_to` — "Posting to"-- `variant.feed`, `variant.reel`, `variant.story` (IG) — pill labels-- `variant.post`, `variant.reel`, `variant.story` (FB) — pill labels-- `variant.*_description` — sub-text for pills (optional, for a11y title)-- `warning.requires_media`, `warning.max_files_exceeded`, `warning.min_files_required`, `warning.no_video_allowed`, `warning.no_image_allowed` — specific violation messages-- `compliance_incomplete` — button tooltip when submit is blocked--## Data Flow--1. Backend seeds `post_platforms.content_type` with `ContentType::defaultFor($platform)` in `SyncPostPlatforms`.-2. `Edit.vue` reads the incoming `post.post_platforms[].content_type` and initializes `platformContentTypes`.-3. User opens Instagram / Facebook card, picks a variant pill → `InstagramSettings`/`FacebookSettings` emits `update:content-type` → `ScheduleTab` re-emits with `pp.id` → `Edit.vue` updates `platformContentTypes` state.-4. Autosave watcher fires → `getSubmitData()` builds platforms array with updated `content_type` → PUT to `app.posts.update` → `UpdatePost::execute` writes `content_type` on `post_platforms`.-5. Preview, warnings, and submit-button gating all read from the live `platformContentTypes` so changes are immediate.-6. At publish time, `InstagramPublisher::publish()` / `FacebookPublisher::publish()` branch on `content_type` (already implemented) and call the correct Graph API endpoint.--## Error Handling--- All card interactions respect `isReadOnly` (published / partially_published posts), consistent with existing patterns.-- If `platformContentTypes[pp.id]` is somehow empty (e.g. legacy row), the card falls back to the prop value, and the compliance computed returns `false`, blocking submit until the user explicitly picks a variant.-- Invalid `content_type` values sent to the backend are rejected by `UpdatePostRequest`'s `Rule::in(ContentType::cases())` validation.--## Testing--- Update or add a feature test for `PostController::update` that submits a payload with `platforms[].content_type = 'instagram_reel'` and asserts the `post_platform` row is updated.-- Add a unit/feature test that `instagram-facebook` platform rows accept Instagram content types (same set as standalone Instagram).-- (Optional) Pest Browser test: open an edit page with an Instagram account connected, click the card, select "Reel", confirm the preview updates and autosave fires.--## Rollout--Single feature branch, single PR. No migration, no config flags. Backend is already capable — this is purely a frontend/UX enablement. Deploying the change instantly unlocks Reel/Story publishing for all users who have an Instagram or Facebook account connected.diff --git a/docs/superpowers/specs/2026-04-23-media-format-matrix-design.md b/docs/superpowers/specs/2026-04-23-media-format-matrix-design.mddeleted file mode 100644index e7991b1ae..000000000--- a/docs/superpowers/specs/2026-04-23-media-format-matrix-design.md+++ /dev/null@@ -1,258 +0,0 @@-# Media Format Matrix for Social Networks--**Date:** 2026-04-23-**Status:** Draft — needs verification of cells marked `?`--Reference map of accepted media formats per platform/variant. Drives the `MediaConverter` service design.--## Images--| Platform / Variant | JPEG | PNG | WebP | GIF | HEIC | Max size | Max dimensions | Aspect ratio | Notes |-|-------------------|------|-----|------|-----|------|----------|----------------|--------------|-------|-| **Instagram Feed** | ✅ | ❌ | ❌ | ❌ | ❌ | ~8 MB | 1920 × 1080 | 4:5 to 1.91:1 | JPEG **only** per official docs. PNG returns error 2207052/2207005. |-| **Instagram Reel** | ❌ | ❌ | ❌ | ❌ | ❌ | — | — | — | **Reel = video only** (media_type REELS requires video_url) |-| **Instagram Story** | ✅ | ❌ | ❌ | ❌ | ❌ | ~8 MB | 1920 × 1080 | 9:16 preferred | JPEG only. Same rules as Feed for image stories. |-| **Facebook Post** | ✅ | ✅ | ? | ? | ❌ | 4 MB | ? | wide range | Postiz maps error 1366046 for size/format violations |-| **Facebook Reel** | ❌ | ❌ | ❌ | ❌ | ❌ | — | — | — | Video only |-| **Facebook Story** | ✅ | ✅ | ? | ? | ❌ | 4 MB | ? | 9:16 preferred | Same as Post format-wise |-| **LinkedIn Post** | ✅ | ✅ | ? | ❌ | ❌ | 5 MB | 6000 × 6000 | wide range | JPEG/PNG safest |-| **LinkedIn Carousel** | ✅ | ✅ | ? | ❌ | ❌ | 5 MB each | 6000 × 6000 | 1:1 to 1:1.91 | Up to 20 images |-| **TikTok Video** | ❌ | ❌ | ❌ | ❌ | ❌ | — | — | — | Video only via this content_type |-| **TikTok Photo** (`auto_add_music`) | ✅ | ✅ | ? | ❌ | ❌ | ? | ? | ? | Postiz has `convertToJPEG: true` |-| **YouTube Shorts** | ❌ | ❌ | ❌ | ❌ | ❌ | — | — | — | Video only |-| **X Post** | ✅ | ✅ | ✅ | ✅ | ❌ | 5 MB | 8192 × 8192 | ≥ 4:1 to ≥ 1:3 | Up to 4 images or 1 video |-| **Threads Post** | ✅ | ✅ | ✅ | ❌ | ❌ | 8 MB | ? | 10:16.5 max | Same as Instagram stack |-| **Pinterest Pin** | ✅ | ✅ | ? | ❌ | ❌ | 20 MB | ? | 2:3 preferred | |-| **Pinterest Carousel** | ✅ | ✅ | ? | ❌ | ❌ | 20 MB | ? | 2:3 preferred | 2–5 images |-| **Bluesky Post** | ✅ | ✅ | ✅ | ✅ | ❌ | **976 KB** | ? | flexible | Postiz auto-resizes to fit 976 KB |-| **Mastodon Post** | ✅ | ✅ | ✅ | ✅ | ❌ | 10 MB (instance-dep) | ? | flexible | Varies by instance |--## Videos--| Platform / Variant | MP4 | MOV | WebM | Max size | Max duration | Min duration | Aspect ratio | Notes |-|-------------------|-----|-----|------|----------|--------------|--------------|--------------|-------|-| **Instagram Feed (video)** | ✅ | ✅ | ❌ | 100 MB | 60 min | 3s | 4:5 to 1.91:1 | Becomes VIDEO or REELS based on aspect |-| **Instagram Reel** | ✅ | ✅ | ❌ | 1 GB | 15 min | 3s | 9:16 preferred | H.264, AAC audio |-| **Instagram Story** | ✅ | ✅ | ❌ | 100 MB | 60s | 3s | 9:16 | |-| **Facebook Post (video)** | ✅ | ✅ | ? | 10 GB | 240 min | — | flexible | Very permissive |-| **Facebook Reel** | ✅ | ✅ | ? | 1 GB | 90s | 3s | 9:16 | |-| **Facebook Story** | ✅ | ✅ | ? | ? | 60s | — | 9:16 | |-| **LinkedIn Post** | ✅ | ? | ? | 5 GB | 10 min | 3s | flexible | |-| **TikTok Video** | ✅ | ✅ | ✅ | max from `creator_info` | max from `creator_info` | 3s | 9:16 preferred | Duration fetched from API per account |-| **YouTube Shorts** | ✅ | ✅ | ✅ | 256 GB | 60s | — | 9:16 | Shorts detection is automatic on vertical vídeo ≤ 60s |-| **X Post (video)** | ✅ | ✅ | ❌ | 512 MB | 140s (std) / 2h 20m (Premium) | 0.5s | wide range | Postiz caps at 2min |-| **Threads Post (video)** | ✅ | ✅ | ❌ | 1 GB | 5 min | — | flexible | |-| **Pinterest Video Pin** | ✅ | ✅ | ❌ | 2 GB | 15 min | 4s | flexible | |-| **Bluesky Post (video)** | ✅ | ✅ | ❌ | 100 MB | 60s | — | flexible | Upload via dedicated endpoint |-| **Mastodon Post (video)** | ✅ | ? | ✅ | 40 MB (instance-dep) | instance-dep | — | flexible | |--## Per-platform "from-to" image normalization--**Philosophy:** every media item passes through the converter before publishing. No env flag. Converter is a no-op when source already matches the platform's accepted set.--| Platform / Variant | Accepted natively (no-op) | Everything else converts to | Also enforces |-|-------------------|---------------------------|-----------------------------|---------------|-| Instagram Feed / Story | JPEG | **JPEG** (q90) | ≤ 1920×1080, aspect 4:5..1.91:1 |-| Instagram Reel | — (video only) | — | — |-| Facebook Post / Story | JPEG | **JPEG** (q90) | ≤ 4 MB |-| Facebook Reel | — (video only) | — | — |-| TikTok Photo mode | JPEG | **JPEG** (q90) | — |-| LinkedIn Post / Carousel | JPEG, PNG | **JPEG** (q90) from WebP/HEIC/GIF | ≤ 5 MB, ≤ 6000×6000 |-| X Post | JPEG, PNG, WebP, GIF | **JPEG** (q90) from HEIC | ≤ 5 MB |-| Threads Post | JPEG, PNG, WebP | **JPEG** (q90) from HEIC/GIF | ≤ 8 MB |-| Pinterest Pin / Carousel | JPEG, PNG | **JPEG** (q90) from WebP/HEIC/GIF | ≤ 20 MB |-| Bluesky Post | JPEG, PNG, WebP, GIF | **JPEG** from HEIC; **iterative resize** if > 976 KB | ≤ 976 KB |-| Mastodon Post | JPEG, PNG, WebP, GIF | **JPEG** (q90) from HEIC | instance-dep |--**Derived rules:**--- **HEIC → always JPEG** (nenhuma plataforma aceita HEIC)-- **WebP → JPEG** para Meta (IG/FB), TikTok Photo, LinkedIn, Pinterest; nativo em X/Threads/Bluesky/Mastodon-- **PNG → JPEG** para Meta + TikTok Photo; nativo no resto-- **GIF → JPEG** (primeiro frame) para Meta + LinkedIn + Pinterest + Threads; nativo em X/Bluesky/Mastodon-- **Animated GIF / Animated WebP**: perde animação quando convertido (limitação v1, flag futuro)--## Video normalization (v1)--**Fora do escopo do converter.** Vídeos passam direto pelo publisher — plataformas validam server-side e a gente surfa erro pro usuário. Transcoding (FFmpeg, codec fix, re-mux) fica pra v2.--## Converter service design--### Service signature--```php-namespace App\Services\Media;--use App\Enums\PostPlatform\ContentType;-use App\Models\Media;--class MediaConverter-{- /**- * Ensure a media item is compatible with the given content_type.- * Returns a Media (original or a newly-created converted copy).- * Idempotent: if the original already complies, returns it as-is.- * Cached: repeated calls for the same (media, content_type) reuse the previously-converted file.- */- public function ensureCompatible(Media $media, ContentType $contentType): Media;-}-```--### Rules catalog--A single class centralizes the "from-to" table above:--```php-final class PlatformMediaRules-{- public function __construct(- public readonly array $acceptedImageMimes, // ['image/jpeg']- public readonly string $targetImageMime, // 'image/jpeg'- public readonly int $targetJpegQuality, // 90- public readonly ?int $maxImageWidth, // 1920- public readonly ?int $maxImageHeight, // 1080- public readonly ?int $maxImageBytes, // 4_000_000- ) {}-- public static function for(ContentType $ct): self { /* match per variant */ }-}-```--### When it's called--Each publisher invokes once, at the top of `publish()`:--```php-public function publish(PostPlatform $pp): array-{- $media = $pp->post->mediaItems->map(- fn ($m) => $this->converter->ensureCompatible($m, $pp->content_type),- );- // continue with normalized $media-}-```--Same pattern in every publisher: Instagram, Facebook, TikTok, LinkedIn, X, Threads, Pinterest, Bluesky, Mastodon, YouTube.--### Pipeline (image)--```-1. Fetch original file from storage-2. Detect real MIME via finfo (not trusting extension)-3. If MIME ∈ acceptedImageMimes AND bytes ≤ maxImageBytes AND dims ≤ max → return original Media (no-op)-4. Else:- a. Load into Intervention\Image- b. Resize if > maxImageWidth/Height (keep aspect)- c. For Bluesky: loop shrinking 10% until bytes ≤ 976 KB (Postiz precedent)- d. Encode to targetImageMime at targetJpegQuality- e. Upload to storage: `converted/{media_id}/{file_hash}/{content_type_value}.jpg`- f. Create Media row pointing at converted file (or return cached row if exists)- g. Return the new Media-```--### Caching / idempotency--Path strategy: `converted/{original_media_id}/{original_file_sha256_prefix}/{content_type_value}.{ext}`--- If original file changes → sha256 differs → new path → fresh conversion-- If same original + same target → path exists → reuse-- DB table `media_conversions` (migration) tracks `(source_media_id, content_type, derived_media_id)` for fast lookup without listing storage--### Failure handling--- Conversion happens inside the publish job (already async/queued).-- On failure, publisher catches and marks `post_platform.status = failed` with a clear error ("Could not convert image for Instagram: PNG to JPEG conversion failed"). Same path as any other publish failure.-- Original media is never mutated or deleted. Converted derivatives are never mutated either.--## Dependencies--- **`intervention/image` v3.x** (composer install)-- PHP GD or Imagick extension (already required by Laravel's `Illuminate/Http/UploadedFile` image validation — safe assumption)-- No new queue, no config changes-- **New migration:** `media_conversions` table--## Decisions (confirmed with user)--1. **Bluesky iterative resize:** replicate Postiz — shrink 10% per iteration until ≤ 976 KB. Done **in memory at publish time**, not stored on CDN (Bluesky API accepts bytes directly).-2. **Converted file storage:** **replace the original in place** at upload time. No parallel `converted/` directory, no `media_conversions` table, no cleanup job. One file per Media, always JPEG.-3. **GIF policy:** accepted only on X, Bluesky, Mastodon. Frontend validation blocks submit when GIF is attached and a GIF-incompatible platform is selected. No silent first-frame conversion.--## Revised pipeline--**Principle:** upload-time touches **only the format** (pixel-perfect). Dimensions and bytes are preserved for maximum platform flexibility (9:16 Reel, 4:5 carousel, etc.). Per-platform size/dimension constraints are handled at publish time in memory, without mutating the CDN original.--### At upload time (asset controller)--```-1. Receive upload-2. Detect real MIME via finfo-3. If MIME is an image AND format ≠ JPEG AND format ≠ GIF:- a. Load into Intervention\Image (keeps original dimensions + aspect)- b. Encode as JPEG q100 (no quality loss — format conversion only) with SAME dimensions- c. Overwrite the original file at `medias/{uuid}.jpg`- d. Save Media row with mime_type='image/jpeg'-4. GIFs: keep as GIF (for X/Bluesky/Mastodon only). Frontend blocks incompatible platforms.-5. JPEG already: no-op, store as-is.-6. Videos: unchanged v1 (passthrough).-```--### At publish time (minimal — no resize except Bluesky)--All publishers pass the **single CDN URL** stored on the Media row. No temporary variants, no resize-for-Graph-API dance, no cleanup jobs.--| Platform | Handling at publish |-|----------|---------------------|-| Instagram, Facebook, LinkedIn, X, Threads, Pinterest, TikTok Photo, YouTube thumb, Mastodon | Pass `media.url` as-is to the platform API. If the platform rejects for dimensions/size, the error surfaces to the user via `post_platform.error_message`. |-| **Bluesky (only exception)** | Bluesky's API accepts raw bytes (not URL). Before upload, check byte size: if > 976 KB, do Postiz-style iterative 10 %-shrink loop **in memory** — shrinks only dimensions (not quality — keeps q100). Loops until ≤ 976 KB. Then upload bytes. No CDN round-trip, no temp files. |--### Filename preservation--- UUID stays the same (`abc-123...`)-- Only the extension changes when the real format changes (`.png` → `.jpg`, `.webp` → `.jpg`)-- The DB `media.path` updates (`medias/abc-123.png` → `medias/abc-123.jpg`)-- Old file is deleted from CDN after the new one is written-- Frontend's `Media` object is returned with the updated URL so the editor displays the right image--Why the extension must change: some platform APIs check extension in addition to Content-Type. Keeping `.png` on a file with JPEG bytes risks inconsistent behavior.--### Frontend validation additions--Update `useMediaRules.ts` to track per-`content_type` GIF acceptance:--| Content type | Accepts GIF? |-|--------------|--------------|-| `x_post` | ✅ |-| `bluesky_post` | ✅ |-| `mastodon_post` | ✅ |-| everything else | ❌ |--Extend `isMediaValidForContentType()` in `Edit.vue` (and per-platform compliance computeds) to reject when media contains a GIF and the current `content_type` doesn't accept it.--## Updated dependencies--- **`intervention/image` v3.x** (composer install)-- No new migrations-- No new tables-- No cleanup job--## Cells still needing verification (`?` in tables)--- Facebook Post/Story image max dimensions + WebP support-- LinkedIn Post/Carousel WebP support-- TikTok Photo mode max size/dimensions-- Pinterest WebP support + max dimensions-- Threads image max dimensions-- Mastodon instance-dependent limits--These gaps don't block — normalizing to JPEG q90 ≤ 1920×1080 ≤ ~4 MB covers all of them comfortably.--## Cells still needing verification (`?` in tables)--- Facebook Post/Story image max dimensions + WebP support-- LinkedIn Post/Carousel WebP support-- TikTok Photo mode max size/dimensions-- Pinterest WebP support + max dimensions-- Threads image max dimensions-- Mastodon instance-dependent limits--These gaps don't block the design — falling back to "convert to JPEG" covers all of them safely.diff --git a/docs/superpowers/specs/2026-04-23-media-pipeline-manual-verification.md b/docs/superpowers/specs/2026-04-23-media-pipeline-manual-verification.mddeleted file mode 100644index dd722e6fa..000000000--- a/docs/superpowers/specs/2026-04-23-media-pipeline-manual-verification.md+++ /dev/null@@ -1,96 +0,0 @@-# Manual verification checklist — media pipeline--After code changes to upload conversion + publish flow, run these checks in the running app.--## Prerequisites--- `npm run dev` running-- User logged into trypost with:- - At least one Instagram account connected (any flow: standalone or via Facebook)- - At least one Facebook Page connected- - At least one Bluesky account (optional, for the resize test)--## Check 1 — PNG upload converts to JPEG at CDN--1. Create a new post (or open an existing draft) at `/posts/*/edit`-2. Upload a **PNG** file (e.g., screenshot, logo with transparency)-3. Open browser devtools → Network tab → find the POST to `assets/store`-4. In the response, verify:- - `mime_type` = `image/jpeg`- - `path` ends with `.jpg`- - `url` ends with `.jpg`-5. Open the `url` in a new tab — confirms the file is served as JPEG--## Check 2 — Metadata propagates--1. Upload an image → response `meta` object has `width` and `height` (> 0)-2. Upload a video → response `meta` has `width`, `height`, `duration` (> 0)-3. If duration is missing for videos, check devtools console for errors during `readFileMetadata`--## Check 3 — Instagram publishing (the original bug)--1. With the JPEG from Check 1, select Instagram (standalone or via Facebook) as target-2. Pick "Feed Post" variant-3. Click **Post now**-4. Wait ~10–30 seconds for the async job-5. Open the Instagram account in a browser/app — the post should appear-6. Back in trypost, `post_platform.status` should be `published` (not `failed`)--## Check 4 — GIF validation (frontend)--1. Upload a `.gif` file-2. Select **Instagram** or **Facebook** — the card should show a red warning: *"This platform does not accept GIF..."*-3. Try clicking "Post now" → button is **disabled**-4. Deselect Instagram/Facebook, select **X** only → warning disappears, button enabled-5. Click "Post now" → GIF publishes to X (animated)--## Check 5 — Video duration validation--1. Upload a video > 60 seconds (e.g., 2min MP4)-2. Select Instagram → pick **Reel** variant-3. Warning shows: *"Video is 2min long, but this post type allows up to 15min"* (Reel is 15min) — no warning expected here-4. Select **Story** instead → warning: *"Video is 2min long, but this post type allows up to 60s"*-5. Submit button disabled--## Check 6 — File size validation--1. Upload a large image (> 4MB JPEG — use a high-res photo)-2. Select **Facebook Post**-3. Warning appears: *"Image exceeds the 4.0 MB limit (yours is X.X MB)"*-4. Submit disabled--## Check 7 — Aspect ratio validation--1. Upload a **square (1:1) image**-2. Select **Instagram Reel**-3. Warning appears: *"Aspect ratio 1.00 is too wide (max 0.60)"* (Reel requires ~9:16)-4. Submit disabled--## Check 8 — Bluesky iterative resize--1. Upload an image > 976 KB that's ALSO a JPEG (not to trigger PNG conversion)-2. Select Bluesky only-3. Click "Post now"-4. Check `storage/logs/laravel.log` for MediaOptimizer entries — should NOT see quality reduction warnings (only dimension reduction if the limit is still exceeded)-5. Post appears on Bluesky with acceptable quality--## Check 9 — Non-normalized video passthrough--1. Upload a `.mp4` file-2. `media.path` in DB/response still has `.mp4` extension (no conversion attempted)-3. Publish to any platform that accepts video — works via existing flow--## Troubleshooting--- If Check 1 fails (still PNG in CDN):- - Check `vendor/bin/composer require intervention/image` is installed- - Check `storage/logs/laravel.log` for `HasMedia: image normalization failed`- - GD or Imagick extension must be loaded in PHP--- If Check 3 still fails on Instagram:- - Verify the stored image IS JPEG: `curl -I <url>` should return `Content-Type: image/jpeg`- - Check Instagram error code in `post_platform.error_message`; 2207009 = aspect ratio, 2207004 = too large--- If videos don't validate in frontend (no warnings):- - Browser must be able to read video metadata (codec-dependent)- - Check devtools console for `readFileMetadata` resolving empty `{}`diff --git a/routes/api.php b/routes/api.phpindex b2d31bd57..e4cad2e63 100644--- a/routes/api.php+++ b/routes/api.php@@ -4,19 +4,26 @@ declare(strict_types=1);use App\Http\Controllers\Api\ApiKeyController;use App\Http\Controllers\Api\LabelController;+use App\Http\Controllers\Api\PlatformController;use App\Http\Controllers\Api\PostController;use App\Http\Controllers\Api\SignatureController;use App\Http\Controllers\Api\SocialAccountController;use App\Http\Controllers\Api\WorkspaceController;use Illuminate\Support\Facades\Route;-Route::prefix('api')->middleware(['auth:api', 'workspace.token', 'throttle:api'])->group(function () {+Route::middleware(['auth:api', 'workspace.token', 'throttle:api'])->group(function () {// PostsRoute::get('/posts', [PostController::class, 'index'])->name('api.posts.index');Route::post('/posts', [PostController::class, 'store'])->name('api.posts.store');Route::get('/posts/{post}', [PostController::class, 'show'])->name('api.posts.show');Route::put('/posts/{post}', [PostController::class, 'update'])->name('api.posts.update');Route::delete('/posts/{post}', [PostController::class, 'destroy'])->name('api.posts.destroy');+ Route::post('/posts/{post}/media', [PostController::class, 'attachMedia'])->name('api.posts.attach-media');+ Route::get('/posts/{post}/metrics', [PostController::class, 'metrics'])->name('api.posts.metrics');+ Route::get('/posts/{post}/preview', [PostController::class, 'preview'])->name('api.posts.preview');++ // Platforms (read-only metadata)+ Route::get('/content-types', [PlatformController::class, 'contentTypes'])->name('api.content-types');// WorkspaceRoute::get('/workspace', [WorkspaceController::class, 'show'])->name('api.workspace.show');diff --git a/tests/Feature/Api/PlatformApiTest.php b/tests/Feature/Api/PlatformApiTest.phpnew file mode 100644index 000000000..204253c6e--- /dev/null+++ b/tests/Feature/Api/PlatformApiTest.php@@ -0,0 +1,35 @@+<?php++declare(strict_types=1);++beforeEach(function () {+ $result = createApiTestToken();+ $this->user = $result['user'];+ $this->workspace = $result['workspace'];+ $this->plainToken = $result['plain_token'];+});++it('lists content types per platform', function () {+ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.content-types'))+ ->assertOk()+ ->assertJsonStructure([+ 'platforms' => [+ '*' => [+ 'platform',+ 'label',+ 'max_content_length',+ 'recommended_content_length',+ 'allowed_media_types',+ 'default_content_type',+ 'content_types' => [+ '*' => ['value', 'label', 'description', 'max_media_count', 'requires_media'],+ ],+ ],+ ],+ ]);+});++it('rejects content-types without auth', function () {+ $this->getJson(route('api.content-types'))->assertUnauthorized();+});diff --git a/tests/Feature/Api/PostMediaApiTest.php b/tests/Feature/Api/PostMediaApiTest.phpnew file mode 100644index 000000000..32ec6491c--- /dev/null+++ b/tests/Feature/Api/PostMediaApiTest.php@@ -0,0 +1,149 @@+<?php++declare(strict_types=1);++use App\Enums\SocialAccount\Platform;+use App\Models\Media;+use App\Models\Post;+use App\Models\PostPlatform;+use App\Models\SocialAccount;+use App\Models\Workspace;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Storage;++beforeEach(function () {+ $result = createApiTestToken();+ $this->user = $result['user'];+ $this->workspace = $result['workspace'];+ $this->plainToken = $result['plain_token'];++ $this->socialAccount = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::LinkedIn,+ ]);++ $this->post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ PostPlatform::factory()->linkedin()->create([+ 'post_id' => $this->post->id,+ 'social_account_id' => $this->socialAccount->id,+ 'enabled' => true,+ ]);++ Storage::fake();+});++it('attaches media from url', function () {+ Http::fake([+ 'cdn.example.com/photo.png' => Http::response(+ file_get_contents(__DIR__.'/../../fixtures/1x1.png'),+ 200,+ ['Content-Type' => 'image/png'],+ ),+ ]);++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->postJson(route('api.posts.attach-media', $this->post), [+ 'urls' => ['https://cdn.example.com/photo.png'],+ ])+ ->assertOk()+ ->assertJsonPath('attached_count', 1)+ ->assertJsonPath('failed_urls', []);++ expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);+ expect($this->post->fresh()->media)->toHaveCount(1);+});++it('reports failures for unreachable urls', function () {+ Http::fake([+ 'cdn.example.com/missing.png' => Http::response(null, 404),+ ]);++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->postJson(route('api.posts.attach-media', $this->post), [+ 'urls' => ['https://cdn.example.com/missing.png'],+ ])+ ->assertOk()+ ->assertJsonPath('attached_count', 0)+ ->assertJsonPath('failed_urls.0', 'https://cdn.example.com/missing.png');+});++it('cannot attach media to a post from another workspace', function () {+ $other = Workspace::factory()->create();+ $post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->postJson(route('api.posts.attach-media', $post), [+ 'urls' => ['https://cdn.example.com/photo.png'],+ ])+ ->assertNotFound();+});++it('previews per platform with sanitized content and length', function () {+ $this->post->update(['content' => str_repeat('a', 500)]);++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.posts.preview', $this->post))+ ->assertOk()+ ->assertJsonStructure([+ 'post_id',+ 'original_content',+ 'original_length',+ 'platforms' => [+ '*' => [+ 'post_platform_id',+ 'platform',+ 'content_type',+ 'sanitized_content',+ 'sanitized_length',+ 'max_content_length',+ 'truncated',+ ],+ ],+ ])+ ->assertJsonPath('original_length', 500);+});++it('returns metrics shape including unsupported reason for unpublished platforms', function () {+ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.posts.metrics', $this->post))+ ->assertOk()+ ->assertJsonStructure([+ 'post_id',+ 'platforms' => [+ '*' => [+ 'post_platform_id',+ 'platform',+ 'status',+ 'platform_post_id',+ 'platform_url',+ 'metrics',+ ],+ ],+ ])+ ->assertJsonPath('platforms.0.metrics.unsupported', true)+ ->assertJsonPath('platforms.0.metrics.reason', 'not_published');+});++it('cannot get metrics from another workspace post', function () {+ $other = Workspace::factory()->create();+ $post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.posts.metrics', $post))+ ->assertNotFound();++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.posts.preview', $post))+ ->assertNotFound();+});++it('rejects attach media payload without urls', function () {+ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->postJson(route('api.posts.attach-media', $this->post), [])+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['urls']);+});diff --git a/tests/Feature/Mcp/AttachMediaFromUrlToolTest.php b/tests/Feature/Mcp/AttachMediaFromUrlToolTest.phpnew file mode 100644index 000000000..76192ae1c--- /dev/null+++ b/tests/Feature/Mcp/AttachMediaFromUrlToolTest.php@@ -0,0 +1,104 @@+<?php++declare(strict_types=1);++use App\Enums\UserWorkspace\Role;+use App\Mcp\Servers\TryPostServer;+use App\Mcp\Tools\Post\AttachMediaFromUrlTool;+use App\Models\Media;+use App\Models\Post;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Storage;++beforeEach(function () {+ $this->user = User::factory()->create();+ $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);+ $this->workspace->members()->attach($this->user->id, ['role' => Role::Member->value]);+ $this->user->update(['current_workspace_id' => $this->workspace->id]);++ $this->post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ Storage::fake();+});++test('attaches an image from url and creates a media row', function () {+ Http::fake([+ 'cdn.example.com/photo.jpg' => Http::response(+ file_get_contents(__DIR__.'/../../fixtures/1x1.png'),+ 200,+ ['Content-Type' => 'image/png'],+ ),+ ]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(AttachMediaFromUrlTool::class, [+ 'post_id' => $this->post->id,+ 'urls' => ['https://cdn.example.com/photo.jpg'],+ ]);++ $response->assertOk();++ expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);+ expect($this->post->fresh()->media)->toHaveCount(1);+});++test('rejects url that returns non-image content type', function () {+ Http::fake([+ 'evil.example.com/payload' => Http::response('not an image', 200, ['Content-Type' => 'text/html']),+ ]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(AttachMediaFromUrlTool::class, [+ 'post_id' => $this->post->id,+ 'urls' => ['https://evil.example.com/payload'],+ ]);++ $response->assertOk();++ expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(0);+ expect($this->post->fresh()->media)->toHaveCount(0);+});++test('reports failures and successes separately', function () {+ Http::fake([+ 'cdn.example.com/ok.png' => Http::response(+ file_get_contents(__DIR__.'/../../fixtures/1x1.png'),+ 200,+ ['Content-Type' => 'image/png'],+ ),+ 'cdn.example.com/missing.png' => Http::response(null, 404),+ ]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(AttachMediaFromUrlTool::class, [+ 'post_id' => $this->post->id,+ 'urls' => [+ 'https://cdn.example.com/ok.png',+ 'https://cdn.example.com/missing.png',+ ],+ ]);++ $response->assertOk()+ ->assertSee(['cdn.example.com/missing.png']);++ expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);+ expect($this->post->fresh()->media)->toHaveCount(1);+});++test('post 404 from another workspace', function () {+ $other = Workspace::factory()->create();+ $post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(AttachMediaFromUrlTool::class, [+ 'post_id' => $post->id,+ 'urls' => ['https://cdn.example.com/photo.jpg'],+ ]);++ $response->assertHasErrors(['Post not found.']);+});diff --git a/tests/Feature/Mcp/PlatformToolTest.php b/tests/Feature/Mcp/PlatformToolTest.phpnew file mode 100644index 000000000..e603f7cf2--- /dev/null+++ b/tests/Feature/Mcp/PlatformToolTest.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++use App\Enums\UserWorkspace\Role;+use App\Mcp\Servers\TryPostServer;+use App\Mcp\Tools\Platform\ListContentTypesTool;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Testing\Fluent\AssertableJson;++beforeEach(function () {+ $this->user = User::factory()->create();+ $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);+ $this->workspace->members()->attach($this->user->id, ['role' => Role::Member->value]);+ $this->user->update(['current_workspace_id' => $this->workspace->id]);+});++test('list content types returns all platforms with constraints', function () {+ $response = TryPostServer::actingAs($this->user)+ ->tool(ListContentTypesTool::class, []);++ $response->assertOk()+ ->assertStructuredContent(function (AssertableJson $json) {+ $json->has('platforms', fn (AssertableJson $platforms) => $platforms+ ->each(fn (AssertableJson $p) => $p+ ->hasAll([+ 'platform',+ 'label',+ 'max_content_length',+ 'recommended_content_length',+ 'allowed_media_types',+ 'default_content_type',+ 'content_types',+ ])+ )+ );+ });+});++test('list content types includes content types per platform', function () {+ $response = TryPostServer::actingAs($this->user)+ ->tool(ListContentTypesTool::class, []);++ $response->assertOk()+ ->assertSee(['linkedin', 'linkedin_post', 'x_post', 'instagram_feed', 'mastodon_post']);+});diff --git a/tests/Feature/Mcp/PostPublishToolTest.php b/tests/Feature/Mcp/PostPublishToolTest.phpnew file mode 100644index 000000000..3185f69fd--- /dev/null+++ b/tests/Feature/Mcp/PostPublishToolTest.php@@ -0,0 +1,202 @@+<?php++declare(strict_types=1);++use App\Enums\Post\Status as PostStatus;+use App\Enums\PostPlatform\ContentType;+use App\Enums\SocialAccount\Platform;+use App\Enums\UserWorkspace\Role;+use App\Jobs\PublishPost;+use App\Mcp\Servers\TryPostServer;+use App\Mcp\Tools\Post\PublishPostTool;+use App\Mcp\Tools\Post\UpdatePostTool;+use App\Models\Post;+use App\Models\PostPlatform;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use App\Models\WorkspaceLabel;+use Illuminate\Support\Facades\Queue;+use Illuminate\Testing\Fluent\AssertableJson;++beforeEach(function () {+ $this->user = User::factory()->create();+ $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);+ $this->workspace->members()->attach($this->user->id, ['role' => Role::Member->value]);+ $this->user->update(['current_workspace_id' => $this->workspace->id]);++ $this->socialAccount = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::LinkedIn,+ ]);+});++// UpdatePostTool++test('update post can change content', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'content' => 'old',+ ]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(UpdatePostTool::class, [+ 'post_id' => $post->id,+ 'content' => 'new content',+ ]);++ $response->assertOk()+ ->assertStructuredContent(function (AssertableJson $json) {+ $json->where('content', 'new content')->etc();+ });++ expect($post->fresh()->content)->toBe('new content');+});++test('update post enables platforms', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ $platform = PostPlatform::factory()->linkedin()->create([+ 'post_id' => $post->id,+ 'social_account_id' => $this->socialAccount->id,+ 'enabled' => false,+ ]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(UpdatePostTool::class, [+ 'post_id' => $post->id,+ 'platforms' => [+ ['id' => $platform->id, 'content_type' => ContentType::LinkedInPost->value],+ ],+ ]);++ $response->assertOk();++ expect($platform->fresh()->enabled)->toBeTrue();+});++test('update post can attach labels', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);+ $label = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(UpdatePostTool::class, [+ 'post_id' => $post->id,+ 'label_ids' => [$label->id],+ ]);++ $response->assertOk();+ expect($post->fresh()->labels()->pluck('id')->all())->toBe([$label->id]);+});++test('update post 404 from another workspace', function () {+ $other = Workspace::factory()->create();+ $post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(UpdatePostTool::class, ['post_id' => $post->id, 'content' => 'x']);++ $response->assertHasErrors(['Post not found.']);+});++test('update post rejects already-published post', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'status' => PostStatus::Published,+ ]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(UpdatePostTool::class, ['post_id' => $post->id, 'content' => 'x']);++ $response->assertHasErrors(['Cannot edit a published post.']);+});++// PublishPostTool++test('publish post immediate dispatches PublishPost job', function () {+ Queue::fake();++ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'status' => PostStatus::Draft,+ ]);++ PostPlatform::factory()->linkedin()->create([+ 'post_id' => $post->id,+ 'social_account_id' => $this->socialAccount->id,+ 'enabled' => true,+ ]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(PublishPostTool::class, ['post_id' => $post->id]);++ $response->assertOk();++ Queue::assertPushed(PublishPost::class);+ expect($post->fresh()->status)->toBe(PostStatus::Publishing);+});++test('publish post scheduled does not dispatch immediately', function () {+ Queue::fake();++ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'status' => PostStatus::Draft,+ ]);++ PostPlatform::factory()->linkedin()->create([+ 'post_id' => $post->id,+ 'social_account_id' => $this->socialAccount->id,+ 'enabled' => true,+ ]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(PublishPostTool::class, [+ 'post_id' => $post->id,+ 'scheduled_at' => '2099-12-31T15:30:00Z',+ ]);++ $response->assertOk();++ Queue::assertNotPushed(PublishPost::class);+ expect($post->fresh()->status)->toBe(PostStatus::Scheduled);+});++test('publish post fails when no platforms enabled', function () {+ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'status' => PostStatus::Draft,+ ]);++ PostPlatform::factory()->linkedin()->create([+ 'post_id' => $post->id,+ 'social_account_id' => $this->socialAccount->id,+ 'enabled' => false,+ ]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(PublishPostTool::class, ['post_id' => $post->id]);++ $response->assertHasErrors(['Post has no enabled platforms. Use update-post-tool to enable at least one platform first.']);+});++test('publish post 404 from another workspace', function () {+ $other = Workspace::factory()->create();+ $post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);++ $response = TryPostServer::actingAs($this->user)+ ->tool(PublishPostTool::class, ['post_id' => $post->id]);++ $response->assertHasErrors(['Post not found.']);+});diff --git a/tests/Feature/Mcp/PostToolTest.php b/tests/Feature/Mcp/PostToolTest.phpindex 823039348..df7977d0f 100644--- a/tests/Feature/Mcp/PostToolTest.php+++ b/tests/Feature/Mcp/PostToolTest.php@@ -95,20 +95,38 @@ test('create post with content and date', function () {$response = TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, ['content' => 'My new post',- 'date' => '2026-04-15',+ 'scheduled_at' => '2099-12-31T15:30:00Z',]);$response->assertOk()->assertStructuredContent(function (AssertableJson $json) {$json->where('content', 'My new post')->where('status', 'draft')- ->where('scheduled_at', '2026-04-15 09:00:00')+ ->where('scheduled_at', '2099-12-31 15:30:00')->etc();});expect(Post::where('workspace_id', $this->workspace->id)->count())->toBe(1);});+test('create post with platforms enables only those', function () {+ $response = TryPostServer::actingAs($this->user)+ ->tool(CreatePostTool::class, [+ 'content' => 'with platforms',+ 'platforms' => [+ ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],+ ],+ ]);++ $response->assertOk();++ $post = Post::where('workspace_id', $this->workspace->id)->first();+ $enabled = $post->postPlatforms()->where('enabled', true)->get();+ expect($enabled)->toHaveCount(1);+ expect($enabled->first()->social_account_id)->toBe($this->socialAccount->id);+ expect($enabled->first()->content_type->value)->toBe('linkedin_post');+});+test('create post without args creates empty draft for today', function () {$response = TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, []);@@ -123,9 +141,9 @@ test('create post without args creates empty draft for today', function () {expect(Post::where('workspace_id', $this->workspace->id)->count())->toBe(1);});-test('create post rejects invalid date format', function () {+test('create post rejects scheduled_at in the past', function () {$response = TryPostServer::actingAs($this->user)- ->tool(CreatePostTool::class, ['date' => 'not-a-date']);+ ->tool(CreatePostTool::class, ['scheduled_at' => '2020-01-01T00:00:00Z']);$response->assertHasErrors();});