From 9a26e6d80212398b193ba7b861ee81384b3a509e Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Mon, 4 May 2026 08:12:28 -0300 Subject: [PATCH 01/19] feat: complete create + publish post flow via MCP and REST API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lets ChatGPT (MCP) and external clients (REST API) drive the full lifecycle of a post — create with platform selection, attach media from URLs, schedule or publish immediately, and fetch engagement metrics — without touching the web UI. MCP tools added: UpdatePostTool, PublishPostTool, AttachMediaFromUrlTool, ListContentTypesTool, GetPostMetricsTool, PreviewPostTool. CreatePostTool now accepts platforms[] + scheduled_at + label_ids; ListPostsTool gains status/search/limit filters. REST endpoints added: POST /api/posts/{post}/media, GET /api/posts/{post}/metrics, GET /api/posts/{post}/preview, GET /api/content-types. Also fixes a silent CreatePost::execute bug — the action validated platforms[] but ignored it, so REST callers never saw their selection persisted. Adds cross validation rules (ContentTypeMatchesPlatform / ContentTypeMatchesPostPlatform) so a LinkedIn account can't be saddled with x_post, and rejects inactive social accounts during validation instead of failing silently downstream. Shared services (PostMetricsFetcher, PostPreviewer, MediaAttacher) back both MCP tools and REST controllers so behaviour stays aligned. New Resources (PlatformContentTypesResource, PostMetricsResource, PostPreviewResource, PostMediaAttachResource) keep controllers free of inline model mapping. Suite: 1.332 passing, 0 failing — covers web (PostControllerTest), REST (PostApiTest, PlatformApiTest, PostMediaApiTest), MCP (66 tool tests), and the publish job (PublishToSocialPlatformTest). Removes /docs from git tracking and TIKTOK_REVIEW_VIDEO_SCRIPT.md. --- TIKTOK_REVIEW_VIDEO_SCRIPT.md | 333 --- app/Actions/Post/CreatePost.php | 76 +- app/Enums/PostPlatform/ContentType.php | 28 +- .../Controllers/Api/PlatformController.php | 24 + app/Http/Controllers/Api/PostController.php | 57 +- app/Http/Controllers/App/PostController.php | 32 +- .../Requests/Api/Post/StorePostRequest.php | 16 +- .../Requests/Api/Post/UpdatePostRequest.php | 8 +- .../Api/PlatformContentTypesResource.php | 50 + .../Resources/Api/PostMediaAttachResource.php | 36 + .../Resources/Api/PostMetricsResource.php | 27 + .../Resources/Api/PostPreviewResource.php | 24 + app/Mcp/Servers/TryPostServer.php | 14 + .../Tools/Platform/ListContentTypesTool.php | 52 + app/Mcp/Tools/Post/AttachMediaFromUrlTool.php | 59 + app/Mcp/Tools/Post/CreatePostTool.php | 45 +- app/Mcp/Tools/Post/GetPostMetricsTool.php | 47 + app/Mcp/Tools/Post/ListPostsTool.php | 48 +- app/Mcp/Tools/Post/PreviewPostTool.php | 44 + app/Mcp/Tools/Post/PublishPostTool.php | 68 + app/Mcp/Tools/Post/UpdatePostTool.php | 84 + app/Rules/ContentTypeMatchesPlatform.php | 61 + app/Rules/ContentTypeMatchesPostPlatform.php | 57 + app/Services/Post/MediaAttacher.php | 186 ++ app/Services/Post/PostMetricsFetcher.php | 76 + app/Services/Post/PostPreviewer.php | 73 + bootstrap/app.php | 2 +- .../2026-04-14-workspace-billing-plans.md | 2223 ----------------- ...26-04-14-workspace-billing-plans-design.md | 322 --- ...4-23-instagram-facebook-variants-design.md | 288 --- .../2026-04-23-media-format-matrix-design.md | 258 -- ...4-23-media-pipeline-manual-verification.md | 96 - routes/api.php | 9 +- tests/Feature/Api/PlatformApiTest.php | 35 + tests/Feature/Api/PostMediaApiTest.php | 149 ++ .../Mcp/AttachMediaFromUrlToolTest.php | 104 + tests/Feature/Mcp/PlatformToolTest.php | 47 + tests/Feature/Mcp/PostPublishToolTest.php | 202 ++ tests/Feature/Mcp/PostToolTest.php | 26 +- 39 files changed, 1787 insertions(+), 3599 deletions(-) delete mode 100644 TIKTOK_REVIEW_VIDEO_SCRIPT.md create mode 100644 app/Http/Controllers/Api/PlatformController.php create mode 100644 app/Http/Resources/Api/PlatformContentTypesResource.php create mode 100644 app/Http/Resources/Api/PostMediaAttachResource.php create mode 100644 app/Http/Resources/Api/PostMetricsResource.php create mode 100644 app/Http/Resources/Api/PostPreviewResource.php create mode 100644 app/Mcp/Tools/Platform/ListContentTypesTool.php create mode 100644 app/Mcp/Tools/Post/AttachMediaFromUrlTool.php create mode 100644 app/Mcp/Tools/Post/GetPostMetricsTool.php create mode 100644 app/Mcp/Tools/Post/PreviewPostTool.php create mode 100644 app/Mcp/Tools/Post/PublishPostTool.php create mode 100644 app/Mcp/Tools/Post/UpdatePostTool.php create mode 100644 app/Rules/ContentTypeMatchesPlatform.php create mode 100644 app/Rules/ContentTypeMatchesPostPlatform.php create mode 100644 app/Services/Post/MediaAttacher.php create mode 100644 app/Services/Post/PostMetricsFetcher.php create mode 100644 app/Services/Post/PostPreviewer.php delete mode 100644 docs/superpowers/plans/2026-04-14-workspace-billing-plans.md delete mode 100644 docs/superpowers/specs/2026-04-14-workspace-billing-plans-design.md delete mode 100644 docs/superpowers/specs/2026-04-23-instagram-facebook-variants-design.md delete mode 100644 docs/superpowers/specs/2026-04-23-media-format-matrix-design.md delete mode 100644 docs/superpowers/specs/2026-04-23-media-pipeline-manual-verification.md create mode 100644 tests/Feature/Api/PlatformApiTest.php create mode 100644 tests/Feature/Api/PostMediaApiTest.php create mode 100644 tests/Feature/Mcp/AttachMediaFromUrlToolTest.php create mode 100644 tests/Feature/Mcp/PlatformToolTest.php create mode 100644 tests/Feature/Mcp/PostPublishToolTest.php diff --git a/TIKTOK_REVIEW_VIDEO_SCRIPT.md b/TIKTOK_REVIEW_VIDEO_SCRIPT.md deleted file mode 100644 index cd781fcc..00000000 --- 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.php index 413bdfbe..d9a48882 100644 --- a/app/Actions/Post/CreatePost.php +++ b/app/Actions/Post/CreatePost.php @@ -9,26 +9,74 @@ 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, + * date?: ?string, + * scheduled_at?: ?string, + * platforms?: array + * } $data + */ public static function execute(Workspace $workspace, User $user, array $data): Post { + $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->postPlatforms() + ->where('social_account_id', $accountId) + ->update($updates); + } + + return $post; + }); + } + + /** + * @param array $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'); - $scheduledAt = Carbon::parse($date, 'UTC') - ->setTime(9, 0) - ->utc(); - $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); - - return $post; + return Carbon::parse($date, 'UTC')->setTime(9, 0)->utc(); } } diff --git a/app/Enums/PostPlatform/ContentType.php b/app/Enums/PostPlatform/ContentType.php index 56973159..15325a99 100644 --- a/app/Enums/PostPlatform/ContentType.php +++ b/app/Enums/PostPlatform/ContentType.php @@ -264,15 +264,39 @@ public static function aiSupported(): array } /** - * 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 + */ + 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 */ 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.php new file mode 100644 index 00000000..0ec9edf1 --- /dev/null +++ b/app/Http/Controllers/Api/PlatformController.php @@ -0,0 +1,24 @@ +json([ + 'platforms' => PlatformContentTypesResource::collection(Platform::cases())->resolve(), + ]); + } +} diff --git a/app/Http/Controllers/Api/PostController.php b/app/Http/Controllers/Api/PostController.php index 3f6f4ab2..e2f6ab17 100644 --- a/app/Http/Controllers/Api/PostController.php +++ b/app/Http/Controllers/Api/PostController.php @@ -10,8 +10,12 @@ 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 @@ public function index(Request $request): AnonymousResourceCollection public 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 @@ public function store(StorePostRequest $request): JsonResponse public 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 @@ public function update(UpdatePostRequest $request, Post $post): PostResource|Jso public 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.php index d906ad95..afeba1df 100644 --- a/app/Http/Controllers/App/PostController.php +++ b/app/Http/Controllers/App/PostController.php @@ -18,22 +18,13 @@ 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 @@ public function platformMetrics(Request $request, Post $post, PostPlatform $post abort(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|RedirectResponse diff --git a/app/Http/Requests/Api/Post/StorePostRequest.php b/app/Http/Requests/Api/Post/StorePostRequest.php index 51b66a29..cbeb3fa3 100644 --- a/app/Http/Requests/Api/Post/StorePostRequest.php +++ b/app/Http/Requests/Api/Post/StorePostRequest.php @@ -6,6 +6,7 @@ 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 @@ public function rules(): array { 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.php index b283660f..29fa072a 100644 --- a/app/Http/Requests/Api/Post/UpdatePostRequest.php +++ b/app/Http/Requests/Api/Post/UpdatePostRequest.php @@ -7,6 +7,7 @@ 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 @@ public function rules(): array '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.php new file mode 100644 index 00000000..1082de9f --- /dev/null +++ b/app/Http/Resources/Api/PlatformContentTypesResource.php @@ -0,0 +1,50 @@ + + */ + 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.php new file mode 100644 index 00000000..8c20d9d3 --- /dev/null +++ b/app/Http/Resources/Api/PostMediaAttachResource.php @@ -0,0 +1,36 @@ +>, failed: array} $result + */ + public function __construct(Post $post, private readonly array $result) + { + parent::__construct($post); + } + + /** + * @return array + */ + 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.php new file mode 100644 index 00000000..6724a00f --- /dev/null +++ b/app/Http/Resources/Api/PostMetricsResource.php @@ -0,0 +1,27 @@ + + */ + 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.php new file mode 100644 index 00000000..3e524bdf --- /dev/null +++ b/app/Http/Resources/Api/PostPreviewResource.php @@ -0,0 +1,24 @@ + + */ + 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.php index 95a2e0d6..6bd9df35 100644 --- a/app/Mcp/Servers/TryPostServer.php +++ b/app/Mcp/Servers/TryPostServer.php @@ -11,10 +11,16 @@ 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 Server ListPostsTool::class, GetPostTool::class, CreatePostTool::class, + UpdatePostTool::class, + PublishPostTool::class, + PreviewPostTool::class, DeletePostTool::class, + AttachMediaFromUrlTool::class, + GetPostMetricsTool::class, + + // Platforms (read-only metadata) + ListContentTypesTool::class, // Signatures ListSignaturesTool::class, diff --git a/app/Mcp/Tools/Platform/ListContentTypesTool.php b/app/Mcp/Tools/Platform/ListContentTypesTool.php new file mode 100644 index 00000000..a7b3b632 --- /dev/null +++ b/app/Mcp/Tools/Platform/ListContentTypesTool.php @@ -0,0 +1,52 @@ + [ + '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.php new file mode 100644 index 00000000..efd65842 --- /dev/null +++ b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php @@ -0,0 +1,59 @@ +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.php index 3350f8ed..4de9ac80 100644 --- a/app/Mcp/Tools/Post/CreatePostTool.php +++ b/app/Mcp/Tools/Post/CreatePostTool.php @@ -5,29 +5,45 @@ 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 @@ public function handle(Request $request): ResponseFactory public 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.php new file mode 100644 index 00000000..b6ceb14f --- /dev/null +++ b/app/Mcp/Tools/Post/GetPostMetricsTool.php @@ -0,0 +1,47 @@ +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.php index dcaea5e4..68d3bc5e 100644 --- a/app/Mcp/Tools/Post/ListPostsTool.php +++ b/app/Mcp/Tools/Post/ListPostsTool.php @@ -4,7 +4,10 @@ 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\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.php new file mode 100644 index 00000000..f4ae064c --- /dev/null +++ b/app/Mcp/Tools/Post/PreviewPostTool.php @@ -0,0 +1,44 @@ +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.php new file mode 100644 index 00000000..e27d9b39 --- /dev/null +++ b/app/Mcp/Tools/Post/PublishPostTool.php @@ -0,0 +1,68 @@ +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.php new file mode 100644 index 00000000..87f576cb --- /dev/null +++ b/app/Mcp/Tools/Post/UpdatePostTool.php @@ -0,0 +1,84 @@ +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.php new file mode 100644 index 00000000..4e6ab851 --- /dev/null +++ b/app/Rules/ContentTypeMatchesPlatform.php @@ -0,0 +1,61 @@ + */ + private array $data = []; + + /** + * @param array $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.php new file mode 100644 index 00000000..b967155a --- /dev/null +++ b/app/Rules/ContentTypeMatchesPostPlatform.php @@ -0,0 +1,57 @@ + */ + private array $data = []; + + /** + * @param array $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.php new file mode 100644 index 00000000..0ccdfd58 --- /dev/null +++ b/app/Services/Post/MediaAttacher.php @@ -0,0 +1,186 @@ + $urls + * @return array{attached: array>, failed: array} + */ + 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 + */ + 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 $allowedTypes + * @return array|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.php new file mode 100644 index 00000000..9f6ba8c4 --- /dev/null +++ b/app/Services/Post/PostMetricsFetcher.php @@ -0,0 +1,76 @@ +|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|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.php new file mode 100644 index 00000000..549491db --- /dev/null +++ b/app/Services/Post/PostPreviewer.php @@ -0,0 +1,73 @@ + + * } + */ + 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> + */ + 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.php index 5629cb14..77e37ac5 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -15,7 +15,7 @@ ->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.md deleted file mode 100644 index 24fff357..00000000 --- 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 -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 - 'Starter', - self::Plus => 'Plus', - self::Pro => 'Pro', - self::Max => 'Max', - }; - } -} -``` - -- [ ] **Step 3: Create Plan model** - -Create `app/Models/Plan.php`: - -```php - 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 -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 - '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 -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 -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 -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 -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 - ['required', 'string', 'max:255'], - ]; - } -} -``` - -Create `app/Http/Requests/App/Brand/UpdateBrandRequest.php`: - -```php - ['required', 'string', 'max:255'], - ]; - } -} -``` - -- [ ] **Step 8: Create BrandController** - -Create `app/Http/Controllers/App/BrandController.php`: - -```php -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 - 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 -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 -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 -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 - */ - 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 -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 -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 -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 -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 - 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 -plan?->social_account_limit ?? 5; - } -} -``` - -Create `app/Features/MemberLimit.php`: - -```php -plan?->member_limit ?? 1; - } -} -``` - -Create `app/Features/BrandLimit.php`: - -```php -plan?->brand_limit ?? 0; - } -} -``` - -Create `app/Features/AiImagesLimit.php`: - -```php -plan?->ai_images_limit ?? 50; - } -} -``` - -Create `app/Features/AiVideosLimit.php`: - -```php -plan?->ai_videos_limit ?? 10; - } -} -``` - -Create `app/Features/DataRetentionDays.php`: - -```php -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 - 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 - 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 - 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 - 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 - 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 - 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 - 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.md deleted file mode 100644 index 7eb33c3c..00000000 --- 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.md deleted file mode 100644 index 673d60f5..00000000 --- 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>( - 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)` — reactive, already present on `main`, for use in `